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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29174cd72a41bad66eb11c1dfbe4cde0c694aa6c | Java | ggj010010/mooncy | /mooncyHome/mooncy/src/main/java/com/spring/mooncy/service/QuService.java | UHC | 724 | 1.875 | 2 | [] | no_license | package com.spring.mooncy.service;
import java.util.List;
import javax.servlet.http.HttpSession;
import com.spring.mooncy.dao.QuDAO;
import com.spring.mooncy.dto.QuVO;
public interface QuService {
// 01. Խñ ۼ
public void create(QuVO vo) throws Exception;
// 02. Խñ
public QuVO read(int q_no) throws Exception;
// 03. Խñ
public void update(QuVO vo) throws Exception;
// 04. Խñ
public void delete(int q_no) throws Exception;
// 05. Խñ ü
public List<QuVO> listAll() throws Exception;
// // 06. Խñ ȸ
// public void increaseViewcnt(int q_no, HttpSession session) throws Exception;
}
| true |
00e9b81efe3ec7e3a9112f72cc6d32910da5bc32 | Java | mauriciorepo/budget | /src/main/java/com/finance/budget/model/OrderService.java | UTF-8 | 2,571 | 2.1875 | 2 | [] | no_license | package com.finance.budget.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class OrderService {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "id_company")
private Company company;
//@OneToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE, CascadeType.MERGE, CascadeType.REMOVE})
//@JoinColumn(name="ORDERSERVICE_ID" , nullable = false)
@OneToMany(mappedBy = "orderService",cascade = {CascadeType.ALL},orphanRemoval = true)
@JsonManagedReference
@OrderBy("numItem ASC")
public List<OrderServiceItems> list=new ArrayList<>();
@NotNull
private String status;
private String orderNumber;
private String description;
@NotNull
private String title;
private String annotation;
@NotNull
private LocalDate registrationDate;
private boolean indorsement;
private LocalDate modified;
@PostPersist
private void noReturn(){
String number=this.company.getId()+"";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YY");
this.setOrderNumber(String.format("%0"+(4-this.company.getId().toString().length())+"d%s",0,number )
.concat(this.getId()+"")
.concat(LocalDate.now().format(formatter)+""));
}
@PrePersist
private void onCreate(){
this.setModified(LocalDate.now());
this.setRegistrationDate(LocalDate.now());
}
@PreUpdate
private void onUpdate(){
this.setModified(LocalDate.now());
}
public void updateItems(List<OrderServiceItems> items){
if(this.list != null){
this.list.retainAll(items);
this.list.addAll(items);
}
}
}
| true |
03629932a16be742e1ff31e3a1883e617e31a4f1 | Java | zach-hu/srr_java8 | /PuridiomCommon/src/com/tsa/puridiom/entity/RecentReqItemPK.java | UTF-8 | 2,666 | 2.359375 | 2 | [] | no_license | package com.tsa.puridiom.entity;
import com.tsa.puridiom.common.utility.HiltonUtility;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
/** @author Hibernate CodeGenerator */
public class RecentReqItemPK implements Serializable {
/** identifier field */
private java.lang.String requisitionerCode;
/** identifier field */
private java.lang.String itemNumber;
/** identifier field */
private java.lang.String itemLocation;
/** full constructor */
public RecentReqItemPK(java.lang.String requisitionerCode, java.lang.String itemNumber, java.lang.String itemLocation) {
this.requisitionerCode = requisitionerCode;
this.itemNumber = itemNumber;
this.itemLocation = itemLocation;
}
/** default constructor */
public RecentReqItemPK() {
}
public java.lang.String getRequisitionerCode() {
return (java.lang.String)HiltonUtility.ckNull(this.requisitionerCode);
}
public void setRequisitionerCode(java.lang.String requisitionerCode) {
this.requisitionerCode = requisitionerCode;
}
public java.lang.String getItemNumber() {
return (java.lang.String)HiltonUtility.ckNull(this.itemNumber);
}
public void setItemNumber(java.lang.String itemNumber) {
this.itemNumber = itemNumber;
}
public java.lang.String getItemLocation() {
return (java.lang.String)HiltonUtility.ckNull(this.itemLocation);
}
public void setItemLocation(java.lang.String itemLocation) {
this.itemLocation = itemLocation;
}
public String toString() {
return new ToStringBuilder(this)
.append("requisitionerCode", getRequisitionerCode())
.append("itemNumber", getItemNumber())
.append("itemLocation", getItemLocation())
.toString();
}
public boolean equals(Object other) {
if ( !(other instanceof RecentReqItemPK) ) return false;
RecentReqItemPK castOther = (RecentReqItemPK) other;
return new EqualsBuilder()
.append(this.getRequisitionerCode(), castOther.getRequisitionerCode())
.append(this.getItemNumber(), castOther.getItemNumber())
.append(this.getItemLocation(), castOther.getItemLocation())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(getRequisitionerCode())
.append(getItemNumber())
.append(getItemLocation())
.toHashCode();
}
}
| true |
29e96d0d30309862c0c5e978a1765cf1ce7ba5b3 | Java | mcooling/javalabs | /Lab 07 (Arrays)/src/myPackage/Ex3TextProcessing.java | UTF-8 | 1,850 | 4.5 | 4 | [] | no_license | package myPackage;
public class Ex3TextProcessing
//CREATE NEW method call
//CREATE NEW method
//create a string variable
//transform the string into an array
//create a counter variable to 'count' the number of times a letter appears
//create a loop counter, to loop through each character in the array
//check if the character in the array is the one we’re searching for (passed in as a parameter)
//if so, increase the counter by 1
//RETURN counter to main method
//TEST method call by printing counter result
{
public static void main(String[] args)
{
//CREATE NEW method call
timesCharOccurs();
//TEST method call by printing counter result
System.out.print(timesCharOccurs());
}
//CREATE NEW method
public static int timesCharOccurs()
{
//create a string variable
String str = "i InsIst on icy indoor IglOos";
//transform the string into an array
char [] stringArray = str.toCharArray(); //uses the .toCharArray() library method
//effectively creates an array with an index of 29, i.e. stringArray[0] = 'i'..stringArray[29] = 's'
int counter = 0; //create counter to store number of times character appears
for (int i = 0; i < stringArray.length; i++) //create loop counter for each letter in the string
//stringArray.length used as the test condition. this means it would work for any string
{
//if statement to check if the value of the array index is the same as the one being checked
//uses 'equals' 'or' operators and Character.toUpperCase() method to include upper case
if(stringArray[i] == 'o' || stringArray[i] == Character.toUpperCase('o'))
{
//if so, increase the counter by 1
counter ++;
}
}
return counter; //RETURN final counter value to main method, once for loop completes
}
}
| true |
8126b7faf3798447a03251ffe5a5acdbd8968793 | Java | kenjs/NightFury | /src/com/TroyEmpire/NightFury/Ghost/Service/MapService.java | UTF-8 | 7,206 | 2.375 | 2 | [] | no_license | package com.TroyEmpire.NightFury.Ghost.Service;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import com.TroyEmpire.NightFury.Constant.DBConstant;
import com.TroyEmpire.NightFury.Constant.Constant;
import com.TroyEmpire.NightFury.Entity.Building;
import com.TroyEmpire.NightFury.Entity.Cell;
import com.TroyEmpire.NightFury.Entity.PathDot;
import com.TroyEmpire.NightFury.Ghost.DBManager.BuildingDBManager;
import com.TroyEmpire.NightFury.Ghost.DBManager.CellDBManager;
import com.TroyEmpire.NightFury.Ghost.DBManager.PathDotDBManager;
import com.TroyEmpire.NightFury.Ghost.DBManager.ShortestPathDBManager;
import com.TroyEmpire.NightFury.Ghost.IService.IMapService;
public class MapService implements IMapService {
private String campusId;
private String dbFile;
private SQLiteDatabase db;
private PathDotService pathDotService;
private CellService cellService;
private BuildingService buildingService;
private ShortestPathService shortestPathService;
final String TAG = "MAP";
public Activity activity;
public MapService(Activity activity) {
this.activity = activity;
// campusId must be first stored in XiaoYuanDTWebView.java
// open database
SharedPreferences sp = activity.getSharedPreferences(
Constant.SHARED_PREFERENCE_MAP_CAMPUS_ID_FILE,
Context.MODE_PRIVATE);
campusId = sp.getString(Constant.SHARED_PREFERENCE_MAP_CMAPUS_ID_KEY,
"");
if (campusId.equals("")) {
Log.e(TAG, "error: can not found campus ID");
} else {
this.dbFile = Constant.NIGHTFURY_STORAGE_ROOT + "/Map/Campus_"
+ campusId + "_Map/MapDB/Map.db";
db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
pathDotService = new PathDotService(Integer.parseInt(campusId));
cellService = new CellService(Integer.parseInt(campusId));
buildingService = new BuildingService(Integer.parseInt(campusId));
shortestPathService = new ShortestPathService(
Integer.parseInt(campusId));
}
}
@Override
public void addToSearchHistory(int cellId) {
SharedPreferences sp = activity.getSharedPreferences(
Constant.SHARED_PREFERENCE_MAP_HISTORY_FILE,
Context.MODE_PRIVATE);
String cellIdString = sp.getString(
Constant.SHARED_PREFERENCE_MAP_HSITORY_KEY, "");
if (cellIdString.equals("")) {
cellIdString = String.valueOf(cellId);
SharedPreferences.Editor editor = sp.edit();
editor.putString(Constant.SHARED_PREFERENCE_MAP_HSITORY_KEY,
cellIdString);
editor.commit();
return;
}
String[] id = cellIdString.split("#");
int newCellIdStringLength = id.length;
boolean cellIdInId = false;// cellId is in id set
for (int i = 0; i < id.length; i++) {
if (Integer.parseInt(id[i]) == cellId) {
int j = i - 1;
for (; j >= 0; j--) {
id[j + 1] = id[j];
}
id[0] = String.valueOf(cellId);
newCellIdStringLength = id.length;
cellIdInId = true;
break;
}
}
// cellId is not in id set,add it to set ,the size of set is at most
// Constant.MAP_LIST_HISTORY_SIZE
if (cellIdInId == false) {
int n = Integer.parseInt(Constant.MAP_LIST_HISTORY_SIZE);
if (n == id.length) {
for (int i = n - 1; i > 0; i--) {
id[i] = id[i - 1];
}
id[0] = String.valueOf(cellId);
newCellIdStringLength = id.length;
} else {
for (int i = id.length; i > 0; i--) {
id[i] = id[i - 1];
}
id[0] = String.valueOf(cellId);
newCellIdStringLength = id.length + 1;
}
}
String newCellIdString = id[0];
for (int i = 1; i < newCellIdStringLength; i++) {
newCellIdString = newCellIdString + "#" + id[i];
}
Log.i(TAG, "in addTOSearchHistory[newCellIdString]:" + newCellIdString);
SharedPreferences.Editor editor = sp.edit();
editor.putString(Constant.SHARED_PREFERENCE_MAP_HSITORY_KEY,
newCellIdString);
editor.commit();
}
@Override
public List<Cell> getSearchHistory() {
List<Cell> cellList = new ArrayList<Cell>();
SharedPreferences sp = activity.getSharedPreferences(
Constant.SHARED_PREFERENCE_MAP_HISTORY_FILE,
Context.MODE_PRIVATE);
String cellIdString = sp.getString(
Constant.SHARED_PREFERENCE_MAP_HSITORY_KEY, "");
if (cellIdString.equals(""))
return cellList;
String[] cellId = cellIdString.split("#");
cellList.clear();
for (int i = 0; i < cellId.length; i++) {
Cell cell = cellService.getCellById(Integer.parseInt(cellId[i]));
cellList.add(cell);
}
return cellList;
}
@Override
public List<Cell> getFrequentPlace() {
int n = Integer.parseInt(Constant.MAP_LIST_FREQUENT_PLACE_SIZE);
Cursor cursor = db.rawQuery(" select "
+ DBConstant.TABLE_FREQUENT_PLACE_FIELD_CELL_ID + " from "
+ DBConstant.TABLE_FREQUENT_PLACE + "," + DBConstant.TABLE_CELL
+ " where " + DBConstant.TABLE_FREQUENT_PLACE + "."
+ DBConstant.TABLE_FREQUENT_PLACE_FIELD_CELL_ID + "="
+ DBConstant.TABLE_CELL + "." + DBConstant.TABLE_CELL_FIELD_ID
+ " order by "
+ DBConstant.TABLE_FREQUENT_PLACE_FIELD_HIT_COUNT
+ " desc limit " + String.valueOf(n), null);
activity.startManagingCursor(cursor);
List<Cell> cellList = new ArrayList<Cell>();
cellList.clear();
// Log.i(TAG,cursor.getColumnName(0));
while (cursor.moveToNext()) {
int id = cursor
.getInt(cursor
.getColumnIndex(DBConstant.TABLE_FREQUENT_PLACE_FIELD_CELL_ID));
Cell cell = this.getCellById(id);
// System.out.println(cell.getName());
cellList.add(cell);
}
cursor.close();
return cellList;
}
@Override
public List<String> getSuggestPlaceName(String pattern) {
String[] columns = { DBConstant.TABLE_CELL_FIELD_ID,
DBConstant.TABLE_CELL_FIELD_NAME,
DBConstant.TABLE_CELL_FIELD_BUILDINGID };
String selection = "name like \'%" + pattern + "%\'";
Cursor cursor = db.query(DBConstant.TABLE_CELL, columns, selection,
null, null, null, null);
List<String> cellList = new ArrayList<String>();
int n = Integer.parseInt(Constant.MAP_LIST_SUGGESTION_SIZE);
int i = 0;
while (cursor.moveToNext()) {
// int id =
// cursor.getInt(cursor.getColumnIndex(DBConstant.TABLE_CELL_FIELD_ID));
String name = cursor.getString(cursor
.getColumnIndex(DBConstant.TABLE_CELL_FIELD_NAME));
// int buildingId =
// cursor.getInt(cursor.getColumnIndex(DBConstant.TABLE_CELL_FIELD_BUILDINGID));
cellList.add(name);
i++;
if (i > n) {
break;
}
}
cursor.close();
return cellList;
}
@Override
public Cell getCellById(int id) {
return cellService.getCellById(id);
}
@Override
public PathDot getPathDotById(int id) {
return pathDotService.getPathDotById(id);
}
@Override
public String getShortestPath(Building sourceBuilding, Building destBuilding) {
return shortestPathService.getShortestPath(sourceBuilding, destBuilding);
}
}
| true |
ff3df8e17b9ad0be9133b27a79120058545cfc70 | Java | Michael-1990/Michael-s-repo | /MFeykLandingPage/Assignment9/src/Question1.java | UTF-8 | 348 | 3.109375 | 3 | [] | no_license | import java.util.*;
public class Question1 {
public void DisplayAll(){
Iterator<String> nameIterator = phoneBook.getKeyIterator();
Iterator<String> numberIterator = phoneBook.getValueIterator();
while (nameIterator.hasNext())
System.out.println(nameIterator.next() + ", " + numberIterator.next());
}
}
| true |
532467d6b3b29faf3196f456c7ed910dbe036fbd | Java | miladomiki/Assignment_6 | /src/abstractFactory/VictorianCoffeeTable.java | UTF-8 | 274 | 3.03125 | 3 | [] | no_license | package abstractFactory;
public class VictorianCoffeeTable implements CoffeeTable{
public VictorianCoffeeTable(){
}
@Override
public void sitAt() {
System.out.println("You sat at the victorian coffe table. You feel wealthy.");
}
}
| true |
9308c55f1d7a89d5f808b66eca7f923648bfd979 | Java | techgurukulbharat/mapstruct | /examples/differentfieldmapping/src/main/java/com/techgurukul/mapstruct/differentfieldmapping/StudentDTO.java | UTF-8 | 559 | 2.46875 | 2 | [] | no_license | package com.techgurukul.mapstruct.differentfieldmapping;
public class StudentDTO {
private String firstName;
private Integer rollNumber;
private String email;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getRollNumber() {
return rollNumber;
}
public void setRollNumber(Integer rollNumber) {
this.rollNumber = rollNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| true |
712cf9118b18f09845bee39a87594018726c62c3 | Java | hdwww/Road-Name | /src/main/java/views/MainController.java | UTF-8 | 2,930 | 2.296875 | 2 | [] | no_license | package views;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import util.Util;
public class MainController {
@FXML
private TextField dongTxt;
@FXML
private TextField numberTxt;
@FXML
private Label label;
@FXML
private Label label2;
@FXML
private Label label3;
private String newZuso = "";
private String oldZuso = "";
private ArrayList<String> zipCode = new ArrayList<String>();
@FXML
private void initialize() {
label.setText("");
label2.setText("");
}
public void zuso() throws IOException {
String dong = dongTxt.getText();
String number = numberTxt.getText();
if(dong.isEmpty() || number.isEmpty()) {
Util.showAlert("에러", "모두 입력해주세요.", AlertType.INFORMATION);
return;
}
String value = dong + " " + number;
StringBuilder urlBuilder = new StringBuilder("http://openapi.epost.go.kr/postal/retrieveNewAdressAreaCdService/retrieveNewAdressAreaCdService/getNewAddressListAreaCd"); /*URL*/
urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8") + "=pqFRCIwlvJWTAC5aXpVAGFANVuVscfsHwVOlV9f2eqSCCMEd1NL3gEp34l39FYSRxn0qEB8Iev5nI2xg3q1dVg%3D%3D"); /*Service Key*/
urlBuilder.append("&" + URLEncoder.encode("searchSe","UTF-8") + "=" + URLEncoder.encode("dong", "UTF-8")); /*dong : 동(읍/면)명 road :도로명[default] post : 우편번호 */
urlBuilder.append("&" + URLEncoder.encode("srchwrd","UTF-8") + "=" + URLEncoder.encode(value, "UTF-8")); /*검색어*/
urlBuilder.append("&" + URLEncoder.encode("countPerPage","UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*페이지당 출력될 개수를 지정*/
urlBuilder.append("&" + URLEncoder.encode("currentPage","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*출력될 페이지 번호*/
try {
Document doc = Jsoup.connect(urlBuilder.toString()).get();
Elements el =doc.getAllElements();
zipCode = (ArrayList<String>) el.select("zipNo").eachText();
newZuso = el.select("lnmAdres").text();
oldZuso = el.select("rnAdres").text();
} catch (Exception e) {
Util.showAlert("에러", "검색중 오류발생", AlertType.ERROR);
}
if(newZuso.length() > 16) {
// newZuso = newZuso.replace(newZuso.charAt(newZuso.charAt(newZuso.indexOf(15))), "\n ");
}
System.out.println(zipCode);
label.setText(newZuso);
label2.setText(oldZuso);
label3.setText(zipCode.get(0));
}
}
| true |
526d5ead936c860a350e4640c5ac052b1e4db69f | Java | ZionTech/cas | /cas-server-core/src/main/java/org/jasig/cas/AbstractCentralAuthenticationService.java | UTF-8 | 13,557 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | package org.jasig.cas;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import org.jasig.cas.authentication.AcceptAnyAuthenticationPolicyFactory;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.ContextualAuthenticationPolicy;
import org.jasig.cas.authentication.ContextualAuthenticationPolicyFactory;
import org.jasig.cas.authentication.principal.DefaultPrincipalFactory;
import org.jasig.cas.authentication.principal.PrincipalFactory;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.logout.LogoutManager;
import org.jasig.cas.logout.LogoutRequest;
import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServiceContext;
import org.jasig.cas.services.ServicesManager;
import org.jasig.cas.services.UnauthorizedProxyingException;
import org.jasig.cas.services.UnauthorizedServiceException;
import org.jasig.cas.support.events.CasTicketGrantingTicketDestroyedEvent;
import org.jasig.cas.ticket.AbstractTicketException;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketFactory;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.UnsatisfiedAuthenticationPolicyException;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.util.Assert;
import com.codahale.metrics.annotation.Counted;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Predicate;
/**
* An abstract implementation of the {@link CentralAuthenticationService} that provides access to
* the needed scaffolding and services that are necessary to CAS, such as ticket registry, service registry, etc.
* The intention here is to allow extensions to easily benefit these already-configured components
* without having to to duplicate them again.
* @author Misagh Moayyed
* @see CentralAuthenticationServiceImpl
* @since 4.2.0
*/
public abstract class AbstractCentralAuthenticationService implements CentralAuthenticationServiceExtended, Serializable,
ApplicationEventPublisherAware {
private static final long serialVersionUID = -7572316677901391166L;
/** Log instance for logging events, info, warnings, errors, etc. */
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/** Application event publisher. */
@Autowired
protected ApplicationEventPublisher eventPublisher;
/** {@link TicketRegistry} for storing and retrieving tickets as needed. */
@NotNull
@Resource(name="ticketRegistry")
protected TicketRegistry ticketRegistry;
/** Implementation of Service Manager. */
@NotNull
@Resource(name="servicesManager")
protected ServicesManager servicesManager;
/** The logout manager. **/
@NotNull
@Resource(name="logoutManager")
protected LogoutManager logoutManager;
/** The ticket factory. **/
@NotNull
@Resource(name="defaultTicketFactory")
protected TicketFactory ticketFactory;
/**
* Authentication policy that uses a service context to produce stateful security policies to apply when
* authenticating credentials.
*/
@NotNull
@Resource(name="authenticationPolicyFactory")
protected ContextualAuthenticationPolicyFactory<ServiceContext> serviceContextAuthenticationPolicyFactory =
new AcceptAnyAuthenticationPolicyFactory();
/** Factory to create the principal type. **/
@NotNull
protected PrincipalFactory principalFactory = new DefaultPrincipalFactory();
/**
* The thread local for TGT.
*/
protected final ThreadLocal<TicketGrantingTicket> threadLocalTGT = new ThreadLocal<TicketGrantingTicket>();
/**
* Instantiates a new Central authentication service impl.
*/
protected AbstractCentralAuthenticationService() {}
/**
* Build the central authentication service implementation.
*
* @param ticketRegistry the tickets registry.
* @param ticketFactory the ticket factory
* @param servicesManager the services manager.
* @param logoutManager the logout manager.
*/
public AbstractCentralAuthenticationService(
final TicketRegistry ticketRegistry,
final TicketFactory ticketFactory,
final ServicesManager servicesManager,
final LogoutManager logoutManager) {
this.ticketRegistry = ticketRegistry;
this.servicesManager = servicesManager;
this.logoutManager = logoutManager;
this.ticketFactory = ticketFactory;
}
public final void setServiceContextAuthenticationPolicyFactory(final ContextualAuthenticationPolicyFactory<ServiceContext> policy) {
this.serviceContextAuthenticationPolicyFactory = policy;
}
public void setTicketFactory(final TicketFactory ticketFactory) {
this.ticketFactory = ticketFactory;
}
/**
* Sets principal factory to create principal objects.
*
* @param principalFactory the principal factory
*/
@Autowired
public final void setPrincipalFactory(@Qualifier("principalFactory")
final PrincipalFactory principalFactory) {
this.principalFactory = principalFactory;
}
/**
* Publish CAS events.
*
* @param e the event
*/
protected final void doPublishEvent(final ApplicationEvent e) {
logger.debug("Publishing {}", e);
this.eventPublisher.publishEvent(e);
}
/**
* Handle TGT destroy.
*
* @param ticket The {@link TicketGrantingTicket}.
* @return The {@link List} of logout requests.
*/
protected List<LogoutRequest> handlerDestroy(final TicketGrantingTicket ticket) {
logger.info("initiated the perform logouts");
final List<LogoutRequest> logoutRequests = logoutManager.performLogout(ticket);
doPublishEvent(new CasTicketGrantingTicketDestroyedEvent(this, ticket));
return logoutRequests;
}
/**
* {@inheritDoc}
*
* Note:
* Synchronization on ticket object in case of cache based registry doesn't serialize
* access to critical section. The reason is that cache pulls serialized data and
* builds new object, most likely for each pull. Is this synchronization needed here?
*/
@Timed(name = "GET_TICKET_TIMER")
@Metered(name = "GET_TICKET_METER")
@Counted(name="GET_TICKET_COUNTER", monotonic=true)
@Override
public final <T extends Ticket> T getTicket(final String ticketId, final Class<? extends Ticket> clazz)
throws InvalidTicketException {
Assert.notNull(ticketId, "ticketId cannot be null");
final Ticket ticket = this.ticketRegistry.getTicket(ticketId, clazz);
if (ticket == null) {
logger.debug("Ticket [{}] by type [{}] cannot be found in the ticket registry.", ticketId, clazz.getSimpleName());
throw new InvalidTicketException(ticketId);
}
if (ticket instanceof TicketGrantingTicket) {
synchronized (ticket) {
if (ticket.isExpired()) {
if(((TicketGrantingTicket) ticket).isRoot())
{
threadLocalTGT.set((TicketGrantingTicket) ticket);
}
this.ticketRegistry.deleteTicket(ticketId);
logger.debug("Ticket [{}] has expired and is now deleted from the ticket registry.", ticketId);
throw new InvalidTicketException(ticketId);
}
}
}
return (T) ticket;
}
@Timed(name = "GET_TICKETS_TIMER")
@Metered(name = "GET_TICKETS_METER")
@Counted(name="GET_TICKETS_COUNTER", monotonic=true)
@Override
public final Collection<Ticket> getTickets(final Predicate<Ticket> predicate) {
final Collection<Ticket> c = new HashSet<>(this.ticketRegistry.getTickets());
final Iterator<Ticket> it = c.iterator();
while (it.hasNext()) {
if (!predicate.apply(it.next())) {
it.remove();
}
}
return c;
}
/**
* Gets the authentication satisfied by policy.
*
* @param ticket the ticket
* @param context the context
* @return the authentication satisfied by policy
* @throws AbstractTicketException the ticket exception
*/
protected final Authentication getAuthenticationSatisfiedByPolicy(
final TicketGrantingTicket ticket, final ServiceContext context) throws AbstractTicketException {
final ContextualAuthenticationPolicy<ServiceContext> policy =
serviceContextAuthenticationPolicyFactory.createPolicy(context);
if (policy.isSatisfiedBy(ticket.getAuthentication())) {
return ticket.getAuthentication();
}
for (final Authentication auth : ticket.getSupplementalAuthentications()) {
if (policy.isSatisfiedBy(auth)) {
return auth;
}
}
throw new UnsatisfiedAuthenticationPolicyException(policy);
}
/**
* Ensure that the service is found and enabled in the service registry.
* @param registeredService the located entry in the registry
* @param service authenticating service
* @throws UnauthorizedServiceException if service is unauthorized
*/
protected final void verifyRegisteredServiceProperties(final RegisteredService registeredService,
final Service service) throws UnauthorizedServiceException {
if (registeredService == null) {
final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
+ "Service [%s] is not found in service registry.", service.getId());
logger.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
if (!registeredService.getAccessStrategy().isServiceAccessAllowed()) {
final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
+ "Service [%s] is not enabled in service registry.", service.getId());
logger.warn(msg);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
}
/**
* Evaluate proxied service if needed.
*
* @param service the service
* @param ticketGrantingTicket the ticket granting ticket
* @param registeredService the registered service
*/
protected final void evaluateProxiedServiceIfNeeded(final Service service, final TicketGrantingTicket ticketGrantingTicket,
final RegisteredService registeredService) {
final Service proxiedBy = ticketGrantingTicket.getProxiedBy();
if (proxiedBy != null) {
logger.debug("TGT is proxied by [{}]. Locating proxy service in registry...", proxiedBy.getId());
final RegisteredService proxyingService = servicesManager.findServiceBy(proxiedBy);
if (proxyingService != null) {
logger.debug("Located proxying service [{}] in the service registry", proxyingService);
if (!proxyingService.getProxyPolicy().isAllowedToProxy()) {
logger.warn("Found proxying service {}, but it is not authorized to fulfill the proxy attempt made by {}",
proxyingService.getId(), service.getId());
throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
+ registeredService.getId());
}
} else {
logger.warn("No proxying service found. Proxy attempt by service [{}] (registered service [{}]) is not allowed.",
service.getId(), registeredService.getId());
throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
+ registeredService.getId());
}
} else {
logger.trace("TGT is not proxied by another service");
}
}
@Override
public void setApplicationEventPublisher(final ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}
public void setTicketRegistry(final TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
public void setServicesManager(final ServicesManager servicesManager) {
this.servicesManager = servicesManager;
}
public void setLogoutManager(final LogoutManager logoutManager) {
this.logoutManager = logoutManager;
}
public TicketRegistry getTicketRegistry() {
return this.ticketRegistry;
}
}
| true |
c802b2aabb67850142deca028d5a467cb3c78d29 | Java | nehamolakallapalli/Inventorymgt | /inventorymgt/src/main/java/com/dxctraining/inventorymgt/item/controller/ComputerController.java | UTF-8 | 2,184 | 2.390625 | 2 | [] | no_license | package com.dxctraining.inventorymgt.item.controller;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.dxctraining.inventorymgt.item.entities.Computer;
import com.dxctraining.inventorymgt.item.entities.Item;
import com.dxctraining.inventorymgt.item.service.IItemService;
import com.dxctraining.inventorymgt.item.dto.*;
import com.dxctraining.inventorymgt.supplier.entities.Supplier;
import com.dxctraining.inventorymgt.supplier.service.*;
@Controller
public class ComputerController
{
@Autowired
private IItemService service1;
@Autowired
private ISupplierService service2;
@PostConstruct
public void init() {
Supplier supplier1=new Supplier("aaaa","1234");
service2.addSupplier(supplier1);
Computer computer1=new Computer("Dell",supplier1,200);
service1.addItem(computer1);
}
@GetMapping("/listallcmp")
public ModelAndView allComputers(){
List<Computer>computer=service1.allComputer();
ModelAndView modelAndView=new ModelAndView("clist","computers",computer);
return modelAndView;
}
@GetMapping("/addcomputer")
public ModelAndView addComputer() {
ModelAndView modelAndView = new ModelAndView("addcomputer");
return modelAndView;
}
@GetMapping("/processaddcomputer")
public ModelAndView processAddComputer(@RequestParam("name")String name, @RequestParam("discsize")int discsize) {
Computer computer = new Computer(name, discsize);
Item item = (Item)computer;
item = service1.addItem(item);
ModelAndView modelAndView = new ModelAndView("processaddcomputer","computers",item);
return modelAndView;
}
@GetMapping("/postaddcomputer")
public ModelAndView postAddComputer() {
CreateComputerRequest computer = new CreateComputerRequest();
ModelAndView modelAndView = new ModelAndView("postaddcomputer","computers",computer);
return modelAndView;
}
}
| true |
6b3d2e6300f8b1833c11b91995ee9b43e493a184 | Java | DeliriumTremens/inna | /inna-sinai-web/src/main/java/com/inna/sinai/web/vo/ReportSearch.java | UTF-8 | 445 | 1.757813 | 2 | [] | no_license | package com.inna.sinai.web.vo;
import java.util.Date;
public class ReportSearch {
private Date initialDate;
private Date finalDate;
public Date getInitialDate() {
return initialDate;
}
public void setInitialDate(Date initialDate) {
this.initialDate = initialDate;
}
public Date getFinalDate() {
return finalDate;
}
public void setFinalDate(Date finalDate) {
this.finalDate = finalDate;
}
}
| true |
8c56f4e8766b07d1b90a295abd9d20acc34eeb7c | Java | huxiaojun0/mu-sso | /spring-ldap-demo/src/main/java/com/muyh/dao/TPermissionMapper.java | UTF-8 | 1,416 | 1.789063 | 2 | [] | no_license | package com.muyh.dao;
import com.muyh.model.TPermission;
public interface TPermissionMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
int insert(TPermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
int insertSelective(TPermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
TPermission selectByPrimaryKey(Integer id);
TPermission selectByRoleid(Integer role_id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(TPermission record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_permission
*
* @mbggenerated
*/
int updateByPrimaryKey(TPermission record);
} | true |
32a07cec9d677bddc48a65be087754a9e0c8411d | Java | HumanLeung/Cloud | /cloud-consumerconsul-order80/src/main/java/com/company/springcloud/OrderConsulMain80.java | UTF-8 | 479 | 1.539063 | 2 | [] | no_license | package com.company.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author HumanLeung
* @create 2021/10/2 13:58
*/
@SpringBootApplication
@EnableDiscoveryClient
public class OrderConsulMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderConsulMain80.class,args);
}
}
| true |
f0df04c6db7d09c9455834069bb6c03454a6d8c7 | Java | rafaela-t/Vendas | /p_corporativos/src/main/java/com/prova/p_corporativos/Model/Cotacao.java | UTF-8 | 1,050 | 2.203125 | 2 | [] | no_license | package com.prova.p_corporativos.Model;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "cotacao")
public class Cotacao extends AbstractEntity{
private float preco_final;
private String prazo_entrega;
private String prazo_pagamento;
@OneToOne
@JoinColumn(name = "produto_id")
private Produto produto;
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public float getPreco_final() {
return preco_final;
}
public void setPreco_final(float preco_final) {
this.preco_final = preco_final;
}
public String getPrazo_entrega() {
return prazo_entrega;
}
public void setPrazo_entrega(String prazo_entrega) {
this.prazo_entrega = prazo_entrega;
}
public String getPrazo_pagamento() {
return prazo_pagamento;
}
public void setPrazo_pagamento(String prazo_pagamento) {
this.prazo_pagamento = prazo_pagamento;
}
}
| true |
e67c782b6b52c2cba5f66be0e27050ff21bc1a83 | Java | Strivema/designPartern | /src/com/xiaowei/factory/simpele/Pizza.java | UTF-8 | 269 | 2 | 2 | [] | no_license | package com.xiaowei.factory.simpele;
/**
* @athour Marie
* @date 2018/11/7 8:24 PM
**/
public abstract class Pizza {
public void prepare(){
}
public void bake(){
}
public void cut(){
}
public void box(){}
public void pizza(){}
}
| true |
09d9f75c29929f906fb892d281a179d9a90222c0 | Java | fuentesj/daily_programmer | /src/challenge293_easy/wirecuttingrules/GreenWireCuttingRule.java | UTF-8 | 560 | 2.640625 | 3 | [] | no_license | package challenge293_easy.wirecuttingrules;
import challenge293_easy.WireColor;
import java.util.Arrays;
import java.util.HashSet;
/**
* Created by Jonathan on 6/16/17.
*/
public class GreenWireCuttingRule extends WireCuttingRule {
public GreenWireCuttingRule() {
this.setCurrentColor(WireColor.GREEN);
this.setAllowedWireColors(new HashSet<>(Arrays.asList(WireColor.ORANGE, WireColor.WHITE)));
this.setDisallowedColors(new HashSet<>(Arrays.asList(WireColor.BLACK, WireColor.PURPLE, WireColor.GREEN, WireColor.RED)));
}
}
| true |
d58d19a92ecdbfc6b41718ce6aadbd9e31cca8d4 | Java | Softkeydel/TestBigApp | /app/src/main/java/com/example/pasari/testbigapp/fragment/CommonFragment.java | UTF-8 | 1,527 | 2.0625 | 2 | [] | no_license | package com.example.pasari.testbigapp.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.pasari.testbigapp.R;
import com.example.pasari.testbigapp.adapter.RecycleViewAdapter;
import com.example.pasari.testbigapp.model.ListItemModel;
import java.util.List;
/**
* Created by pasari on 19/5/17.
*/
public class CommonFragment extends Fragment {
private RecyclerView recyclerView;
private List<ListItemModel> listItemModels;
public CommonFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.common_frag, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(new RecycleViewAdapter(getActivity(),listItemModels));
return view;
}
} | true |
802289a2efadf7d8ae8f479706e3dc7eb6c04aaa | Java | testinfected/simple-petstore | /domain/src/main/java/org/testinfected/petstore/billing/CorrectCardNumber.java | UTF-8 | 1,443 | 2.796875 | 3 | [] | no_license | package org.testinfected.petstore.billing;
import org.testinfected.petstore.validation.Constraint;
import org.testinfected.petstore.validation.Path;
import org.testinfected.petstore.validation.Report;
import java.io.Serializable;
import java.util.regex.Pattern;
public class CorrectCardNumber implements Constraint<String>, Serializable {
private static final String INCORRECT = "incorrect";
private static final Pattern VISA_PATTERN = Pattern.compile("4\\d{12}(\\d{3})?");
private static final Pattern MASTERCARD_PATTERN = Pattern.compile("5[1-5]\\d{14}");
private static final Pattern AMEX_PATTERN = Pattern.compile("3[47]\\d{13}");
private final CreditCardType cardType;
private final String cardNumber;
public CorrectCardNumber(CreditCardType cardType, String cardNumber) {
this.cardType = cardType;
this.cardNumber = cardNumber;
}
public String get() {
return cardNumber;
}
public void check(Path path, Report report) {
if (!satisfied()) report.violation(path, INCORRECT, cardNumber);
}
private boolean satisfied() {
if (cardNumber == null) return false;
if (cardType.equals(CreditCardType.visa)) return VISA_PATTERN.matcher(cardNumber).matches();
if (cardType.equals(CreditCardType.mastercard)) return MASTERCARD_PATTERN.matcher(cardNumber).matches();
return AMEX_PATTERN.matcher(cardNumber).matches();
}
}
| true |
4ba9cb6b38cc547c7ede40b7fbf19f744fb70390 | Java | Shiiiiiy/ams-approveflow | /src/main/java/com/uws/apw/model/MulApproveResult.java | UTF-8 | 515 | 1.976563 | 2 | [] | no_license | package com.uws.apw.model;
import java.util.List;
/**
* 流程审批结果
*/
public class MulApproveResult {
private List<ApproveResult> results;
private String resultFlag;
public List<ApproveResult> getResults() {
return results;
}
public void setResults(List<ApproveResult> results) {
this.results = results;
}
public String getResultFlag() {
return resultFlag;
}
public void setResultFlag(String resultFlag) {
this.resultFlag = resultFlag;
}
}
| true |
7c1afdb96c383a4a214ed939b91b6483fa08e659 | Java | TheMCBrothers/Useful-Machinery | /src/main/java/themcbros/usefulmachinery/container/MachineContainer.java | UTF-8 | 2,341 | 2.4375 | 2 | [
"MIT"
] | permissive | package themcbros.usefulmachinery.container;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.inventory.container.Slot;
import net.minecraft.util.IIntArray;
import themcbros.usefulmachinery.machine.RedstoneMode;
import themcbros.usefulmachinery.tileentity.MachineTileEntity;
import javax.annotation.Nullable;
public class MachineContainer extends Container {
public MachineTileEntity machineTileEntity;
private RedstoneMode mode = RedstoneMode.IGNORED;
protected IIntArray fields;
MachineContainer(@Nullable ContainerType<?> type, int id, PlayerInventory playerInventory, MachineTileEntity tileEntity, IIntArray fields) {
super(type, id);
this.machineTileEntity = tileEntity;
this.fields = fields;
this.trackIntArray(fields);
}
protected void addPlayerSlots(PlayerInventory playerInventory) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
}
for (int k = 0; k < 9; ++k) {
this.addSlot(new Slot(playerInventory, k, 8 + k * 18, 142));
}
}
@Override
public boolean canInteractWith(PlayerEntity playerIn) {
return this.machineTileEntity.isUsableByPlayer(playerIn);
}
public RedstoneMode getRedstoneMode() {
return RedstoneMode.byIndex(this.fields.get(4));
}
public void setRedstoneMode(RedstoneMode mode) {
this.fields.set(4, mode.ordinal());
}
public IIntArray getFields() {
return fields;
}
public int getEnergyStored() {
int lower = this.fields.get(0) & 0xFFFF;
int upper = this.fields.get(1) & 0xFFFF;
return (upper << 16) + lower;
}
public int getMaxEnergyStored() {
int lower = this.fields.get(2) & 0xFFFF;
int upper = this.fields.get(3) & 0xFFFF;
return (upper << 16) + lower;
}
public int getEnergyScaled(int height) {
int i = this.getEnergyStored();
int j = this.getMaxEnergyStored();
return i != 0 && j != 0 ? height * i / j : 0;
}
}
| true |
491080a58bca9e8760de1c2702dd1f3eb78747ad | Java | dehkadehooshmand/android-taxi-driver | /app/src/main/java/ir/idpz/taxi/driver/Adapter/HistoryAdapter.java | UTF-8 | 4,718 | 1.992188 | 2 | [] | no_license | package ir.idpz.taxi.driver.Adapter;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.parisa.viewpager.R;
import java.util.List;
import ir.idpz.taxi.driver.Classes.Request;
import ir.idpz.taxi.driver.Utils.AppController;
import omidi.mehrdad.moalertdialog.MoAlertDialog;
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.MyViewHolder> {
Typeface face = Typeface.createFromAsset(AppController.getAppContext().getAssets(),
"IRANSans(FaNum).ttf");
List<Request> requests;
Request request;
Context mContext;
Activity activity;
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.history_adapter, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
request = requests.get(position);
holder.origin.setText(request.getOrigin());
holder.des.setText(request.getDestination());
holder.name.setText(request.getDrivername());
holder.price.setText(request.getPrice());
holder.detail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public int getItemCount() {
return requests.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView origin, origin_title, des, des_title, price, name, title_name, title_price, detail, support, date;
public MyViewHolder(View view) {
super(view);
origin = view.findViewById(R.id.origin);
origin_title = view.findViewById(R.id.origin_title);
des = view.findViewById(R.id.des);
des_title = view.findViewById(R.id.des_title);
price = view.findViewById(R.id.price);
name = view.findViewById(R.id.name);
title_name = view.findViewById(R.id.title_name);
title_price = view.findViewById(R.id.title_price);
detail = view.findViewById(R.id.detail);
support = view.findViewById(R.id.support);
date = view.findViewById(R.id.date);
detail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog_detail();
}
});
support.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog_support();
}
});
origin_title.setTypeface(face);
des_title.setTypeface(face);
origin.setTypeface(face);
des.setTypeface(face);
support.setTypeface(face);
detail.setTypeface(face);
title_price.setTypeface(face);
title_name.setTypeface(face);
price.setTypeface(face);
name.setTypeface(face);
date.setTypeface(face);
}
}
public HistoryAdapter(List<Request> requests, Activity activity) {
this.requests = requests;
this.activity = activity;
}
public void AlertDialog_detail() {
MoAlertDialog dialog = new MoAlertDialog(activity);
dialog.showSuccessDialog("جزییات", "نمایش جزییات ....");
dialog.setTypeface(face);
dialog.setDilogIcon(R.drawable.ic_support);
dialog.setDialogButtonText("باشه!");
}
public void AlertDialog_support() {
MoAlertDialog dialog = new MoAlertDialog(activity);
dialog.showSuccessDialog("تماس با پشتیبانی", "پیشنهادات و انتقادات خود را از طریق راه های ارتباطی زیر با ما درمیان بگذارید."
+
"\n" +
"آدرس الکترونیکی :"
+
"\n" +
" idpz@yahoo.com " +
"\n"
+
"شماره تماس :" +
"\n" +
"09144454444");
dialog.setTypeface(face);
dialog.setDilogIcon(R.drawable.ic_support);
dialog.setDialogButtonText("باشه!");
}
}
| true |
ab13ddb586825e4fdf73f3c00b9318cde9cf8a8e | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_65f815ec08ecac28e37b72e7b168c3d85e216b16/Game/2_65f815ec08ecac28e37b72e7b168c3d85e216b16_Game_t.java | UTF-8 | 4,002 | 2.0625 | 2 | [] | no_license | /**
* Copyright (C) 2011 Julien SMADJA <julien dot smadja at gmail dot com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.anzymus.neogeo.hiscores.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import com.google.common.base.Objects;
@Entity
@Table(name = "GAME", uniqueConstraints = @UniqueConstraint(columnNames = { "NAME" }))
@NamedQueries({ //
@NamedQuery(name = "game_findAll", query = "SELECT g FROM Game g ORDER BY g.name ASC"), //
@NamedQuery(name = "game_findByName", query = "SELECT g FROM Game g WHERE g.name = :name") //
})
public class Game implements Comparable<Game>, Serializable {
public static final String findAllPlayedGames = "SELECT * FROM GAME WHERE id IN (SELECT DISTINCT game_id FROM SCORE) ORDER BY name";
public static final String findAllGamesPlayedBy = "SELECT * FROM GAME WHERE id IN (SELECT DISTINCT game_id FROM SCORE WHERE player_id = ?) ORDER BY name";
public static final String findAllGamesOneCreditedBy = "SELECT * FROM GAME WHERE id IN (SELECT DISTINCT game_id FROM SCORE WHERE player_id = ? AND all_clear = 1) ORDER BY name";;
public static final String getNumberOfGames = "SELECT COUNT(id) FROM GAME";
public static final String findAllScoreCountForEachGames = "SELECT g.id, g.name, COUNT(s.id) FROM SCORE s, GAME g WHERE s.game_id = g.id GROUP BY g.id ORDER BY g.name";
public static final String findAllUnplayedGames = "SELECT * FROM GAME WHERE id NOT IN (SELECT DISTINCT game_id FROM SCORE) ORDER BY name";
private static final long serialVersionUID = -8252960983109413218L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
private Long postId;
@Column(nullable = true, name = "CUSTOM_STAGE_VALUES")
private String customStageValues;
@Transient
private int contribution;
private boolean improvable;
public Game() {
}
public Game(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Long getPostId() {
return postId;
}
public void setPostId(Long postId) {
this.postId = postId;
}
public String getCustomStageValues() {
return customStageValues;
}
public void setCustomStageValues(String customStageValues) {
this.customStageValues = customStageValues;
}
public boolean isImprovable() {
return improvable;
}
public void setImprovable(boolean improvable) {
this.improvable = improvable;
}
@Override
public int compareTo(Game game) {
return name.compareTo(game.name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Game) {
Game g = (Game) obj;
return name.equals(g.name);
}
return false;
}
@Override
public String toString() {
return name;
}
public int getContribution() {
return contribution;
}
public void setContribution(int contribution) {
this.contribution = contribution;
}
}
| true |
7ebc92db6a0269da7a26472d756cf72af0a0b73b | Java | longxing/AndroidTestDemo | /udpServer/src/com/example/udpserver/UdpThreadTools.java | UTF-8 | 1,385 | 2.390625 | 2 | [] | no_license | package com.example.udpserver;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class UdpThreadTools {
/*** send udp data type **/
public final static int SEND_UDP_DATAGRAM = 0;
public final static int RESPONSE_UDP_DATAGRAM = 1;
public final static int SEND_ONLINE_UDP_MSG = 2;
public final static int SEND_OFFLINE_UDP_MSG = 3;
public final static int SEND_HERATBEAT_DATAPACKET = 4;
/** udp state set param **/
public static int HEARTBEAT_DELAY_TIME = 3000;
public static String SEND_MulticastSocket_IP = "230.0.0.1"; //这些IP地址的范围是224.0.0.0至239.255.255.255
public static int BOX_LISTENING_PORT = 6790;
public static int PHONE_LISTENING_PORT = 6789;
/**
* 发送组播
* @param ipAddress
* @param port
* @param msg
* @throws Exception
*/
public static void sendMulticastSocket(String ipAddress,int port,String msg) throws Exception {
InetAddress group = InetAddress.getByName(ipAddress);
MulticastSocket ms = new MulticastSocket(port);
ms.joinGroup(group);
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.length(),group, port);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
ms.send(dp);
}
Thread.sleep(1000);
}
ms.leaveGroup(group);
}
}
| true |
d00456c9bee7708d7b1dfb70a8f35cf0e56ef479 | Java | kedarvdm/OnlineAuctioning | /OnlineAuctioning/src/Business/Enterprise/AdvertiserEnterprise.java | UTF-8 | 1,373 | 2.1875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Business.Enterprise;
import Business.Advertiser.Advertisement.AdvertisementDirectory;
import Business.Advertiser.DemandSidePlatform.DSPDirectory;
import Business.Role.Role;
import java.util.ArrayList;
/**
*
* @author Sonam
*/
public class AdvertiserEnterprise extends Enterprise {
private AdvertisementDirectory adInventory;
private DSPDirectory dspDirectory;
public AdvertiserEnterprise(String name, EnterpriseType type)
{
super(name,type);
adInventory= new AdvertisementDirectory();
dspDirectory=new DSPDirectory();
}
public AdvertisementDirectory getAdInventory() {
return adInventory;
}
public void setAdInventory(AdvertisementDirectory adInventory) {
this.adInventory = adInventory;
}
public DSPDirectory getDspDirectory() {
return dspDirectory;
}
public void setDspDirectory(DSPDirectory dspDirectory) {
this.dspDirectory = dspDirectory;
}
@Override
public ArrayList<Role> getSupportedRole() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| true |
469b430d1795a504c9865173d1bd9ef55c8a7ee0 | Java | Givou/LoginSystem | /LoginSystem/ActionbarPackage.java | UTF-8 | 683 | 2.125 | 2 | [] | no_license | package LoginSystem;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R3.IChatBaseComponent;
import net.minecraft.server.v1_8_R3.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_8_R3.PacketPlayOutChat;
public class ActionbarPackage {
public void setActionBar(Player player, String message) {
CraftPlayer p = (CraftPlayer) player;
IChatBaseComponent ibc = ChatSerializer.a("{\"text\": \"" + message + "\"}");
PacketPlayOutChat packet = new PacketPlayOutChat(ibc, (byte) 2);
p.getHandle().playerConnection.sendPacket(packet);
}
}
| true |
a8d349ba6fd079187212b78b00e1f70552e3d007 | Java | wulin-challenge/bjhy_data_sync_db | /data-sync-db-example/src/main/java/com/bjhy/db/converter/service/impl/BatchSyncServiceImpl.java | UTF-8 | 4,629 | 1.734375 | 2 | [] | no_license | package com.bjhy.db.converter.service.impl;
import org.springframework.stereotype.Service;
import com.bjhy.data.sync.db.core.BaseAsynchronousBatchCommitCode;
import com.bjhy.data.sync.db.domain.SingleRunEntity;
import com.bjhy.data.sync.db.domain.SyncTemplate;
import com.bjhy.db.converter.listener.BatchSyncListener;
import com.bjhy.db.converter.service.BaseSyncService;
import com.bjhy.db.converter.util.StepUtil;
/**
* 批量同步实现类
* @author wubo
*
*/
@Service
public class BatchSyncServiceImpl extends BaseSyncService{
@Override
public void doRunSync(SingleRunEntity singleRunEntity) {
StepUtil.checkSyncNotNullAndNoJYBHAndSingleThread(singleRunEntity, "SYS_ORGANIZATION", "SYS_ORGANIZATION_NEW", "ID", null, null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_region_sys_region_new", "select * ", "from sys_region", "sys_region_new", "ID", BatchSyncListener.class.getName(), null);
// BaseAsynchronousBatchCommitCode.getInstance().addEmptyOrderTask();
// BaseAsynchronousBatchCommitCode.getInstance().addEmptyOrderTask();
// BaseAsynchronousBatchCommitCode.getInstance().addEmptyOrderTask();
// BaseAsynchronousBatchCommitCode.getInstance().addEmptyOrderTask();
//
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
//
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere2(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
//
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
// StepUtil.checkSyncNotNullWhere3NoOrder(singleRunEntity, "sys_code_sys_code_new", "select * ", "from sys_code", "sys_code_new", "ID", BatchSyncListener.class.getName(), null);
}
@Override
public int order() {
return 0;
}
@Override
public String toTask() {
return "to_old_region_task";
}
@Override
public String fromTask() {
return "from_reverse_to_old_region_task";
}
}
| true |
52da1e91fd6b22d8d1234b57d6b7d66ac75131b3 | Java | cc8848/DessertHouse | /dessertHouse/dessert/src/dessert/dao/ScheduleDao.java | UTF-8 | 1,051 | 2.28125 | 2 | [] | no_license | package dessert.dao;
import java.sql.Date;
import java.util.ArrayList;
import dessert.models.ScheduleDetail;
import dessert.models.WeekSchedule;
public interface ScheduleDao {
public boolean saveSchedule(WeekSchedule schedule);
public WeekSchedule findSchedule(String scheduleId);
public ArrayList<WeekSchedule> retrieveAllSchedule();
public ArrayList<WeekSchedule> retrieveScheduleForStore(String storeId,int state);
public ArrayList<WeekSchedule> retrieveScheduleForStore(String storeId,Date[] period,int state);
public ArrayList<WeekSchedule> retrieveScheduleByState(int scheduleState);
public boolean updateSchedule(WeekSchedule schedule);
public boolean deleteSchedule(WeekSchedule schedule);
public boolean removeSchedule(String scheduleId);
public ArrayList<ScheduleDetail> findScheduleDetail(String scheduleId);
public boolean removeScheduleDetail(String scheduleId);
public boolean saveScheduleDetail(ScheduleDetail scheduleDetail);
public boolean updateScheduleDetail(ScheduleDetail scheduleDetail);
}
| true |
0e6f45be25158ee1eec0e8b708989a400f257476 | Java | allyixi/HuToolTest | /src/test/java/Util/UnicodeUtilTest.java | UTF-8 | 648 | 3.171875 | 3 | [] | no_license | package Util;
import cn.hutool.core.text.UnicodeUtil;
import org.junit.Test;
public class UnicodeUtilTest {
// Unicode编码转换工具
@Test
public void test01() {
// 字符串转Unicode符
//第二个参数true表示跳过ASCII字符(只跳过可见字符)
String s = UnicodeUtil.toUnicode("aaa123中文", true);
// aaa123\u4e2d\u6587
System.out.println(s);
// Unicode转字符串
String str = "aaa\\U4e2d\\u6587\\u111\\urtyu\\u0026";
String res = UnicodeUtil.toString(str);
// 非Unicode字符串,原样输出
System.out.println(res);
}
}
| true |
821b004c087803c4461407db06ab9eb9ed3b0f8a | Java | dc6273632/LGame | /Java/Loon-Neo/src/loon/utils/res/FontSheet.java | UTF-8 | 910 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package loon.utils.res;
import loon.BaseIO;
import loon.Json;
import loon.LRelease;
import loon.LSystem;
import loon.LTexture;
import loon.LTextures;
public class FontSheet implements LRelease {
private TextureAtlas _texAtlas = null;
public LTexture sheet() {
return _texAtlas.img();
}
public TextureData getCharData(char ch) {
String str = String.valueOf(ch);
return _texAtlas.getFrame(str);
}
protected FontSheet(String url) {
Json.Object jsonObj = LSystem.base().json().parse(BaseIO.loadText(url));
String imagePath = url;
LTexture sheet = LTextures.loadTexture(imagePath);
init(jsonObj, sheet);
}
protected FontSheet(Json.Object jsonObj, LTexture sheet) {
init(jsonObj, sheet);
}
protected void init(Json.Object jsonObj, LTexture sheet) {
_texAtlas = new TextureAtlas(sheet, jsonObj);
}
public void close() {
if (_texAtlas != null) {
_texAtlas.close();
}
}
}
| true |
77b0e22e6da8589011e16eca9414cf6d3fb4755d | Java | kang2011/JAVASwingFlashWindow | /src/User32.java | UTF-8 | 834 | 2.078125 | 2 | [] | no_license |
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.platform.win32.WinDef.HWND;
public interface User32 extends Library {
@SuppressWarnings("deprecation")
User32 INSTANCE = (User32) Native.loadLibrary((Platform.isWindows() ? "user32" : "c"), User32.class);
boolean FlashWindow(int hwnd, boolean bInvert);
int SendMessageA(int hwnd, int msg, int wparam, int lparam);
// int FindWindowA(String arg0, String arg1);
void BlockInput(boolean isBlock);
int MessageBoxA(int hWnd, String lpText, int lpCaption, int uType);
//
HWND FindWindowExA(HWND hwndParent, HWND childAfter, String className, String windowName);
HWND FindWindowA(String className, String windowName);
boolean FlashWindow(HWND hWnd, boolean bInvert);
HWND FindWindow(int winClass, String title);
}
| true |
c9dd76fee59604ecb34066078a6633a00117c16c | Java | britolucaspatrick/appbolao | /app/src/main/java/com/example/patri/appbolaoprojeto/CustomAdapter/ArrayAdapterJogoRodada.java | UTF-8 | 1,922 | 2.28125 | 2 | [] | no_license | package com.example.patri.appbolaoprojeto.CustomAdapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.patri.appbolaoprojeto.Entity.JogoRodada;
import com.example.patri.appbolaoprojeto.R;
import com.example.patri.appbolaoprojeto.WS.WSGetEquipe;
import java.util.List;
public class ArrayAdapterJogoRodada extends ArrayAdapter<JogoRodada> {
private List<JogoRodada> list;
private Context context;
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View linha = layoutInflater.inflate(R.layout.layout_item_list_palpite, parent, false);
TextView tvTime1 = linha.findViewById(R.id.tvTime1);
TextView tvTime2 = linha.findViewById(R.id.tvTime2);
tvTime1.setText(WSGetEquipe.getNmComumEquipe(Integer.parseInt(list.get(position).getCdEquipe1())));
tvTime2.setText(WSGetEquipe.getNmComumEquipe(Integer.parseInt(list.get(position).getCdEquipe2())));
return linha;
}
@Override
public void setDropDownViewResource(int resource) {
super.setDropDownViewResource(resource);
}
public ArrayAdapterJogoRodada(@NonNull Context context, int resource, List<JogoRodada> list) {
super(context, resource);
this.list = list;
this.context = context;
}
@Override
public int getPosition(@Nullable JogoRodada item) {
return super.getPosition(item);
}
@Nullable
@Override
public JogoRodada getItem(int position) {
return list.get(position);
}
}
| true |
e21d7d3869e04283ce4fab8a9a7ab73ee4ccd401 | Java | Nefaur/Heatclinic.bdd | /src/test/java/com/heatclinic/junittests/ScriptBaseJUnit.java | UTF-8 | 1,209 | 2.40625 | 2 | [] | no_license | package com.heatclinic.junittests;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.heatclinic.framework.DriverFactory;
import com.heatclinic.pages.PageManager;
import com.heatclinic.tests.TestBase;
import com.heatclinic.utilities.ScreenCapture;
public class ScriptBaseJUnit extends TestBase {
protected ScreenCapture capture=new ScreenCapture();
@BeforeClass
public static void beginTests() {
System.out.println("Starting all tests!");
}
@AfterClass
public static void afterTests() {
System.out.println("Ending all tests!");
}
public void setUp() {
capture.startCapture("target/Video/",this.getClass().getSimpleName(), false);
System.out.println("Opening website.");
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public void tearDown() {
PageManager.getInstance().closePages();
System.out.println("Closing browser.");
capture.endCapture();
try {
DriverFactory.initialize().tearDown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
deaf9fdef82e5146554ebd0d08b37b9100c2ab62 | Java | nfebrian13/invoicescheduler | /SchedulerAppku/src/com/nana/bankapp/entity/CustomerEntity.java | UTF-8 | 3,191 | 2.125 | 2 | [] | no_license | package com.nana.bankapp.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "mst_customer")
public class CustomerEntity {
@Id
@Column(name = "CUSTOMER_ID")
protected String customerId;
@Column(name = "CUSTOMER_NAME")
protected String customerName;
@Column(name = "ADDRESS")
protected String address;
@Column(name = "CITY")
protected String city;
@Column(name = "PROVINCE")
protected String province;
@Column(name = "COUNTRY")
protected String country;
@Column(name = "FAX_NUMBER")
protected String faxNumber;
@Column(name = "PHONE_NUMBER")
protected String phoneNumber;
@Column(name = "POSTAL_CODE")
protected String postalCode;
@Column(name = "CREATED_BY")
protected String createdBy;
@Column(name = "CREATED_DATE")
protected Date createdDate;
@Column(name = "UPDATED_BY")
protected String updatedBy;
@Column(name = "UPDATED_DATE")
protected Date updatedDate;
@Column(name = "EMAIL_ADDRESS")
protected String emailAddress;
public String getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
}
public String getAddress() {
return address;
}
public String getCity() {
return city;
}
public String getProvince() {
return province;
}
public String getCountry() {
return country;
}
public String getFaxNumber() {
return faxNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getPostalCode() {
return postalCode;
}
public String getCreatedBy() {
return createdBy;
}
public Date getCreatedDate() {
return createdDate;
}
public String getUpdatedBy() {
return updatedBy;
}
public Date getUpdatedDate() {
return updatedDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public void setAddress(String address) {
this.address = address;
}
public void setCity(String city) {
this.city = city;
}
public void setProvince(String province) {
this.province = province;
}
public void setCountry(String country) {
this.country = country;
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
| true |
13832f8cccfae505606727348de97b9c7de91994 | Java | philipraath/HangMan | /src/HangmanTUI.java | UTF-8 | 4,847 | 3.59375 | 4 | [] | no_license | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;
public class HangmanTUI extends AbstractHangmanUI {
// protected BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static Scanner scanner = new Scanner(System.in);
/**
* Constructor for objects of class HangmanUI
*/
public HangmanTUI(){
}
public static void main (String[] args)
{
HangmanUIInterface UI = new HangmanTUI();
}
@Override
/**
* Displays welcome message.
*/
public void displayWelcome(){
System.out.println("Welcome to Hangman!!!***Exciting!!!***Exclamation marks!!!!");
}
@Override
/**
* Request user input for current guess.
* @return char
*/
public char askGuess()
{
InputStreamReader reader = new InputStreamReader(System.in);
System.out.println("Please enter a guess: ");
char[] charArray = new char[1];
try {
reader.read(charArray);
}
catch (IOException e)
{
e.printStackTrace();
}
return charArray[0];
}
@Override
/**
* Request user input for the number of guesses allowed.
* @return int
*/
public int askGuessLimit()
{
System.out.println("Please enter the number of guesses allowed: ");
int guessLimit = scanner.nextInt();
return guessLimit;
}
@Override
/**
* Request length of word.
* @return int
*/
public int askWordLength()
{
int wordLength = 0;
System.out.println("Please enter the desired length of word: ");
wordLength = scanner.nextInt();
while(wordLength<2 || wordLength>20) {
System.out.println("Please be sure to choose a length between 2 and 20 or be faced with this message again!");
askWordLength();
}
return wordLength;
}
@Override
/**
* Display current state of game consisting of guesses left, array of previously guess letters,
* and current pattern of blanks and correct guesses.
*
* @param int numberOfGuessesRemaining
* @param Set previousGuesses a set that contains all previous guesses with no duplicate values
* @param ArrayList<Character> currentPattern contains a pattern of letters and blanks
*/
public void displayCurrentState(int numberOfGuessesRemaining, Set<Character> previousGuesses, ArrayList<Character> currentPattern)
{
System.out.println("Guesses remaining: " + numberOfGuessesRemaining);
System.out.println("Previous guesses:" + previousGuesses.toString());
System.out.println("Current: " + currentPattern.toString() );
}
@Override
/**
* Report that current guess is correct.
* @param char currentGuess
*/
public void displayCorrectGuess(char currentGuess)
{
System.out.println("You have chosen wisely!!! There is at least one " + currentGuess + ".");
}
@Override
/**
* Report that current guess is incorrect.
* @param char currentGuess
*/
public void displayIncorrectGuess(char currentGuess)
{
System.out.println("You have chosen poorly!!! There are no " + currentGuess + "'s.");
}
@Override
/**
* Display correct answer.
* @param String correctAnswer
*/
public void displayAnswer(String correctAnswer)
{
System.out.println("The correct answer was: " + correctAnswer + ".");
}
@Override
/**
Display win message.
*/
public void displayWinMessage()
{
System.out.println("Congragulations! You win!");
}
@Override
/**
Display loss message.
*/
public void displayLossMessage()
{
System.out.println("You. Lose. So. Sorry. Stop. Crying.");
}
public void displayAlreadyGuess(char previouslyGuessed)
{
System.out.println("You have already guessed " + previouslyGuessed + ".");
}
@Override
/**
Ask user if they wish to play another game.
* @return boolean true if user requests a new game; false otherwise
*/
public boolean askNewGame()
{
InputStreamReader reader = new InputStreamReader(System.in);
System.out.println("Would you like to play another game? (Y or N)?: ");
char[] charArray = new char[1];
try {
reader.read(charArray);
}
catch (IOException e)
{
e.printStackTrace();
}
while(charArray[0]!='y' && charArray[0]!='Y' && charArray[0]!='n' && charArray[0]!='N')
{
System.out.println("Please restrict your response to 'y' for yes or 'n' for no!");
askNewGame();
}
if(charArray[0]=='y' || charArray[0]=='Y')
{
return true;
}
else
{
return false;
}
}
}
| true |
387ffcba041460999f7c996f9bc2a07d7bb21195 | Java | loipn1804/Beetrack | /app/src/main/java-gen/greendao/SessionDao.java | UTF-8 | 6,944 | 2.1875 | 2 | [] | no_license | package greendao;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import greendao.Session;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table SESSION.
*/
public class SessionDao extends AbstractDao<Session, Long> {
public static final String TABLENAME = "SESSION";
/**
* Properties of entity Session.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Session_id = new Property(0, Long.class, "session_id", true, "SESSION_ID");
public final static Property Company_id = new Property(1, Long.class, "company_id", false, "COMPANY_ID");
public final static Property Name = new Property(2, String.class, "name", false, "NAME");
public final static Property Description = new Property(3, String.class, "description", false, "DESCRIPTION");
public final static Property Session_date = new Property(4, String.class, "session_date", false, "SESSION_DATE");
public final static Property Created_at = new Property(5, String.class, "created_at", false, "CREATED_AT");
public final static Property Updated_at = new Property(6, String.class, "updated_at", false, "UPDATED_AT");
public final static Property Is_chosen = new Property(7, Integer.class, "is_chosen", false, "IS_CHOSEN");
public final static Property F_completed = new Property(8, Integer.class, "f_completed", false, "F_COMPLETED");
};
public SessionDao(DaoConfig config) {
super(config);
}
public SessionDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "'SESSION' (" + //
"'SESSION_ID' INTEGER PRIMARY KEY ," + // 0: session_id
"'COMPANY_ID' INTEGER," + // 1: company_id
"'NAME' TEXT," + // 2: name
"'DESCRIPTION' TEXT," + // 3: description
"'SESSION_DATE' TEXT," + // 4: session_date
"'CREATED_AT' TEXT," + // 5: created_at
"'UPDATED_AT' TEXT," + // 6: updated_at
"'IS_CHOSEN' INTEGER," + // 7: is_chosen
"'F_COMPLETED' INTEGER);"); // 8: f_completed
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'SESSION'";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, Session entity) {
stmt.clearBindings();
Long session_id = entity.getSession_id();
if (session_id != null) {
stmt.bindLong(1, session_id);
}
Long company_id = entity.getCompany_id();
if (company_id != null) {
stmt.bindLong(2, company_id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(3, name);
}
String description = entity.getDescription();
if (description != null) {
stmt.bindString(4, description);
}
String session_date = entity.getSession_date();
if (session_date != null) {
stmt.bindString(5, session_date);
}
String created_at = entity.getCreated_at();
if (created_at != null) {
stmt.bindString(6, created_at);
}
String updated_at = entity.getUpdated_at();
if (updated_at != null) {
stmt.bindString(7, updated_at);
}
Integer is_chosen = entity.getIs_chosen();
if (is_chosen != null) {
stmt.bindLong(8, is_chosen);
}
Integer f_completed = entity.getF_completed();
if (f_completed != null) {
stmt.bindLong(9, f_completed);
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/** @inheritdoc */
@Override
public Session readEntity(Cursor cursor, int offset) {
Session entity = new Session( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // session_id
cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1), // company_id
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // name
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // description
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // session_date
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // created_at
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // updated_at
cursor.isNull(offset + 7) ? null : cursor.getInt(offset + 7), // is_chosen
cursor.isNull(offset + 8) ? null : cursor.getInt(offset + 8) // f_completed
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, Session entity, int offset) {
entity.setSession_id(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setCompany_id(cursor.isNull(offset + 1) ? null : cursor.getLong(offset + 1));
entity.setName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setDescription(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setSession_date(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setCreated_at(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setUpdated_at(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setIs_chosen(cursor.isNull(offset + 7) ? null : cursor.getInt(offset + 7));
entity.setF_completed(cursor.isNull(offset + 8) ? null : cursor.getInt(offset + 8));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(Session entity, long rowId) {
entity.setSession_id(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(Session entity) {
if(entity != null) {
return entity.getSession_id();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
| true |
e9c658b811fa815512f6175a385ba0a5a5f9af65 | Java | suleymanozay/Project1 | /src/test/java/com/syntax/pages/AddDependentsPageWebElements.java | UTF-8 | 682 | 1.921875 | 2 | [] | no_license | package com.syntax.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.syntax.utils.CommonMethods;
public class AddDependentsPageWebElements extends CommonMethods{
@FindBy(id = "dependent_name")
public WebElement depName;
@FindBy(id="dependent_relationshipType")
public WebElement depRelation;
@FindBy(id="dependent_dateOfBirth")
public WebElement depDOB;
@FindBy(id="btnSaveDependent")
public WebElement saveBtn;
@FindBy(id="btnAddDependent")
public WebElement addBtn;
public AddDependentsPageWebElements() {
PageFactory.initElements(driver, this);
}
} | true |
4019f8ea84a2b5efe64ee89e3e0b63674c9a1398 | Java | SzuMusic/SzuMusicApp | /SzuMusicApp/app/src/main/java/com/szumusic/szumusicapp/ui/widget/CircleView.java | UTF-8 | 3,892 | 2.21875 | 2 | [] | no_license | package com.szumusic.szumusicapp.ui.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.WindowManager;
import android.widget.ImageView;
import com.szumusic.szumusicapp.R;
import com.szumusic.szumusicapp.utils.ImageUtils;
/**
* Created by kobe_xuan on 2017/2/5.
*/
public class CircleView extends ImageView {
private int width;
private int mradius;
private BitmapShader mbitmapShader;
private Matrix matrix;
private Paint mBitmapPaint;
private Paint mBorderPaint;
private float mstrokeWidth;
private int mstrokeColor;
private Bitmap mDiscBitmap;
public CircleView(Context context) {
super(context);
}
public CircleView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs,0);
}
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs,defStyleAttr);
}
private void init(AttributeSet attrs, int defStyle){
matrix=new Matrix();
mBitmapPaint=new Paint();
mBorderPaint=new Paint();
mBitmapPaint.setAntiAlias(true);
mDiscBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.play_page_default_cover);
//获取属性
TypedArray typedArray=getContext().obtainStyledAttributes(attrs,R.styleable.CircleView);
mstrokeWidth=typedArray.getDimension(R.styleable.CircleView_strokeWidth,0);
mstrokeColor=typedArray.getColor(R.styleable.CircleView_strokeColor,Color.WHITE);
typedArray.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
System.out.println();
width=Math.min(getMeasuredHeight(),getMeasuredWidth());
mradius=width/2;
mradius= (int) (mradius-mstrokeWidth/2);
setMeasuredDimension(width,width);
System.out.println("图片的宽度为"+mDiscBitmap.getWidth());
System.out.println("屏幕的宽度为"+getMeasuredWidth());
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable()==null)
return;
setBitmapShader();
canvas.drawCircle(width/2,width/2,mradius,mBitmapPaint);
setmBorderPaint();
canvas.drawCircle(width/2,width/2,mradius,mBorderPaint);
}
private void setBitmapShader(){
Drawable drawable=getDrawable();
if(drawable==null)
return ;
BitmapDrawable bd= (BitmapDrawable) drawable;
Bitmap bitmap=bd.getBitmap();
mbitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale=1.0f;
int bitmapsize=Math.min(bitmap.getWidth(),bitmap.getHeight());
scale=width*1.0f/bitmapsize;
matrix.setScale(scale,scale);
mbitmapShader.setLocalMatrix(matrix);
mBitmapPaint.setShader(mbitmapShader);
}
private void setmBorderPaint(){
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setColor(mstrokeColor);
mBorderPaint.setStrokeCap(Paint.Cap.ROUND);
mBorderPaint.setAlpha((int) 0.5);
mBorderPaint.setStrokeWidth(mstrokeWidth);
}
private int getScreenWidth() {
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
return wm.getDefaultDisplay().getWidth();
}
}
| true |
c45495a1b4fc3b0d09393599726d248ba4c738cc | Java | lukaszog/WzB | /src/main/java/pl/lenda/marcin/wzb/repository/Reserved_ItemsRepository.java | UTF-8 | 570 | 1.921875 | 2 | [] | no_license | package pl.lenda.marcin.wzb.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import pl.lenda.marcin.wzb.entity.Reserved_Items;
import java.util.List;
/**
* Created by Promar on 26.11.2016.
*/
@Repository
public interface Reserved_ItemsRepository extends MongoRepository<Reserved_Items, String> {
List<Reserved_Items> findAll();
Reserved_Items findById(String id);
void delete(Reserved_Items reserved_items);
List<Reserved_Items> findByNameTeam(String nameTeam);
}
| true |
e9c1bd6416770b0c9914068052f4624e4724c09c | Java | lishulongVI/leetcode | /java/680.Valid Palindrome II(验证回文字符串 Ⅱ).java | UTF-8 | 1,738 | 3.546875 | 4 | [
"MIT"
] | permissive | /**
<p>
Given a non-empty string <code>s</code>, you may delete <b>at most</b> one character. Judge whether you can make it a palindrome.
</p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> "aba"
<b>Output:</b> True
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> "abca"
<b>Output:</b> True
<b>Explanation:</b> You could delete the character 'c'.
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>The string will only contain lowercase characters a-z.
The maximum length of the string is 50000.</li>
</ol>
</p><p>给定一个非空字符串 <code>s</code>,<strong>最多</strong>删除一个字符。判断是否能成为回文字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> "aba"
<strong>输出:</strong> True
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> "abca"
<strong>输出:</strong> True
<strong>解释:</strong> 你可以删除c字符。
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。</li>
</ol>
<p>给定一个非空字符串 <code>s</code>,<strong>最多</strong>删除一个字符。判断是否能成为回文字符串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> "aba"
<strong>输出:</strong> True
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> "abca"
<strong>输出:</strong> True
<strong>解释:</strong> 你可以删除c字符。
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>字符串只包含从 a-z 的小写字母。字符串的最大长度是50000。</li>
</ol>
**/
class Solution {
public boolean validPalindrome(String s) {
}
} | true |
16a5301bca11810dca4cecbe768eea7c1fc86198 | Java | nathan-devroy1217/FantasyFootballDataModule | /src/main/java/com/nathan/FantasyFootballDataModule/dao/impl/RosterWeekDaoImpl.java | UTF-8 | 1,644 | 2.328125 | 2 | [] | no_license | package com.nathan.FantasyFootballDataModule.dao.impl;
import com.nathan.FantasyFootballDataModule.dao.IRosterWeekDao;
import com.nathan.FantasyFootballDataModule.model.RosterWeek;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class RosterWeekDaoImpl implements IRosterWeekDao {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
final String INSERT_QUERY = "insert into rosterWeek(playerRosterYearId, week, teamId, playerKey) " +
"values (:playerRosterYearId, :week, :teamId, :playerKey)";
@Override
public RosterWeek insertIntoRosterWeek(RosterWeek rosterWeek) {
KeyHolder holder = new GeneratedKeyHolder();
SqlParameterSource parameters = new MapSqlParameterSource()
.addValue("playerRosterYearId", rosterWeek.getPlayerRosterYearId())
.addValue("week", rosterWeek.getWeek())
.addValue("teamId", rosterWeek.getTeamId())
.addValue("playerKey",rosterWeek.getPlayerKey());
namedParameterJdbcTemplate.update(INSERT_QUERY, parameters, holder);
return rosterWeek;
}
}
| true |
2596f4013e6e41fef0494c76a610823d2d21cb0b | Java | unica-open/siacbilitf | /src/main/java/it/csi/siac/siacfinser/frontend/webservice/msg/LeggiTreeContoEconomico.java | UTF-8 | 1,100 | 1.820313 | 2 | [] | no_license | /*
*SPDX-FileCopyrightText: Copyright 2020 | CSI Piemonte
*SPDX-License-Identifier: EUPL-1.2
*/
package it.csi.siac.siacfinser.frontend.webservice.msg;
import javax.xml.bind.annotation.XmlType;
import it.csi.siac.siaccorser.model.ServiceRequest;
import it.csi.siac.siacfinser.frontend.webservice.FINSvcDictionary;
/**
* Messaggio di richiesta per leggere il tree piano dei conti
*
* @author rmontuori
*
*/
@XmlType(namespace = FINSvcDictionary.NAMESPACE)
public class LeggiTreeContoEconomico extends ServiceRequest {
private Integer anno;
private Integer idEnteProprietario;
private Integer idCodificaPadre;
public Integer getAnno() {
return anno;
}
public void setAnno(Integer anno) {
this.anno = anno;
}
public Integer getIdEnteProprietario() {
return idEnteProprietario;
}
public void setIdEnteProprietario(Integer idEnteProprietario) {
this.idEnteProprietario = idEnteProprietario;
}
public Integer getIdCodificaPadre() {
return idCodificaPadre;
}
public void setIdCodificaPadre(Integer idCodificaPadre) {
this.idCodificaPadre = idCodificaPadre;
}
}
| true |
963d37c272f1d349dd5254070bd5ce11096d1712 | Java | martinmallen/sistema_ventas | /src/main/java/cl/accenture/curso_java/sistema_ventas/controlador/CrearUsuarioCtrl.java | UTF-8 | 6,452 | 1.976563 | 2 | [] | no_license | /**
*
*/
package cl.accenture.curso_java.sistema_ventas.controlador;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import cl.accenture.curso_java.sistema_ventas.dao.SucursalDAO;
import cl.accenture.curso_java.sistema_ventas.dao.UsuarioDAO;
import cl.accenture.curso_java.sistema_ventas.excepciones.SinConexionException;
import cl.accenture.curso_java.sistema_ventas.modelo.Perfil;
import cl.accenture.curso_java.sistema_ventas.modelo.Sucursal;
import cl.accenture.curso_java.sistema_ventas.modelo.Usuario;
import cl.accenture.curso_java.sistema_ventas.servicios.SHAServices;
/**
* @author Martin Cuevas
*
*/
@ManagedBean
@RequestScoped
public class CrearUsuarioCtrl implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2570733654212148470L;
private String nombre;
private String apellido;
private String password;
private String email;
private String rut;
private boolean estado;
private String perfil_nombre;
private int idSucursal;
private String mensaje;
private List<Sucursal> sucursales;
private String confMail;
private String confPass;
/**
*
*/
public CrearUsuarioCtrl() {
this.nombre = "";
this.apellido = "";
this.password = "";
this.email = "";
this.rut = "";
this.estado = true;
this.perfil_nombre = "";
this.idSucursal = 0;
this.mensaje = "";
obtenerSucursales();
}
/**
* @param nombre
* @param apellido
* @param password
* @param email
* @param rut
* @param estado
* @param perfil_nombre
* @param idSucursal
* @param mensaje
*/
public CrearUsuarioCtrl(String nombre, String apellido, String password, String email, String rut, boolean estado,
String perfil_nombre, int idSucursal, String mensaje) {
this.nombre = nombre;
this.apellido = apellido;
this.password = password;
this.email = email;
this.rut = rut;
this.estado = estado;
this.perfil_nombre = perfil_nombre;
this.idSucursal = idSucursal;
this.mensaje = mensaje;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre
* the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the apellido
*/
public String getApellido() {
return apellido;
}
/**
* @param apellido
* the apellido to set
*/
public void setApellido(String apellido) {
this.apellido = apellido;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the rut
*/
public String getRut() {
return rut;
}
/**
* @param rut
* the rut to set
*/
public void setRut(String rut) {
this.rut = rut;
}
/**
* @return the estado
*/
public boolean isEstado() {
return estado;
}
/**
* @param estado
* the estado to set
*/
public void setEstado(boolean estado) {
this.estado = estado;
}
/**
* @return the perfil_nombre
*/
public String getPerfil_nombre() {
return perfil_nombre;
}
/**
* @param perfil_nombre
* the perfil_nombre to set
*/
public void setPerfil_nombre(String perfil_nombre) {
this.perfil_nombre = perfil_nombre;
}
/**
* @return the idSucursal
*/
public int getIdSucursal() {
return idSucursal;
}
/**
* @param idSucursal
* the idSucursal to set
*/
public void setIdSucursal(int idSucursal) {
this.idSucursal = idSucursal;
}
/**
* @return the mensaje
*/
public String getMensaje() {
return mensaje;
}
/**
* @param mensaje
* the mensaje to set
*/
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
/**
* @return the sucursales
*/
public List<Sucursal> getSucursales() {
return sucursales;
}
/**
* @param sucursales
* the sucursales to set
*/
public void setSucursales(List<Sucursal> sucursales) {
this.sucursales = sucursales;
}
/**
* @return the confMail
*/
public String getConfMail() {
return confMail;
}
/**
* @param confMail
* the confMail to set
*/
public void setConfMail(String confMail) {
this.confMail = confMail;
}
/**
* @return the confPass
*/
public String getConfPass() {
return confPass;
}
/**
* @param confPass
* the confPass to set
*/
public void setConfPass(String confPass) {
this.confPass = confPass;
}
public void guardarUsuario() {
if ((this.password.equals(this.confPass) && this.email.equals(this.confMail))) {
String encriptado = "";
try {
encriptado = SHAServices.encriptacion(this.password);
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Usuario usuario = new Usuario(this.rut, this.nombre, encriptado, this.email, new Perfil(this.perfil_nombre),
this.apellido, this.idSucursal);
UsuarioDAO dao = new UsuarioDAO();
try {
dao.ingresarUsuario(usuario);
limpiar();
this.mensaje = "Usuario Creado Correctamente";
} catch (SQLException e) {
this.mensaje = "Error en la busqueda";
e.printStackTrace();
} catch (SinConexionException e) {
this.mensaje = "Error en la conexion";
e.printStackTrace();
}
}else {
this.email = "";
this.confMail = "";
this.mensaje = "Email o Password no Coinciden";
}
}
public void obtenerSucursales() {
SucursalDAO sdao = new SucursalDAO();
try {
this.setSucursales(sdao.obtenerSucursales());
this.mensaje = "";
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SinConexionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String cancelar() {
limpiar();
return "principal.xhtml";
}
public void limpiar() {
this.nombre = "";
this.apellido = "";
this.password = "";
this.email = "";
this.rut = "";
this.estado = true;
this.perfil_nombre = "";
this.idSucursal = 0;
this.mensaje = "";
}
}
| true |
080e109cdb6201906dc7bcf52fb24f4dd61a4340 | Java | oyorooms/hue | /desktop/core/ext-py/py4j-0.9/py4j-java/test/py4j/model/ModelTester.java | UTF-8 | 4,334 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* Copyright (c) 2010, 2011, Barthelemy Dagenais All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - 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.
*
* - The name of the author may not 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 HOLDER 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 py4j.model;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import p1.AnObject;
import p1.AnObject2;
import p1.AnObject3;
import p1.AnObject4;
public class ModelTester {
@Test
public void testModel() {
Py4JClass clazz = Py4JClass.buildClass(AnObject.class, true);
assertEquals(clazz.getSignature(false), "p1.AnObject");
assertEquals(clazz.getSignature(true), "AnObject");
assertEquals(1, clazz.getClasses().length);
assertEquals(2, clazz.getMethods().length);
assertEquals(1, clazz.getFields().length);
Py4JMethod m1 = clazz.getMethods()[0];
Py4JMethod m2 = clazz.getMethods()[1];
Py4JField f1 = clazz.getFields()[0];
Py4JClass clazz2 = clazz.getClasses()[0];
assertEquals(m1.getSignature(false),
"m1(java.lang.String, p1.AnObject) : void");
assertEquals(m1.getSignature(true), "m1(String, AnObject) : void");
assertEquals(m2.getSignature(false), "m2(int) : java.lang.String");
assertEquals(m2.getSignature(true), "m2(int) : String");
assertEquals(f1.getSignature(false), "value1 : java.lang.Integer");
assertEquals(f1.getSignature(true), "value1 : Integer");
assertEquals(clazz2.getSignature(false), "p1.AnObject.InternalClass");
assertEquals(clazz2.getSignature(true), "InternalClass");
}
@Test
public void testClassWithSuper() {
Py4JClass clazz2 = Py4JClass.buildClass(AnObject2.class, true);
Py4JClass clazz3 = Py4JClass.buildClass(AnObject3.class, true);
Py4JClass clazz4 = Py4JClass.buildClass(AnObject4.class, true);
assertEquals(clazz2.getSignature(false),
"p1.AnObject2 extends p1.AnObject");
assertEquals(clazz3.getSignature(false),
"p1.AnObject3 implements java.lang.Runnable, java.io.Serializable");
assertEquals(clazz4.getSignature(false),
"p1.AnObject4 extends p1.AnObject3 implements java.lang.Cloneable");
}
@Test
public void testClassHelpPage() {
// This is manual testing, to see how it will look like.
Py4JClass clazz = Py4JClass.buildClass(AnObject.class, true);
String helpPage = HelpPageGenerator.getHelpPage(clazz, null, false);
System.out.println("BEGIN");
System.out.println(helpPage);
System.out.println("END");
helpPage = HelpPageGenerator.getHelpPage(clazz, null, true);
System.out.println("BEGIN");
System.out.println(helpPage);
System.out.println("END");
}
@Test
public void testMethodHelpPage() {
// This is manual testing, to see how it will look like.
Py4JClass clazz = Py4JClass.buildClass(AnObject.class, true);
String helpPage = HelpPageGenerator.getHelpPage(clazz.getMethods()[0],
false);
System.out.println("BEGIN");
System.out.println(helpPage);
System.out.println("END");
}
}
| true |
3a514ce646fcd1fe4c6b41fd355d0a8ab8663c2f | Java | cha63506/CompSecurity | /JC-Penney/src/com/android/b/ac.java | UTF-8 | 569 | 1.546875 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.android.b;
// Referenced classes of package com.android.b:
// n
public class ac extends Exception
{
public final n a;
private long b;
public ac()
{
a = null;
}
public ac(n n)
{
a = n;
}
public ac(Throwable throwable)
{
super(throwable);
a = null;
}
void a(long l)
{
b = l;
}
}
| true |
9666131c76f5ccec0f37f711184cd8aa17eb9653 | Java | linzs150/education | /app/src/main/java/com/newtonacademic/newtontutors/activities/QuestionActivity.java | UTF-8 | 7,868 | 1.804688 | 2 | [] | no_license | package com.newtonacademic.newtontutors.activities;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONArray;
import com.newtonacademic.newtontutors.adapters.QuestionAdapter;
import com.newtonacademic.newtontutors.beans.GetFaqResponse;
import com.newtonacademic.newtontutors.beans.QuestRequest;
import com.newtonacademic.newtontutors.beans.QuestionResponse;
import com.newtonacademic.newtontutors.commons.LogUtils;
import com.newtonacademic.newtontutors.commons.ToastUtils;
import com.newtonacademic.newtontutors.R;
import com.newtonacademic.newtontutors.language.SpUtil;
import com.newtonacademic.newtontutors.network.NetmonitorManager;
import com.newtonacademic.newtontutors.network.RestError;
import com.newtonacademic.newtontutors.network.RestNewCallBack;
import com.newtonacademic.newtontutors.widget.PullRecyclerView;
import com.newtonacademic.mylibrary.ConstantGlobal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* @创建者 Administrator
* @创建时间 2020/4/30 11:41
* @描述 ${TODO}
* @更新者 $Author$
* @更新时间 $Date$
* @更新描述 ${TODO}
**/
public class QuestionActivity extends BaseActivity {
private PullRecyclerView pullRecyclerView;
private RecyclerView recycler_view;
private RelativeLayout leftBtnLayout;
private TextView tvTitle;
private List<QuestionResponse.Question> questionList = new ArrayList<>();
private QuestionAdapter mAdapter;
private QuestionResponse questionResp;
// private List<GetFaqResponse.GetFaq> getFaqResponse;
private Map<Integer, GetFaqResponse.GetFaq> getFaqResponse = new HashMap<>();
private Map<Integer, Boolean> maps = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question_activity);
initView();
initData();
setListener();
}
private void initView() {
pullRecyclerView = findViewById(R.id.pull_recycler_view);
leftBtnLayout = findViewById(R.id.leftBtnLayout);
tvTitle = findViewById(R.id.tvTitle);
recycler_view = findViewById(R.id.recycler_view);
tvTitle.setText(getString(R.string.faqs));
pullRecyclerView.setPullToRefresh(true);
}
private void initData() {
LinearLayoutManager manager = new LinearLayoutManager(getActivity()) {
@Override
public boolean canScrollVertically() {
return true;
}
};
recycler_view.setLayoutManager(manager);
mAdapter = new QuestionAdapter(this, questionList);
recycler_view.setAdapter(mAdapter);
pullRecyclerView.notifyDataSetChanged();
getFaqList();
}
private void getFaqList() {
QuestRequest request = new QuestRequest();
request.setPageNO(1);
request.setPageSize(200);
String spLanguage = SpUtil.getString(getApplicationContext(), ConstantGlobal.LOCALE_LANGUAGE);
String spCountry = SpUtil.getString(getApplicationContext(), ConstantGlobal.LOCALE_COUNTRY);
if (TextUtils.isEmpty(spCountry) && TextUtils.isEmpty(spCountry)) {
request.setCategoryId(28);
} else {
if (spLanguage.equals("zh")) {
if (spCountry.equals("CN")) {
request.setCategoryId(28);
} else if (spCountry.equals("HK")) {
request.setCategoryId(36);
}
} else if (spLanguage.equals("en")) {
request.setCategoryId(29);
}
}
showProgress();
addJob(NetmonitorManager.getArticleList(request, new RestNewCallBack<QuestionResponse>() {
@Override
public void success(QuestionResponse questionResponse) {
closeProgress();
pullRecyclerView.finishLoad(true);
if (questionResponse.isSuccess()) {
maps.clear();
questionResp = questionResponse;
for (int i = 0; i < questionResponse.getData().size(); i++) {
Map<Integer, Boolean> map = new TreeMap<Integer, Boolean>();
maps.put(i, false);
}
// getFaqResponse = new ArrayList<GetFaqResponse.GetFaq>(questionResponse.getData().size());
LogUtils.e("ceshi", JSONArray.toJSONString(questionResponse.getData()));
updateQuest(questionResponse);
} else {
ToastUtils.showToastShort(questionResponse.getDescript());
}
}
@Override
public void failure(RestError error) {
closeProgress();
ToastUtils.showToastShort(error.msg);
}
}));
}
private void updateQuest(QuestionResponse response) {
if (response != null) {
if (response.getData() != null && response.getData().size() > 0) {
mAdapter.updateQuestionInfo(response.getData());
mAdapter.setMap(maps);
pullRecyclerView.notifyDataSetChanged();
}
}
}
private void setListener() {
leftBtnLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
pullRecyclerView.setOnPullListener(new PullRecyclerView.OnPullListener() {
@Override
public void onRefresh(RecyclerView recyclerView) {
getFaqList();
}
@Override
public void onLoadMore(RecyclerView recyclerView) {
}
});
mAdapter.setQuestionListener(new QuestionAdapter.SearchListener() {
@Override
public void click(int position) {
if (mAdapter.getMap() != null && mAdapter.getMap().size() > 0) {
if (mAdapter.getMap().get(position)) {
mAdapter.getMap().put(position, false);
} else {
mAdapter.getMap().put(position, true);
}
}
if (QuestionActivity.this.getFaqResponse != null && QuestionActivity.this.getFaqResponse.size() > 0
&& QuestionActivity.this.getFaqResponse.get(position) != null) {
mAdapter.getFag(position, mAdapter.getMap().get(position), getFaqResponse.get(position));
// mAdapter.
} else {
if (questionResp != null && questionResp.getData() != null) {
getFaq(position, mAdapter.getMap().get(position), questionResp.getData().get(position).getId());
}
}
}
});
}
private void getFaq(final int pos, final boolean flag, long id) {
showProgress();
addJob(NetmonitorManager.getArticle(id, new RestNewCallBack<GetFaqResponse>() {
@Override
public void success(GetFaqResponse getFaqResponse) {
closeProgress();
QuestionActivity.this.getFaqResponse.put(pos, getFaqResponse.getData());
mAdapter.getFag(pos, flag, getFaqResponse.getData());
}
@Override
public void failure(RestError error) {
closeProgress();
}
}));
}
}
| true |
0d3ef91f85bf3104178157eea7db67ca90b9d534 | Java | ZPyhagoras/EverydayLeetcode | /Leetcode10.java | UTF-8 | 1,871 | 2.90625 | 3 | [] | no_license | import java.util.HashMap;
import java.util.Map;
public class Leetcode10 {
public boolean isMatch(String s, String p) {
Map<Integer, Map<Character, Integer[]>> DFA = new HashMap<>();
char[] S = s.toCharArray(), P = p.toCharArray();
int ns = S.length, np = P.length;
int curState = 0, order = 0;
for (int i = 0; i < np; i++) {
char ch = P[i];
char nch = i + 1 < np ? P[i + 1] : '#';
i = nch == '*' ? i + 1 : i;
Map<Character, Integer[]> states = DFA.getOrDefault(curState, new HashMap<>());
int nextState = nch == '*' ? curState : curState + 1;
order = curState == nextState ? order + 1 : 0;
if (states.keySet().contains(ch) && states.get(ch)[0] == curState) {
continue;
}
states.put(ch, new Integer[]{nextState, order});
DFA.put(curState, states);
curState = nextState;
}
int lastState = curState, preState = -1, preOrder = -1, curOrder = 0;
curState = 0;
for (int i = 0; i < ns; i++) {
char ch = S[i];
Map<Character, Integer[]> states = DFA.getOrDefault(curState, new HashMap<>());
preState = curState; preOrder = curOrder;
if (states.keySet().contains(ch)) {
curState = states.get(ch)[0];
curOrder = states.get(ch)[1];
}
else if (states.keySet().contains('.')) {
curState = states.get('.')[0];
curOrder = states.get('.')[1];
}
else {
return false;
}
if (preState == curState) {
if (curOrder < preOrder) {
return false;
}
}
}
return curState == lastState;
}
}
| true |
17c1c91f729608c3dd5387aa7ddcbb2af8544790 | Java | cliicy/autoupdate | /Central/Server/EdgeAppBaseServiceImpl/src/com/ca/arcserve/edge/app/base/schedulers/policymanagement/policydeployment/deploytaskrunner/UnifiedDeployTaskRunner.java | UTF-8 | 11,651 | 1.679688 | 2 | [] | no_license | package com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.deploytaskrunner;
import java.util.List;
import org.apache.log4j.Logger;
import com.ca.arcserve.edge.app.base.appdaos.IEdgePolicyDao;
import com.ca.arcserve.edge.app.base.dao.impl.DaoFactory;
import com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.PolicyDeploymentTask;
import com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.plan.ITaskDeployment;
import com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.plan.RpsSettingTaskDeployment;
import com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.plan.TaskDeploymentFactory;
import com.ca.arcserve.edge.app.base.schedulers.policymanagement.policydeployment.plan.VSphereBackupTaskDeployment;
import com.ca.arcserve.edge.app.base.serviceexception.EdgeServiceFault;
import com.ca.arcserve.edge.app.base.util.EdgeCMWebServiceMessages;
import com.ca.arcserve.edge.app.base.webservice.IActivityLogService;
import com.ca.arcserve.edge.app.base.webservice.asbuintegration.ASBUDestinationManager;
import com.ca.arcserve.edge.app.base.webservice.contract.common.Utils;
import com.ca.arcserve.edge.app.base.webservice.contract.log.LogAddEntity;
import com.ca.arcserve.edge.app.base.webservice.contract.log.Severity;
import com.ca.arcserve.edge.app.base.webservice.contract.policymanagement.PolicyDeployFlags;
import com.ca.arcserve.edge.app.base.webservice.contract.policymanagement.PolicyDeployReasons;
import com.ca.arcserve.edge.app.base.webservice.contract.policymanagement.unified.PlanStatus;
import com.ca.arcserve.edge.app.base.webservice.contract.policymanagement.unified.PlanTaskType;
import com.ca.arcserve.edge.app.base.webservice.contract.policymanagement.unified.UnifiedPolicy;
import com.ca.arcserve.edge.app.base.webservice.log.ActivityLogServiceImpl;
import com.ca.arcserve.edge.app.base.webservice.node.LinuxNodeServiceImpl;
import com.ca.arcserve.edge.app.base.webservice.node.NodeServiceImpl;
import com.ca.arcserve.edge.app.base.webservice.policymanagement.PolicyManagementServiceImpl;
public class UnifiedDeployTaskRunner extends AbstractDeployTaskRunner {
private static Logger logger = Logger.getLogger(UnifiedDeployTaskRunner.class);
private static IEdgePolicyDao policyDao = DaoFactory.getDao(IEdgePolicyDao.class);
private IActivityLogService activityLogService = null;
private long edgeTaskId = PolicyManagementServiceImpl.getTaskId();
@Override
protected void deployPolicy(PolicyDeploymentTask task)
{
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Enter. " + task);
UnifiedPolicy plan;
logger.debug("UnifiedDeployTaskRunner.deployPolicy(): load plan details.");
try {
plan = policyManagementServiceImpl.loadUnifiedPolicyById(task.getPolicyId());
} catch (EdgeServiceFault e) {
logger.error("UnifiedDeployTaskRunner.deployPolicy(): cannot load plan information by id.", e);
return;
}
logger.info( "UnifiedDeployTaskRunner.deployPolicy(): " + plan );
List<ITaskDeployment> deployments = TaskDeploymentFactory.create(task, plan);
boolean hasTaskToDeploy = deployments != null && deployments.size() > 0;
removeUnusedTasks(task, !hasTaskToDeploy);
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Begin to deploy tasks. Deployer count: " + deployments.size() );
for (int i = 0; i < deployments.size(); ++i)
{
String deployerInfo = deployments.get(i).getClass().getSimpleName();
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Index: " + i + ", Deployer: " + deployerInfo );
if (!deployments.get(i).deployTask(task, plan, i == deployments.size() - 1))
{
if(deployments.get(i) instanceof VSphereBackupTaskDeployment){
//when vm have hbbu task + vsb task, then not to block vsb task deployment
logger.error("UnifiedDeployTaskRunner.deployPolicy(): vsphere backup deploy have errors.");
continue;
}else {
logger.error("UnifiedDeployTaskRunner.deployPolicy(): Deploying task failed.");
break;
}
}
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Deploying task succeed.");
}
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Deploying all tasks finished." );
updatePlanStatus(task, plan);
logger.info("UnifiedDeployTaskRunner.deployPolicy(): Leave.");
}
private boolean removeUnusedTasks(PolicyDeploymentTask task, boolean updateDeployStatusOnSuccess) {
logger.info( "removeUnusedTasks(): Begin to remove unused tasks." );
List<ITaskDeployment> deployerList = TaskDeploymentFactory.createUnusedTasks(task);
int deployerSize = deployerList.size();
logger.info( "removeUnusedTasks(): Deployer count: " + deployerSize );
for (int i = 0; i < deployerSize; i++) {
ITaskDeployment deployment = deployerList.get(i);
logger.info("UnifiedDeployTaskRunner.removeUnusedTasks - remove unused task ["
+ deployment.getClass().getSimpleName() + "], " + task);
if (!deployment.removeTask(task, updateDeployStatusOnSuccess && i == deployerSize - 1)) {
logger.warn("UnifiedDeployTaskRunner.removeUnusedTasks - remove unused task ["
+ deployment.getClass().getSimpleName() + "] failed, " + task);
return false;
}
logger.info("UnifiedDeployTaskRunner.removeUnusedTasks - remove unused task ["
+ deployment.getClass().getSimpleName() + "] succeed, " + task);
}
logger.info( "removeUnusedTasks(): Removing unused tasks finished." );
return true;
}
@Override
protected void removePolicy(PolicyDeploymentTask task) {
logger.debug("UnifiedDeployTaskRunner.removePolicy - Enter, " + task);
UnifiedPolicy plan;
try {
plan = policyManagementServiceImpl.loadUnifiedPolicyById(task.getPolicyId());
} catch (EdgeServiceFault e) {
logger.error("UnifiedDeployTaskRunner.removePolicy - cannot load plan information by id.", e);
return;
}
if (isModify(task)) {
removeUnusedTasks(task, true);
} else {
List<ITaskDeployment> deployments = TaskDeploymentFactory.create(task, plan);
for (int i = 0; i < deployments.size(); ++i) {
if (!deployments.get(i).removeTask(task, i == deployments.size() - 1)) {
break;
}
}
if ((task.getDeployFlags() & PolicyDeployFlags.UnregisterNodeAfterUnassign) != 0){
if(Utils.hasBit(task.getContentFlag(), PlanTaskType.LinuxBackup)){
unRegisterLinuxD2D(task);
}else{
unregisterD2D(task);
}
}
}
if(Utils.hasBit(task.getContentFlag(), PlanTaskType.LinuxBackup)){
@SuppressWarnings("unchecked")
List<Integer> idList = (List<Integer>)task.getTaskParameters();
for(Integer id : idList){
edgePolicyDao.deleteHostPolicyMap(id, task.getPolicyType());
}
}else{
edgePolicyDao.deleteHostPolicyMap(task.getHostId(), task.getPolicyType());
}
updatePlanStatus(task, plan);
logger.debug("UnifiedDeployTaskRunner.removePolicy - Leave, " + task);
}
private void unregisterD2D(PolicyDeploymentTask task){
try
{
NodeServiceImpl nodeServiceImpl = new NodeServiceImpl();
this.edgePolicyDao.deleteHostPolicyMap( task.getHostId(), task.getPolicyType() );
nodeServiceImpl.unregisterD2D( task.getHostId() );
// Need to remove records here , since deleteNode method just set to invisible
this.edgeHostMgrDao.as_edge_host_remove(task.getHostId());
logger.info("UnifiedDeployTaskRunner.unregisterD2D(): delete node, nodeId:" + task.getHostId());
}
catch (Exception e)
{
logger.warn("removePolicy(): Deleting host policy map and unregister " +
"D2D after unassign policy failed." );
// Ignore this exception, and D2D will connect Edge when
// service starts and before job run, and clear the date
// save on D2D.
}
}
private void unRegisterLinuxD2D(PolicyDeploymentTask task){
LinuxNodeServiceImpl impl = new LinuxNodeServiceImpl();
impl.unRegisterLinuxD2DForTask(task);
}
private void updatePlanStatus(PolicyDeploymentTask task, UnifiedPolicy plan) {
logger.info( "updatePlanStatus(): Begin to update plan deployment status." );
int status = getOverallDeployStatus(task.getPolicyId());
String msg = "";
if (status == 1) { // failed
String msgid;
if (isDelete(task)) {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.DeleteFailed);
msgid="deletePlanFailed";
} else if (isModify(task)) {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.ModifyFailed);
msgid="modifyPlanFailed";
} else if(isRedeploy(task)){
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.DeployFailed);
msgid="redeployPlanFailed";
} else {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.DeployFailed);
msgid="createPlanFailed";
}
msg = EdgeCMWebServiceMessages.getMessage( msgid, plan.getName() );
writePlanActivityLog(Severity.Error, 0, msg);
} else if (status == 2) { // success
String msgid;
if (isDelete(task)) {
deletePlan(task, plan);
msgid="deletePlanSuccessful";
} else if (isModify(task)) {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.ModifySucess);
msgid="modifyPlanSuccessful";
} else if (isRedeploy(task)) {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.DeploySuccess);
msgid="redeployPlanSuccessful";
} else {
policyDao.as_edge_policy_updateStatus(task.getPolicyId(), PlanStatus.DeploySuccess);
msgid="createPlanSuccessful";
}
msg = EdgeCMWebServiceMessages.getMessage( msgid, plan.getName() );
writePlanActivityLog(Severity.Information, 0, msg);
}
logger.info( "updatePlanStatus(): Updating plan deployment status finished. Status: " + status + ", Message: " + msg );
}
public static synchronized int getOverallDeployStatus(int policyId) {
int[] status = new int[1];
policyDao.as_edge_policy_getOverallDeployStatus(policyId, status);
return status[0];
}
private boolean isModify(PolicyDeploymentTask task) {
return (task.getDeployFlags() & PolicyDeployFlags.ModifyPlan) != 0;
}
private boolean isRedeploy(PolicyDeploymentTask task) {
return (task.getDeployFlags() & PolicyDeployFlags.RedeployPlan) != 0
|| task.getDeployReason() == PolicyDeployReasons.EnablePlan
|| task.getDeployReason() == PolicyDeployReasons.DisablePlan;
}
private boolean isDelete(PolicyDeploymentTask task) {
return (task.getDeployFlags() & PolicyDeployFlags.DeletePlan) != 0;
}
private void deletePlan(PolicyDeploymentTask argument, UnifiedPolicy plan) {
RpsSettingTaskDeployment rpsPolicyTaskDeployment = new RpsSettingTaskDeployment();
try {
rpsPolicyTaskDeployment.deleteRpsPolicySettings(plan);
ASBUDestinationManager.getInstance().deleteASBUSettings(plan);
policyDao.as_edge_policy_remove(argument.getPolicyId());
} catch (EdgeServiceFault e) {
policyDao.as_edge_policy_updateStatus(argument.getPolicyId(), PlanStatus.DeleteFailed);
}
}
private void writePlanActivityLog(
Severity severity, int nodeid, String message )
{
try{
LogAddEntity log = new LogAddEntity();
log.setJobId( edgeTaskId );
log.setTargetHostId(nodeid);
log.setSeverity( severity );
log.setMessage(message);
this.getActivityLogService().addUnifiedLog(log);
}
catch (Exception e)
{
logger.error( "writePlanActivityLog(): Error writting activity log. (Node id: '" +
nodeid + "', Message: '" + message + "')", e );
}
}
private IActivityLogService getActivityLogService()
{
if (this.activityLogService == null)
this.activityLogService = new ActivityLogServiceImpl();
return this.activityLogService;
}
}
| true |
8bf5c4126bd34c9391b37eaff3547ce8fb0a3e64 | Java | sIvanovKonstantyn/demo-bank-app | /deposit-service/src/main/java/com/home/demos/deposit/infrastructure/KafkaTopicsListener.java | UTF-8 | 3,654 | 2.359375 | 2 | [] | no_license | package com.home.demos.deposit.infrastructure;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.home.demos.deposit.application.services.DepositService;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@Profile({"main", "kafka-test"})
public class KafkaTopicsListener {
@Autowired
@Setter
private DepositService depositService;
@Autowired
private ObjectMapper mapper;
private boolean wasAnyCreateCall;
private boolean wasAnyReplenishCall;
private boolean wasAnyRepayCall;
@KafkaListener(
topics = "createDepositCommands",
containerFactory = "createDepositCommandsKafkaListenerContainerFactory")
public void createDepositCommandListener(String createDepositCommandString) throws JsonProcessingException {
System.out.printf("%s: deposit command taken: %s%n", LocalDateTime.now(), createDepositCommandString);
CreateDepositCommand createDepositCommand = mapper.readValue(
createDepositCommandString,
CreateDepositCommand.class
);
depositService.createDeposit(
createDepositCommand.getRequestID(),
createDepositCommand.getName(),
createDepositCommand.getSum(),
createDepositCommand.getCapitalizationType(),
createDepositCommand.getCurrencyCode(),
createDepositCommand.getDepositType(),
createDepositCommand.getCloseDate(),
createDepositCommand.getIncomeRate()
);
wasAnyCreateCall = true;
}
@KafkaListener(
topics = "replenishDepositCommands",
containerFactory = "replenishDepositCommandsKafkaListenerContainerFactory")
public void replenishDepositCommandListener(String replenishDepositCommandString) throws JsonProcessingException {
ReplenishDepositCommand replenishDepositCommand = mapper.readValue(
replenishDepositCommandString,
ReplenishDepositCommand.class
);
depositService.replenishDeposit(
replenishDepositCommand.getRequestID(),
replenishDepositCommand.getDepositID(),
replenishDepositCommand.getSum()
);
wasAnyReplenishCall = true;
}
@KafkaListener(
topics = "repayDepositCommands",
containerFactory = "repayDepositCommandsKafkaListenerContainerFactory")
public void repayDepositCommandListener(String repayDepositCommandString) throws JsonProcessingException {
System.out.println("--- received repayDepositCommandString... " + repayDepositCommandString);
RepayDepositCommand repayDepositCommand = mapper.readValue(
repayDepositCommandString,
RepayDepositCommand.class
);
System.out.println("depositService: " + depositService);
depositService.repayDeposit(
repayDepositCommand.getRequestID(),
repayDepositCommand.getDepositID()
);
wasAnyRepayCall = true;
}
public Boolean wasCreateSuccessfulCall() {
return wasAnyCreateCall;
}
public Boolean wasReplenishSuccessfulCall() {
return wasAnyReplenishCall;
}
public Boolean wasRepaySuccessfulCall() {
return wasAnyRepayCall;
}
} | true |
883d3f6b7b0fb384a90f3155d924ac3f13ec97de | Java | hooji/rameses | /src/main/java/javax/io/StringOutputStream.java | UTF-8 | 1,002 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | package javax.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
public class StringOutputStream extends ByteArrayOutputStream {
protected Charset characterSet = Charset.defaultCharset();
public StringOutputStream() {
super();
}
public StringOutputStream(Charset characterSet) {
super();
this.characterSet = characterSet;
}
public StringOutputStream(int size, Charset characterSet) {
super(size);
this.characterSet = characterSet;
}
public StringOutputStream write(String string) throws IOException {
return write(string, this.characterSet);
}
public StringOutputStream write(String string, Charset characterSet) throws IOException {
write(bytes(string, characterSet));
return this;
}
public byte[] bytes(String string, Charset characterSet) {
return characterSet.encode(string).array();
}
//public String toString() {
// return this.characterSet.decode(ByteBuffer.wrap(this.buf)).toString();
//}
}
| true |
ef909571bad6bb7155c969338a79a54eee755ef1 | Java | afrikgenius/enipro-mobile | /app/src/main/java/com/enipro/presentation/requests/RequestBroadcastReceiver.java | UTF-8 | 735 | 2.234375 | 2 | [] | no_license | package com.enipro.presentation.requests;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.enipro.model.Constants;
/**
* Broadcast receiver that receives broadcast messages from notification requests for
* circle, network, mentoring and tutoring requests.
*/
public class RequestBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Get intent extra to identify the type of request and so appropriate action will
// be triggered for the type of request based on the information.
String requestCode = intent.getStringExtra(Constants.BROADCAST_REQUEST_EXTRA);
}
}
| true |
b979294c08aa8e66c4d01691d29921263c5ee4db | Java | ViktorDimitrov1989/JavaOOP-Fundamentals-Exam | /src/needForSpeed/races/CasualRace.java | UTF-8 | 1,181 | 3.03125 | 3 | [] | no_license | package needForSpeed.races;
import needForSpeed.cars.Car;
import java.util.List;
import java.util.stream.Collectors;
public class CasualRace extends Race{
public CasualRace(int length, String route, int prizePool) {
super(length, route, prizePool);
}
@Override
protected int calculatePerformance(Car car) {
return (car.getHorsepower() / car.getAcceleration()) + (car.getSuspension() + car.getDurability());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(super.toString());
List<Car> sortedCars = super.getParticipants().stream()
.sorted((c1,c2) -> Integer.compare(this.calculatePerformance(c2), this.calculatePerformance(c1)))
.limit(3)
.collect(Collectors.toList());
for (int i = 0; i < sortedCars.size(); i++) {
Car car = sortedCars.get(i);
sb.append(String.format("%d. %s %s %dPP - $%d",
i + 1, car.getBrand(), car.getModel(), this.calculatePerformance(car), super.calculateProfit(i + 1)))
.append(System.lineSeparator());
}
return sb.toString();
}
}
| true |
998cd8ba44eab0b54f069d8d3909c0bd90b06176 | Java | Wells-ING/warehouse | /src/cn/wellswang/service/ModifyGoodsService.java | UTF-8 | 342 | 1.96875 | 2 | [] | no_license | package cn.wellswang.service;
import cn.wellswang.dao.GoodsInfoDAO;
import cn.wellswang.dao.impl.GoodsInfoDAOImpl;
import cn.wellswang.entity.Goods;
public class ModifyGoodsService {
public static Integer modifyGoods(Goods newGoods) {
GoodsInfoDAO g = new GoodsInfoDAOImpl();
return g.updateGoodsInfo(newGoods);
}
}
| true |
3141f5c66be7dfb1174c25ed0872ef0e41debd0d | Java | Vaghelarahul/ImageApp | /app/src/main/java/com/example/batman/eckovationtask/animation/CustomAnimation.java | UTF-8 | 2,048 | 2.15625 | 2 | [] | no_license | package com.example.batman.eckovationtask.animation;
import android.animation.Animator;
import android.os.Build;
import android.support.animation.DynamicAnimation;
import android.support.animation.SpringAnimation;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewPropertyAnimator;
import static android.support.animation.SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY;
import static android.support.animation.SpringForce.STIFFNESS_LOW;
public class CustomAnimation {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void circularRevealAnimate(View view) {
int centerX = view.getWidth() / 2;
int centerY = view.getHeight() / 2;
float endRadius = (float) centerX;
Animator animator = ViewAnimationUtils.createCircularReveal(view, centerX, centerY, 0, endRadius);
animator.start();
}
public static ViewPropertyAnimator getFabAnimator(View view, float rotation, long duration) {
ViewPropertyAnimator animator = view.animate();
animator.rotation(rotation);
animator.setDuration(duration);
return animator;
}
public static ViewPropertyAnimator getJoinGroupAnimator(View view, boolean isExpanded, float alpha, long duration) {
ViewPropertyAnimator animator = view.animate()
.alpha(alpha)
.setDuration(duration);
if (isExpanded) {
animator.translationY(0f);
}
return animator;
}
public static void springAnimateFab(View view) {
SpringAnimation springAnimation = new SpringAnimation(view, DynamicAnimation.TRANSLATION_Y, -220f);
springAnimation.getSpring().setDampingRatio(DAMPING_RATIO_MEDIUM_BOUNCY);
springAnimation.getSpring().setStiffness(STIFFNESS_LOW);
springAnimation.start();
}
public static void getAddChilsAnimate(View view) {
view.animate()
.alpha(1f)
.setDuration(400);
}
}
| true |
987e718a28dafb7def95f876b1ded3fa0eb2531e | Java | nihadatakishiyev/hashcode2020 | /Main.java | UTF-8 | 5,229 | 2.984375 | 3 | [] | no_license | import java.io.*;
import java.util.*;
public class Main {
public static Integer book_count;
public static Integer library_count;
public static Integer days;
public static List<Book> scores = new ArrayList<>();
public static List<Library> libraries = new ArrayList<>();
public static class CustomComparator implements Comparator<Library> {
@Override
public int compare(Library o1, Library o2) {
return o1.getTotalScore().compareTo(o2.getTotalScore());
}
}
public static class CustomComparator2 implements Comparator<Library> {
@Override
public int compare(Library o1, Library o2) {
return o1.getSignUp().compareTo(o2.getSignUp());
}
}
public static class CustomComparator3 implements Comparator<Library> {
@Override
public int compare(Library o1, Library o2) {
return o1.getPerDay().compareTo(o2.getPerDay());
}
}
public static void main(String[] args) {
try {
File myObj = new File("./src/in.txt");
BufferedWriter br = new BufferedWriter(new FileWriter(new File("./src/out.txt")));
Scanner myReader = new Scanner(myObj);
book_count = myReader.nextInt();
int[] usedBooks = new int[book_count];
int cnt = 0;
library_count = myReader.nextInt();
days = myReader.nextInt();
for (int i = 0; i < book_count; i++) {
Book book = new Book();
book.setId(i);
book.setScore(myReader.nextInt());
scores.add(book);
}
for (int i = 0; i < library_count; i++) {
Library library = new Library();
library.setID(i);
int bookcount= myReader.nextInt();
library.setBookCount(bookcount);
library.setSignUp(myReader.nextInt());
library.setPerDay(myReader.nextInt());
List<Book> a = new ArrayList<>();
for (int j = 0; j < library.getBookCount(); j++) {
int tm2 = myReader.nextInt();
Book temp = new Book();
temp.setScore(scores.get(tm2).getScore());
temp.setId(tm2);
a.add(temp);
}
Collections.sort(a, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.getScore().compareTo(o2.getScore());
}
}.reversed());
library.setBooks(a);
library.setTotalScore(scores,days);
libraries.add(library);
}
List<Library> libraries2 = libraries;
Collections.sort(libraries2, new CustomComparator().reversed());
// Collections.sort(libraries2, new CustomComparator2());
// Collections.sort(libraries2, new CustomComparator3());
// System.out.println(library);
br.write(library_count + "\n");
for (int i = 0; i < library_count; i++) {
Library temp = libraries2.get(i);
if (temp.getSignUp()<days){
List<Book> aa = temp.getBooks();
int n = 0;
int m=0;
List<Integer> ls = new ArrayList<>();
for (int j = 0; j <temp.getBookCount(); j++) {
// System.out.print(aa.get(j)+ " ");
if (usedBooks[aa.get(j).getId()]==0 ){
if (m < temp.getMaxBookCount()) {
usedBooks[aa.get(j).getId()] = 1;
ls.add(aa.get(j).getId());
m++;
}
}
else {
n++;
}
if (j == temp.getBookCount()-1) {
if (temp.getBookCount()-n>0) {
br.write(temp.getID() + " ");
br.write((Math.min((temp.getBookCount() - n), temp.getMaxBookCount())) + " \n");
for (int k = 0; k <Math.min((temp.getBookCount() - n), temp.getMaxBookCount()) ; k++) {
br.write(ls.get(k)+ " ");
}
}else{
cnt++;
}
}
}
if(temp.getMaxBookCount()-n > 0)
br.write('\n');
}
}
System.out.println(cnt);
myReader.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
12c8753d04abd1f24f90616a6bb04f3e1bb4a6c6 | Java | RajasekharBandi/codility-solutions-1 | /src/main/java/com/rmacedo/codility/lesson_03_01/Solution1.java | UTF-8 | 823 | 3.234375 | 3 | [
"MIT"
] | permissive | package com.rmacedo.codility.lesson_03_01;
public class Solution1 implements SolutionInterface {
public static void main(String... args) {
Solution1 s = new Solution1();
System.out.println(s.solution(new int[]{3, 1, 2, 4, 3}));
System.out.println(s.solution(new int[]{-1000, 1000}));
}
@Override
public int solution(int[] A) {
int minSum = Integer.MAX_VALUE;
for (int p = 0; p < A.length; p++) {
int first = 0;
int last = 0;
for (int i = 0; i < A.length; i++) {
if (i <= p) first += A[i];
else last += A[i];
}
int sum = Math.abs(first - last) > 0 ? Math.abs(first - last) : minSum;
if (sum < minSum) minSum = sum;
}
return minSum;
}
}
| true |
fee392d01605c065133ee2042b571a883e8e089b | Java | CSC361-Final-Project/filteringproject | /src/filtering/Filtering.java | UTF-8 | 3,608 | 2.453125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package filtering;
import static filtering.ComplexNumber.printComplexVectorCSV;
import static filtering.ComplexNumber.vectorDotMultiply;
import static filtering.Convolution.convolveFIR;
import static filtering.FilterBuilder.bandpassFilter;
import static filtering.FilterBuilder.bandstopFilter;
import static filtering.FilterBuilder.cutSignal;
import static filtering.FilterBuilder.firHighPassFilter;
import static filtering.FilterBuilder.firLowPassFilter;
import static filtering.FilterBuilder.padFilter;
import static filtering.FilterBuilder.padSignal;
import static filtering.FilterTimer.dftTimer;
import static filtering.FilterTimer.fftTimer;
import static filtering.FilterTimer.freqDomainConvolveTimer;
import static filtering.FilterTimer.timeAndSaveFD;
import static filtering.FilterTimer.timeAndSaveTD;
import static filtering.FilterTimer.timeDomainConvolveTimer;
import static filtering.Fourier.fft;
//import static filtering.Fourier.ifft;
//import static filtering.Fourier.ifftDouble;
import static filtering.StdDraw.BLUE;
import static filtering.StdDraw.RED;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
*
* @author kincbe10
*/
public class Filtering {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws UnsupportedAudioFileException, FileNotFoundException, IOException, LineUnavailableException {
// TODO code application logic here
// AudioSignal[] sigArr = new AudioSignal[4];
// //sigArr[0] = new AudioSignal("beethoven16.wav");
// sigArr[0] = new AudioSignal("beethoven256.wav");
// sigArr[1] = new AudioSignal("beethoven4096.wav");
// sigArr[2] = new AudioSignal("beethoven65536.wav");
// sigArr[3] = new AudioSignal("beethoven131072.wav");// StdDraw.setCanvasSize(1024,720);
//// StdDraw.setXscale(0,10);
//// StdDraw.setYscale(0, 10);
//// StdDraw.setPenRadius(0.02);
// for(int j = 0; j < 4; j++){
// int log2 = (int) ((int) Math.log(sigArr[j].getSamples().length)/Math.log(2));
// for(int i = 0; i < log2; i++){
//
// double[] mask = firLowPassFilter(sigArr[j], 10000, (int) (Math.pow(2, i)+1));
//
// double timeTD = timeAndSaveTD(sigArr[j], mask, i+"-"+j+"t.wav");
//
// double timeFD = timeAndSaveFD(sigArr[j], mask, i+"-"+j+"t.wav");
//
// System.out.println(sigArr[j].getSamples().length+" "+mask.length+" "+timeTD+" "+timeFD);
// }
// }
//
// }
AudioSignal sig = new AudioSignal("beethoven131072.wav");
double[] low = firLowPassFilter(sig, 1000, 33);
double[] high = firHighPassFilter(sig, 40000, 33);
double[] bandp = bandpassFilter(sig, 40000, 1000, 33);
double[] bands = bandstopFilter(sig, 5000, 4000, 33);
timeAndSaveTD(sig, low, "lowpass1000.wav");
timeAndSaveTD(sig, high, "highpass40000.wav");
timeAndSaveTD(sig, bandp, "bandpass1000_40000.wav");
timeAndSaveTD(sig, bands, "bandstop4000_5000.wav");
}
}
| true |
d563b71666796cd923cce754b0d20e8e862b4e46 | Java | RyanTech/mobile-2 | /bjmobileadapterV3/src/cn/com/ultrapower/eoms/user/comm/function/PrivateFieldInfo.java | UTF-8 | 2,268 | 2.609375 | 3 | [] | no_license | package cn.com.ultrapower.eoms.user.comm.function;
/**
* @创建作者:wuwenlong
* @创建时间:2006-11-19
* @类的说明:将Remedy的Form中的field进行封装
*/
public class PrivateFieldInfo {
private String strFieldID;
private String strFieldValue;
private int intFieldType;
private String sparator;
public PrivateFieldInfo()
{
}
/**
* 初始化字段信息类
* @param intFieldType 字段类型
* @ AR_DATA_TYPE_NULL 0 空
* @ AR_DATA_TYPE_KEYWORD 1 AR关键字
* @ AR_DATA_TYPE_INTEGER 2 整形
* @ AR_DATA_TYPE_REAL 3 浮点型
* @ AR_DATA_TYPE_CHAR 4 字符型
* @ AR_DATA_TYPE_DIARY 5 日志型
* @ AR_DATA_TYPE_ENUM 6
* @ AR_DATA_TYPE_TIME 7 时间型,传递秒
* @ AR_DATA_TYPE_BITMASK 8
* @ AR_DATA_TYPE_BYTES 9
* @ AR_DATA_TYPE_DECIMAL 10
* @ AR_DATA_TYPE_ATTACH 11 附件,传具体文件名,带路径,例如:“D:\dddd\1.exe”
* @ AR_DATA_TYPE_CURRENCY 12
* @ AR_DATA_TYPE_DATE 13 日期,传递秒
* @ AR_DATA_TYPE_TIME_OF_DAY 14 日期时间,传递秒
*/
public PrivateFieldInfo(
String strFieldID,
String strFieldValue,
int intFieldType)
{
this.setStrFieldID(strFieldID);
this.setStrFieldValue(strFieldValue);
this.setIntFieldType(intFieldType);
}
public PrivateFieldInfo(
String strFieldID,
String strFieldValue,
int intFieldType,String sparator)
{
this.setStrFieldID(strFieldID);
this.setStrFieldValue(strFieldValue);
this.setIntFieldType(intFieldType);
this.setSparator(sparator);
}
public int getIntFieldType() {
return intFieldType;
}
public void setIntFieldType(int intFieldType) {
this.intFieldType = intFieldType;
}
public String getStrFieldID() {
return strFieldID;
}
public void setStrFieldID(String strFieldID) {
this.strFieldID = strFieldID;
}
public String getStrFieldValue() {
return strFieldValue;
}
public void setStrFieldValue(String strFieldValue) {
this.strFieldValue = strFieldValue;
}
public String getSparator() {
return sparator;
}
public void setSparator(String sparator) {
this.sparator = sparator;
}
}
| true |
cc846a8d0f517776a84cdb6b4754845005a78251 | Java | equipeazul/ProjetoPooVendas | /Vendas/src/vendas/Entidades/PedidoProduto.java | UTF-8 | 962 | 2.453125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vendas.Entidades;
/**
*
* @author aluno
*/
public class PedidoProduto {
private Produto produto;
private Double valor;
private Integer quantidade;
public PedidoProduto() {
this.produto = new Produto();
}
public Produto getProduto() {
return this.produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Double getValor() {
return this.valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public Integer getQuantidade() {
return this.quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
}
| true |
5b85191b5a38adb208ea098185f69aa45b6f033c | Java | Yashwanth-36/java-program | /Demo.java | UTF-8 | 114 | 1.953125 | 2 | [] | no_license | class Demo1
{
public static void main(String args[])
{
int i=0;
while(i!=0)
{
Sytem.out.println(i);
i++;
}
}
| true |
6101df0b6a7d8cf0fd762a64c4359f48013b56c2 | Java | pertinee/CCBlog | /src/main/java/com/lcz/blog/bean/UserBean.java | UTF-8 | 2,256 | 2.375 | 2 | [] | no_license | package com.lcz.blog.bean;
import java.io.Serializable;
import java.util.Date;
/**
* Created by luchunzhou on 16/2/23.
* 对应 t_user 表
* id 用户id
* type 用户类型,0代表普通用户,1代表管理员
* username 用户名
* password 用户密码
* nickname 用户昵称
* email 用户邮箱
* website 用户网站
* image 用户头像地址
* isLocked 用户是否锁定
* createDate 创建时间
*/
public class UserBean implements Serializable {
private Integer id;
private Integer type;
private String username;
private String nickname;
private String password;
private String email;
private String website;
private String image;
private Integer isLocked;
private Date createDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getIsLocked() {
return isLocked;
}
public void setIsLocked(Integer isLocked) {
this.isLocked = isLocked;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
} | true |
7bd0b0ad53cc68eae1abaf6bd5a6778e279a4dc1 | Java | AlvinGenta99/Dummy_SBD | /app/src/main/java/com/example/jfood_android/Activities/LoginActivity.java | UTF-8 | 3,550 | 2.25 | 2 | [] | no_license | package com.example.jfood_android.Activities;
import androidx.appcompat.app.AppCompatActivity;
import android.content.*;
import android.os.*;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.jfood_android.R;
import com.example.jfood_android.Requests.LoginRequest;
import com.example.jfood_android.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText etEmail = findViewById(R.id.etEmail);
final EditText etPassword = findViewById(R.id.etPassword);
final Button btnLogin = findViewById(R.id.btnLogin);
final TextView tvRegister = findViewById(R.id.tvRegister);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
final SessionManager session = new SessionManager(getApplicationContext());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject != null) {
Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
loginIntent.putExtra("currentUserId", jsonObject.getInt("id"));
loginIntent.putExtra("currentUserName", jsonObject.getString("name"));
loginIntent.putExtra("currentUserEmail", jsonObject.getString("email"));
startActivity(loginIntent);
finish();
}
} catch (JSONException e) {
Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error occurred", error);
}
};
LoginRequest loginRequest = new LoginRequest(email, password, responseListener, errorListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
//Register Button
tvRegister.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(intent);
}
});
}
} | true |
943ff32c54c4e9914205b785c0587f70567a27e4 | Java | ChristianBirchler/santorini-server | /src/main/java/ch/uzh/ifi/seal/soprafs19/response/ErrorResponse.java | UTF-8 | 323 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package ch.uzh.ifi.seal.soprafs19.response;
public class ErrorResponse {
private String reason;
public ErrorResponse(String reason){
this.reason = reason;
}
public void setReason(String reason){
this.reason = reason;
}
public String getReason() {
return reason;
}
}
| true |
752da34f5e88a9b47e9b0dbf8c88fd3101a42c9d | Java | matthiasbergneels/dhbwmawwi2020seb | /test/lecture/chapter13/SortAlgorithmsTest.java | UTF-8 | 7,492 | 2.90625 | 3 | [] | no_license | package test.lecture.chapter13;
import lecture.chapter13.SortAlgorithms;
import org.junit.jupiter.api.*;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;
class SortAlgorithmsTest {
static int count = 5000;
static int randomRange = 3000000;
static int[] toSort = null;
@DisplayName("Testing on unsorted Array")
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UnsortedArrays {
@BeforeAll
void setUp() {
toSort = generatedArrayWithRandomValues();
}
@Test
void bubbleSortNumberArray() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArray(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArrayV2() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV2(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArrayV3() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV3(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArrayV3TimeBased() {
assertTimeout(Duration.ofSeconds(50), () -> {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV3(toSort.clone());
});
}
@Test
void selectionSortNumberArray() {
int[] sortedArray = SortAlgorithms.selectionSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
@Test
void quickSortNumberArray() {
int[] sortedArray = SortAlgorithms.quickSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
}
@DisplayName("Testing on sorted Array")
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SortedArrays {
@BeforeAll
void setUp() {
toSort = generateSortedArray();
}
@Test
void bubbleSortNumberArraySorted() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArray(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV2() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV2(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV3() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV3(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void selectionSortNumberArray() {
int[] sortedArray = SortAlgorithms.selectionSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
@Test
void quickSortNumberArray() {
int[] sortedArray = SortAlgorithms.quickSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
}
@DisplayName("Testing on half sorted Array (first half sorted)")
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class FirstHalfSortedArrays {
@BeforeAll
void setUp() {
toSort = generateFirstHalfSortedArray();
}
@Test
void bubbleSortNumberArraySorted() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArray(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV2() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV2(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV3() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV3(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void selectionSortNumberArray() {
int[] sortedArray = SortAlgorithms.selectionSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
@Test
void quickSortNumberArray() {
int[] sortedArray = SortAlgorithms.quickSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
}
@DisplayName("Testing on half sorted Array (second half sorted)")
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SecondHalfSortedArrays {
@BeforeAll
void setUp() {
toSort = generateSecondHalfSortedArray();
}
@Test
void bubbleSortNumberArraySorted() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArray(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV2() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV2(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void bubbleSortNumberArraySortedV3() {
int[] bubbleSortedArray = SortAlgorithms.bubbleSortNumberArrayV3(toSort.clone());
assertTrue(isSorted(bubbleSortedArray));
}
@Test
void selectionSortNumberArray() {
int[] sortedArray = SortAlgorithms.selectionSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
@Test
void quickSortNumberArray() {
int[] sortedArray = SortAlgorithms.quickSortNumberArray(toSort.clone());
assertTrue(isSorted(sortedArray));
}
}
private static boolean isSorted(int[] array){
for(int i = 0; i < array.length-1; i++){
if(array[i] > array[i+1]){
return false;
}
}
return true;
}
private static int[] generatedArrayWithRandomValues(){
int[] generatedArray = new int[count];
for(int i = 0; i < count; i++){
boolean notInserted = true;
while(notInserted){
int randomNumber = (int)(Math.random() * randomRange);
boolean found = false;
for(int j = 0; j < i; j++){
if(generatedArray[j] == randomNumber){
found = true;
break;
}
}
if(!found){
generatedArray[i] = randomNumber;
notInserted = false;
}
}
}
return generatedArray;
}
private static int[] generateSortedArray(){
int[] generatedArray = new int[count];
for(int i = 0; i < count; i++){
generatedArray[i] = i;
}
return generatedArray;
}
private static int[] generateFirstHalfSortedArray(){
int[] generatedArray = generatedArrayWithRandomValues();
for(int i = 0; i < count/2; i++){
generatedArray[i] = i;
}
return generatedArray;
}
private static int[] generateSecondHalfSortedArray(){
int[] generatedArray = generatedArrayWithRandomValues();
for(int i = (int)count/2; i < count; i++){
generatedArray[i] = i;
}
return generatedArray;
}
} | true |
69f812af7f4d08eca091b76ede8f96cc4c6cb87f | Java | classicjay/andromeda | /src/main/java/com/bonc/dw3/bean/QueryDataObject.java | UTF-8 | 1,728 | 1.914063 | 2 | [] | no_license | package com.bonc.dw3.bean;
import java.util.List;
/**
* Created by gp on 2017/8/17.
*/
public class QueryDataObject {
//账期
private String acctDate;
//指标编码
private String kpiCode;
//省份id
private String provId;
//地市id
private String areaNo;
//渠道
private List<String> channel;
//合约
private List<String> business;
//产品
private List<String> product;
//查询用的表名
private String tableName;
public String getAcctDate() {
return acctDate;
}
public void setAcctDate(String acctDate) {
this.acctDate = acctDate;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getKpiCode() {
return kpiCode;
}
public void setKpiCode(String kpiCode) {
this.kpiCode = kpiCode;
}
public String getProvId() {
return provId;
}
public void setProvId(String provId) {
this.provId = provId;
}
public String getAreaNo() {
return areaNo;
}
public void setAreaNo(String areaNo) {
this.areaNo = areaNo;
}
public List<String> getChannel() {
return channel;
}
public void setChannel(List<String> channel) {
this.channel = channel;
}
public List<String> getBusiness() {
return business;
}
public void setBusiness(List<String> business) {
this.business = business;
}
public List<String> getProduct() {
return product;
}
public void setProduct(List<String> product) {
this.product = product;
}
}
| true |
0601dd82300dfb0eaf07ac6e8970f3223ef3550a | Java | jenkins-infra/update-center2 | /src/main/java/io/jenkins/update_center/LatestLinkBuilder.java | UTF-8 | 1,665 | 2.421875 | 2 | [] | no_license | package io.jenkins.update_center;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Generates latest/index.html and latest/.htaccess
*
* The former lists all the available symlinks, and the latter actually defines the redirects.
*
*/
public class LatestLinkBuilder implements AutoCloseable {
private static final Logger LOGGER = Logger.getLogger(LatestLinkBuilder.class.getName());
private final IndexHtmlBuilder index;
private final PrintWriter htaccess;
public LatestLinkBuilder(File dir, IndexTemplateProvider service) throws IOException {
LOGGER.log(Level.FINE, String.format("Writing plugin symlinks and redirects to dir: %s", dir));
index = service.newIndexHtmlBuilder(dir,"Permalinks to latest files");
htaccess = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir,".htaccess"), true), StandardCharsets.UTF_8));
htaccess.println("# GENERATED. DO NOT MODIFY.");
// Redirect directive doesn't let us write redirect rules relative to the directory .htaccess exists,
// so we are back to mod_rewrite
htaccess.println("RewriteEngine on");
}
public void close() {
index.close();
htaccess.close();
}
public void add(String localPath, String target) throws IOException {
htaccess.printf("RewriteRule ^%s$ %s [R=302,L]%n", localPath.replace(".", "\\."), target);
index.add(localPath, localPath);
}
}
| true |
ffbfcd73a0c652feb3c8adcac5a48f177ef10198 | Java | NKSEProjectTeam/NKSEProject | /Exchange/src/com/nankai/exchange/biz/impl/FindRequestBizImpl.java | UTF-8 | 11,350 | 1.859375 | 2 | [
"MIT"
] | permissive | package com.nankai.exchange.biz.impl;
import java.util.ArrayList;
import java.util.List;
import com.nankai.exchange.biz.IFindRequestBiz;
//import com.nankai.exchange.biz.INewBiz;
import com.nankai.exchange.dao.IBagsDao;
import com.nankai.exchange.dao.ICosmeticsDao;
import com.nankai.exchange.dao.IDailyprosDao;
import com.nankai.exchange.dao.IDigitsDao;
import com.nankai.exchange.dao.IElectricsDao;
import com.nankai.exchange.dao.IEntertainmentsDao;
import com.nankai.exchange.dao.IExtrabooksDao;
import com.nankai.exchange.dao.IFemalesDao;
import com.nankai.exchange.dao.IMalesDao;
import com.nankai.exchange.dao.IPcDao;
import com.nankai.exchange.dao.IPhonesDao;
import com.nankai.exchange.dao.ISpprosDao;
import com.nankai.exchange.dao.ITextbooksDao;
import com.nankai.exchange.dao.impl.BagsDaoImpl;
import com.nankai.exchange.dao.impl.CosmeticsDaoImpl;
import com.nankai.exchange.dao.impl.DailyprosDaoImpl;
import com.nankai.exchange.dao.impl.DigitsDaoImpl;
import com.nankai.exchange.dao.impl.ElectricsDaoImpl;
import com.nankai.exchange.dao.impl.EntertainmentsDaoImpl;
import com.nankai.exchange.dao.impl.ExtralbooksDaoImpl;
import com.nankai.exchange.dao.impl.FemalesDaoImpl;
import com.nankai.exchange.dao.impl.MalesDaoImpl;
import com.nankai.exchange.dao.impl.PcDaoImpl;
import com.nankai.exchange.dao.impl.PhonesDaoImpl;
import com.nankai.exchange.dao.impl.SpprosDaoImpl;
import com.nankai.exchange.dao.impl.TextbooksDaoImpl;
import com.nankai.exchange.po.Bags;
import com.nankai.exchange.po.Cosmetics;
import com.nankai.exchange.po.Dailypros;
import com.nankai.exchange.po.Digits;
import com.nankai.exchange.po.Electrics;
import com.nankai.exchange.po.Entertainments;
import com.nankai.exchange.po.Extrabooks;
import com.nankai.exchange.po.Females;
import com.nankai.exchange.po.Males;
import com.nankai.exchange.po.Pc;
import com.nankai.exchange.po.Phones;
import com.nankai.exchange.po.Sppros;
import com.nankai.exchange.po.Textbooks;
public class FindRequestBizImpl implements IFindRequestBiz{
public List<List<?>> findRequestState(String msg) {
// TODO Auto-generated method stub
//List<List<?>> lstGoods = new ArrayList<List<?>>();
List<List<?>> lstStateZero = new ArrayList<List<?>>();
List<?> lst;
// msg鐨勬牸寮忎负锛氱被鍒悕1//绫诲埆鍚�//鈥︹�
String[] types = msg.split("//");
for(int i = 0; i < types.length; i++) {
//System.out.println(types[i]);
switch(types[i]) {
case "textbooks":
ITextbooksDao textbooksDao = new TextbooksDaoImpl();
lst = textbooksDao.selectAll();
List<Object> lstex1=new ArrayList<Object>();
//System.out.println(lst);
Textbooks textbooks=new Textbooks();
for(int j=0;j<lst.size();j++)
{
textbooks=(Textbooks) lst.get(j);
//System.out.println(textbooks);
//System.out.println(textbooks.getTbstate());
if(textbooks.getTbstate()==2){
lstex1.add(textbooks);
}
}
if(lstex1.size() < 8) {
lstStateZero.add(lstex1);
} else {
lstex1 = lstex1.subList(lstex1.size() - 8, lstex1.size());
lstStateZero.add(lstex1);
}
//System.out.println(lstStateZero);
break;
case "extrabooks":
IExtrabooksDao extrabooksDao = new ExtralbooksDaoImpl();
lst = extrabooksDao.selectAll();
//System.out.println(lst);
Extrabooks extrabooks=new Extrabooks();
List<Object> lstex2=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
extrabooks=(Extrabooks) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(extrabooks.getEbstate()==2){
lstex2.add(extrabooks);
}
}
if(lstex2.size() < 8) {
lstStateZero.add(lstex2);
} else {
lstex2 = lstex2.subList(lstex2.size() - 8, lstex2.size());
lstStateZero.add(lstex2);
}
//System.out.println(lstStateZero);
break;
case "pc":
IPcDao pcDao = new PcDaoImpl();
lst = pcDao.selectAll();
Pc pc=new Pc();
List<Object> lstex3=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
pc=(Pc) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(pc.getPcstate()==2){
lstex3.add(pc);
}
}
if(lstex3.size() < 8) {
lstStateZero.add(lstex3);
} else {
lstex3 = lstex3.subList(lstex3.size() - 8, lstex3.size());
lstStateZero.add(lstex3);
}
break;
case "phones":
IPhonesDao phonesDao = new PhonesDaoImpl();
lst = phonesDao.selectAll();
Phones phones=new Phones();
List<Object> lstex4=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
phones=(Phones) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(phones.getPhonestate()==2){
lstex4.add(phones);
}
}
if(lstex4.size() < 8) {
lstStateZero.add(lstex4);
} else {
lstex4 = lstex4.subList(lstex4.size() - 8, lstex4.size());
lstStateZero.add(lstex4);
}
break;
case "digits":
IDigitsDao digitsDao = new DigitsDaoImpl();
lst = digitsDao.selectAll();
Digits digits=new Digits();
List<Object> lstex5=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
digits=(Digits) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(digits.getDigitstate()==2){
lstex5.add(digits);
}
}
if(lstex5.size() < 8) {
lstStateZero.add(lstex5);
} else {
lstex5 = lstex5.subList(lstex5.size() - 8, lstex5.size());
lstStateZero.add(lstex5);
}
break;
case "dailypros":
IDailyprosDao dailyprosDao = new DailyprosDaoImpl();
lst = dailyprosDao.selectAll();
Dailypros dailypros=new Dailypros();
List<Object> lstex6=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
dailypros=(Dailypros) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(dailypros.getDpstate()==2){
lstex6.add(dailypros);
}
}
if(lstex6.size() < 8) {
lstStateZero.add(lstex6);
} else {
lstex6 = lstex6.subList(lstex6.size() - 8, lstex6.size());
lstStateZero.add(lstex6);
}
break;
case "entertainments":
IEntertainmentsDao entertainmentsDao = new EntertainmentsDaoImpl();
lst = entertainmentsDao.selectAll();
Entertainments entertainments=new Entertainments();
List<Object> lstex7=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
entertainments=(Entertainments) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(entertainments.getEnterstate()==2){
lstex7.add(entertainments);
}
}
if(lstex7.size() < 8) {
lstStateZero.add(lstex7);
} else {
lstex7 = lstex7.subList(lstex7.size() - 8, lstex7.size());
lstStateZero.add(lstex7);
}
break;
case "electrics":
IElectricsDao electricsDao = new ElectricsDaoImpl();
lst = electricsDao.selectAll();
Electrics electrics=new Electrics();
List<Object> lstex8=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
electrics=(Electrics) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(electrics.getElestate()==2){
lstex8.add(electrics);
}
}
if(lstex8.size() < 8) {
lstStateZero.add(lstex8);
} else {
lstex8 = lstex8.subList(lstex8.size() - 8, lstex8.size());
lstStateZero.add(lstex8);
}
break;
case "cosmetics":
ICosmeticsDao cosmeticsDao = new CosmeticsDaoImpl();
lst = cosmeticsDao.selectAll();
Cosmetics cosmetics=new Cosmetics();
List<Object> lstex9=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
cosmetics=(Cosmetics) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(cosmetics.getCosstate()==2){
lstex9.add(cosmetics);
}
}
if(lstex9.size() < 8) {
lstStateZero.add(lstex9);
} else {
lstex9 = lstex9.subList(lstex9.size() - 8, lstex9.size());
lstStateZero.add(lstex9);
}
break;
case "sppros":
ISpprosDao spprosDao = new SpprosDaoImpl();
lst = spprosDao.selectAll();
Sppros sppros=new Sppros();
List<Object> lstex10=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
sppros=(Sppros) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(sppros.getSpstate()==2){
lstex10.add(sppros);
}
}
if(lstex10.size() < 8) {
lstStateZero.add(lstex10);
} else {
lstex10 = lstex10.subList(lstex10.size() - 8, lstex10.size());
lstStateZero.add(lstex10);
}
break;
case "females":
IFemalesDao femalesDao = new FemalesDaoImpl();
lst = femalesDao.selectAll();
Females females=new Females();
List<Object> lstex11=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
females=(Females) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(females.getFemalestate()==2){
lstex11.add(females);
}
}
if(lstex11.size() < 8) {
lstStateZero.add(lstex11);
} else {
lstex11 = lstex11.subList(lstex11.size() - 8, lstex11.size());
lstStateZero.add(lstex11);
}
break;
case "males":
IMalesDao malesDao = new MalesDaoImpl();
lst = malesDao.selectAll();
Males males=new Males();
List<Object> lstex12=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
males=(Males) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(males.getMalestate()==2){
lstex12.add(males);
}
}
if(lstex12.size() < 8) {
lstStateZero.add(lstex12);
} else {
lstex12 = lstex12.subList(lstex12.size() - 8, lstex12.size());
lstStateZero.add(lstex12);
}
break;
case "bags":
IBagsDao bagsDao = new BagsDaoImpl();
lst = bagsDao.selectAll();
Bags bags=new Bags();
List<Object> lstex13=new ArrayList<Object>();
for(int j=0;j<lst.size();j++)
{
bags=(Bags) lst.get(j);
//System.out.println(extrabooks);
//System.out.println(extrabooks.getEbstate());
if(bags.getBagstate()==2){
lstex13.add(bags);
}
}
if(lstex13.size() < 8) {
lstStateZero.add(lstex13);
} else {
lstex13 = lstex13.subList(lstex13.size() - 8, lstex13.size());
lstStateZero.add(lstex13);
}
break;
}
// }
// IAudiosDao audiosDao = new AudiosDaoImpl();
// lst = audiosDao.selectAll();
// lstGoods.add(lst.get(lst.size() - 1));
}
return lstStateZero;
}
// public static void main(String[] args){
//
// List<List<?>> lstStateZero=findState("textbooks//extrabooks//pc//phones//bags//female//male//sppros//cosmetics//electrics//entertainments//dailypros//digits");
// System.out.println(lstStateZero);
// }
}
| true |
5d92333841de4f13e6f1b577f01ba94728fbba34 | Java | narendraprasadr/ArtemisFW | /RestAssuredLearning/src/com/keystone/Newmap.java | UTF-8 | 237 | 1.75 | 2 | [] | no_license | package com.keystone;
import java.util.HashMap;
public class Newmap {
HashMap<String,String> mp = new HashMap<String, String>(){
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("aa","xy");
}
};
}
| true |
278bb88b9aac01cf9f308ded460dcec421440677 | Java | huaxiufeng/leetcode | /src/algorithm/java/LC355DesignTwitter.java | UTF-8 | 5,319 | 3.546875 | 4 | [] | no_license | package algorithm.java;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
/**
* Created by huaxiufeng on 19/2/27.
*/
public class LC355DesignTwitter {
static class Twitter {
private final int FEED_LIMIT = 10;
private static int gtime = 0;
private Map<Integer, User> userMap = new HashMap<>();
static class Tweet {
public int tweetId;
public int userId;
public int time;
public Tweet(int tweetId, int userId) {
this.tweetId = tweetId;
this.userId = userId;
this.time = gtime++;
}
}
static class User {
public int userId;
public LinkedList<Tweet> tweets = new LinkedList<>();
public Set<Integer> followSet = new HashSet<>(); // 我关注了哪些人
public User(int userId) {
this.userId = userId;
}
public void follow(int followeeId) {
if (followeeId != this.userId) {
followSet.add(followeeId);
}
}
public void unfollow(int followeeId) {
followSet.remove(followeeId);
}
public void postTweet(int tweetId) {
tweets.addFirst(new Tweet(tweetId, this.userId));
}
}
/** Initialize your data structure here. */
public Twitter() {
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
registerUserIfNecessary(userId);
User user = userMap.get(userId);
user.postTweet(tweetId);
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
public List<Integer> getNewsFeed(int userId) {
LinkedList<Integer> result = new LinkedList<>();
User user = userMap.get(userId);
if (null == user) {
return result;
}
PriorityQueue<Tweet> queue = new PriorityQueue<>(FEED_LIMIT, new Comparator<Tweet>() {
@Override
public int compare(Tweet o1, Tweet o2) {
return Integer.compare(o1.time, o2.time);
}
});
for (Tweet tweet : user.tweets) {
addTweetQueue(queue, tweet);
}
for (int followeeId : user.followSet) {
User followee = userMap.get(followeeId);
if (followee == null) {
continue;
}
for (Tweet tweet : followee.tweets) {
addTweetQueue(queue, tweet);
}
}
while (!queue.isEmpty()) {
result.addFirst(queue.poll().tweetId);
}
return result;
}
private void addTweetQueue(PriorityQueue<Tweet> queue, Tweet tweet) {
if (queue.size() >= FEED_LIMIT && tweet.time < queue.peek().time) {
return;
}
queue.offer(tweet);
if (queue.size() > FEED_LIMIT) {
queue.poll();
}
}
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
public void follow(int followerId, int followeeId) {
registerUserIfNecessary(followerId);
registerUserIfNecessary(followeeId);
User user = userMap.get(followerId);
user.follow(followeeId);
}
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
public void unfollow(int followerId, int followeeId) {
User user = userMap.get(followerId);
if (user != null) {
user.unfollow(followeeId);
}
}
private void registerUserIfNecessary(int userId) {
if (!userMap.containsKey(userId)) {
userMap.put(userId, new User(userId));
}
}
}
public static void main(String[] args) {
Twitter twitter = new Twitter();
// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);
// User 1's news feed should return a list with 1 tweet id -> [5].
System.out.println(twitter.getNewsFeed(1));
// User 1 follows user 2.
twitter.follow(1, 2);
// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);
twitter.postTweet(1, 7);
// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
System.out.println(twitter.getNewsFeed(1));
// User 1 unfollows user 2.
twitter.unfollow(1, 2);
// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
System.out.println(twitter.getNewsFeed(1));
}
}
| true |
9a72567f557825ea68915028ee1dc4741f592fbc | Java | sengeiou/yunding_website2.0 | /src/main/java/com/yundingshuyuan/website/enums/ErrorCodeEnum.java | UTF-8 | 1,969 | 2.5 | 2 | [] | no_license | package com.yundingshuyuan.website.enums;
import lombok.Getter;
/**
* @author: leeyf
* @create: 2019-01-29 17:54
* @Description: 错误类型
*/
@Getter
public enum ErrorCodeEnum {
/**
* 参数错误
*/
PARAM_ERROR(1001,"上传参数错误"),
/**
* 验证码错误
*/
CODE_ERROR(1002,"验证码获取错误"),
PHONE_CODE_ERROR(1003,"手机验证码错误"),
USER_EXISTS(1004,"用户已存在"),
PASSWORD_ERROR(1005,"用户名或密码错误"),
PASSWORD_MORE_ERROR(1008,"密码错误次数太多"),
USERNAME_ERROR(1006,"用户名错误"),
USER_NO_ERROR(1006,"用户不存在"),
JSON_TRANS_ERROR(1007,"JSON转化错误"),
USER_IDENTITY_ERROR(2001,"用户权限错误"),
ERROR_TOKEN(401,"token错误"),
USER_ERROR(1009,"用户错误"),
USER_ROLE_ERROR(1010,"用户角色错误"),
USER_ENSHRINE_ERROR(1101,"添加个人收藏错误"),
USER_ENSHRINE_EXISTS(1102,"个人收藏已存在"),
USER_FANS_EXISTS(1202,"已经关注过了"),
USER_PHONE_USED(501,"该手机号已注册"),
USER_EMAIL_USED(501,"该邮箱已注册"),
UK_KNOW_ERROR(500,"未知异常"),
IMAGE_UPLOAD_ERROR(1103,"图片上传错误"),
IDENTITY_UN_ADMIN(555,"用户权限不足"),
IDENTITY_ERROR(1009,"User身份错误(未激活)"),
ARTICLE_UNEXIST(3001,"文章id无效"),
ARTICLE_SUPPORTED(3002,"已经点赞"),
UPLOAD_NOT_EMPTY(4001,"上传文件不能为空"),
BELONG_EXIST(3003,"归属关系已存在"),
NOT_SCORE(3008,"打分已进入核算阶段,禁止打分"),
RESPUSERNAME_EMPTY(3009,"请去个人中心填写真实姓名")
;
ErrorCodeEnum(Integer code, String msg){
this.code =code;
this.msg = msg;
}
Integer code;
String msg;
public <T> T getMsg() {
return (T) msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
} | true |
c7c9dc3089470de9eec1dc197a47d45a1214bb46 | Java | jygt/helloworld | /src/main/java/com/example/helloWorld/DruidConfiguration.java | UTF-8 | 1,474 | 1.992188 | 2 | [] | no_license | package com.example.helloWorld;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletRegistration;
@Configuration
public class DruidConfiguration {
@Bean
public ServletRegistrationBean druidStatViewServlet(){
ServletRegistrationBean slBean = new ServletRegistrationBean(
new StatViewServlet(),"/druid/*");
// 白名单
slBean.addInitParameter("allow","127.0.0.1");
// 黑名单
slBean.addInitParameter("deny","192.168.1.1");
// user
slBean.addInitParameter("loginUsername","admin");
// passwd
slBean.addInitParameter("loginPassword","123456");
// 是否可以重置数据
slBean.addInitParameter("resetEnable","false");
return slBean;
}
@Bean
public FilterRegistrationBean druidStatFilter(){
FilterRegistrationBean frBean = new FilterRegistrationBean(
new WebStatFilter());
frBean.addUrlPatterns("/*");
frBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.css,*.ico,/druid/*");
return frBean;
}
}
| true |
49fb4ec138b249eee1a6f74fb3c3280bed68b56b | Java | apache/myfaces | /impl/src/main/java/org/apache/myfaces/context/servlet/FacesContextImpl.java | UTF-8 | 13,446 | 1.5625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.myfaces.context.servlet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jakarta.faces.FactoryFinder;
import jakarta.faces.application.ApplicationFactory;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
import jakarta.faces.context.PartialViewContext;
import jakarta.faces.context.PartialViewContextFactory;
import jakarta.faces.context.ResponseStream;
import jakarta.faces.context.ResponseWriter;
import jakarta.faces.event.PhaseId;
import jakarta.faces.lifecycle.Lifecycle;
import jakarta.faces.render.RenderKit;
import jakarta.faces.render.RenderKitFactory;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.apache.myfaces.cdi.FacesScopeContext;
import org.apache.myfaces.cdi.view.ViewTransientScopeContext;
import org.apache.myfaces.util.ExternalSpecifications;
import org.apache.myfaces.context.ReleasableFacesContextFactory;
import org.apache.myfaces.core.api.shared.lang.Assert;
/**
* @author Manfred Geiler (latest modification by $Author$)
* @author Anton Koinov
* @version $Revision$ $Date$
*/
public class FacesContextImpl extends FacesContextImplBase
{
// ~ Instance fields ----------------------------------------------------------------------------
private Map<String, List<FacesMessage>> _messages = null;
private PhaseId _currentPhaseId;
private ResponseStream _responseStream = null;
private ResponseWriter _responseWriter = null;
private FacesMessage.Severity _maximumSeverity = null;
private boolean _renderResponse = false;
private boolean _responseComplete = false;
private boolean _validationFailed = false;
private PartialViewContext _partialViewContext = null;
private ReleasableFacesContextFactory _facesContextFactory = null;
private PartialViewContextFactory _partialViewContextFactory = null;
private RenderKitFactory _renderKitFactory = null;
private Lifecycle _lifecycle = null;
// ~ Constructors -------------------------------------------------------------------------------
/**
* Creates a FacesContextImpl with a ServletExternalContextImpl.
*/
public FacesContextImpl(final ServletContext servletContext, final ServletRequest servletRequest,
final ServletResponse servletResponse)
{
this(new ServletExternalContextImpl(servletContext, servletRequest, servletResponse));
}
/**
* Private constructor used in internal constructor chain.
* @param externalContext the external context
*/
private FacesContextImpl(ServletExternalContextImpl externalContext)
{
this(externalContext, externalContext, null);
}
/**
* Creates a FacesContextImpl with the given ExternalContext,
* ReleasableExternalContext and ReleasableFacesContextFactory.
* @param externalContext the external context
* @param defaultExternalContext the default context if the external context is null
* @param facesContextFactory the factory for creating context
*/
public FacesContextImpl(final ExternalContext externalContext,
final ExternalContext defaultExternalContext ,
final ReleasableFacesContextFactory facesContextFactory)
{
// setCurrentInstance is called in constructor of super class
super(externalContext, defaultExternalContext);
_facesContextFactory = facesContextFactory;
}
public FacesContextImpl(final ExternalContext externalContext,
final ExternalContext defaultExternalContext ,
final ReleasableFacesContextFactory facesContextFactory,
final ApplicationFactory applicationFactory,
final RenderKitFactory renderKitFactory,
final PartialViewContextFactory partialViewContextFactory,
final Lifecycle lifecycle)
{
// setCurrentInstance is called in constructor of super class
super(externalContext, defaultExternalContext, applicationFactory,
renderKitFactory);
_facesContextFactory = facesContextFactory;
_renderKitFactory = renderKitFactory;
_partialViewContextFactory = partialViewContextFactory;
_lifecycle = lifecycle;
}
// ~ Methods ------------------------------------------------------------------------------------
@Override
public final void release()
{
assertNotReleased();
if (ExternalSpecifications.isCDIAvailable(getExternalContext()))
{
ViewTransientScopeContext.destroyAll(this);
FacesScopeContext.destroyAll(this);
}
_messages = null;
_currentPhaseId = null;
_responseStream = null;
_responseWriter = null;
_maximumSeverity = null;
_partialViewContext = null;
_renderKitFactory = null;
_partialViewContextFactory = null;
_lifecycle = null;
if (_facesContextFactory != null)
{
_facesContextFactory.release();
_facesContextFactory = null;
}
// release FacesContextImplBase (sets current instance to null)
super.release();
}
@Override
public final FacesMessage.Severity getMaximumSeverity()
{
assertNotReleased();
return _maximumSeverity;
}
@Override
public final void addMessage(final String clientId, final FacesMessage message)
{
assertNotReleased();
Assert.notNull(message, "message");
if (_messages == null)
{
_messages = new LinkedHashMap<>(5, 1f);
}
List<FacesMessage> lst = _messages.computeIfAbsent(clientId, k -> new ArrayList<>(3));
lst.add(message);
FacesMessage.Severity serSeverity = message.getSeverity();
if (serSeverity != null)
{
if (_maximumSeverity == null)
{
_maximumSeverity = serSeverity;
}
else if (serSeverity.compareTo(_maximumSeverity) > 0)
{
_maximumSeverity = serSeverity;
}
}
}
@Override
public List<FacesMessage> getMessageList()
{
assertNotReleased();
if (_messages == null || _messages.size() == 0)
{
return Collections.emptyList();
}
List<FacesMessage> orderedMessages = new ArrayList<>();
for (List<FacesMessage> list : _messages.values())
{
orderedMessages.addAll(list);
}
return Collections.unmodifiableList(orderedMessages);
}
@Override
public List<FacesMessage> getMessageList(String clientId)
{
assertNotReleased();
if (_messages == null || !_messages.containsKey(clientId))
{
return Collections.emptyList();
}
return _messages.get(clientId);
}
@Override
public final Iterator<FacesMessage> getMessages()
{
assertNotReleased();
if (_messages == null || _messages.size() == 0)
{
List<FacesMessage> emptyList = Collections.emptyList();
return emptyList.iterator();
}
return new FacesMessageIterator(_messages);
}
@Override
public final Iterator<FacesMessage> getMessages(final String clientId)
{
assertNotReleased();
if (_messages == null || !_messages.containsKey(clientId))
{
return Collections.emptyIterator();
}
return _messages.get(clientId).iterator();
}
@Override
public final Iterator<String> getClientIdsWithMessages()
{
assertNotReleased();
if (_messages == null || _messages.isEmpty())
{
return Collections.emptyIterator();
}
return _messages.keySet().iterator();
}
@Override
public PhaseId getCurrentPhaseId()
{
assertNotReleased();
return _currentPhaseId;
}
@Override
public void setCurrentPhaseId(PhaseId currentPhaseId)
{
assertNotReleased();
_currentPhaseId = currentPhaseId;
}
@Override
public PartialViewContext getPartialViewContext()
{
assertNotReleased();
if (_partialViewContext == null)
{
//Get through factory finder
if (_partialViewContextFactory == null)
{
_partialViewContextFactory = (PartialViewContextFactory)
FactoryFinder.getFactory(FactoryFinder.PARTIAL_VIEW_CONTEXT_FACTORY);
}
// Put actual facesContext as param, not this - this can be wrapped
_partialViewContext = _partialViewContextFactory.getPartialViewContext(getCurrentFacesContext());
}
return _partialViewContext;
}
@Override
public final boolean getRenderResponse()
{
assertNotReleased();
return _renderResponse;
}
@Override
public final void renderResponse()
{
assertNotReleased();
_renderResponse = true;
}
@Override
public final boolean getResponseComplete()
{
assertNotReleased();
return _responseComplete;
}
@Override
public final void responseComplete()
{
assertNotReleased();
_responseComplete = true;
}
@Override
public final void setResponseStream(final ResponseStream responseStream)
{
assertNotReleased();
Assert.notNull(responseStream, "responseStream");
_responseStream = responseStream;
}
@Override
public final ResponseStream getResponseStream()
{
assertNotReleased();
return _responseStream;
}
@Override
public final void setResponseWriter(final ResponseWriter responseWriter)
{
assertNotReleased();
Assert.notNull(responseWriter, "responseWriter");
_responseWriter = responseWriter;
}
@Override
public final ResponseWriter getResponseWriter()
{
assertNotReleased();
return _responseWriter;
}
@Override
public boolean isPostback()
{
assertNotReleased();
RenderKit renderKit = getRenderKit();
FacesContext facesContext = getCurrentFacesContext();
if (renderKit == null)
{
// NullPointerException with StateManager, because
// to restore state it first restore structure,
// then fill it and in the middle of the two previous
// process there is many calls from _ComponentChildrenList.childAdded
// to facesContext.isPostback, and getViewRoot is null.
//
// Setting a "phantom" UIViewRoot calling facesContext.setViewRoot(viewRoot)
// to avoid it is bad, because this is work of RestoreViewExecutor,
// and theoretically ViewHandler.restoreView must return an UIViewRoot
// instance.
//
// The problem with this is if the user changes the renderkit directly
// using f:view renderKitId param, the ResponseStateManager returned
// will be the one tied to faces-config selected RenderKit. But the usual
// method to check if a request is a postback, is always detect the param
// jakarta.faces.ViewState, so there is no problem after all.
String renderKitId = facesContext.getApplication().getViewHandler().calculateRenderKitId(facesContext);
if (_renderKitFactory == null)
{
_renderKitFactory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
}
renderKit = _renderKitFactory.getRenderKit(facesContext, renderKitId);
}
return renderKit.getResponseStateManager().isPostback(facesContext);
}
@Override
public void validationFailed()
{
assertNotReleased();
_validationFailed = true;
}
@Override
public boolean isValidationFailed()
{
assertNotReleased();
return _validationFailed;
}
@Override
public Lifecycle getLifecycle()
{
assertNotReleased();
return _lifecycle;
}
} | true |
f8bdcfd0f4fc70b966a9e0b21752c6e54adf26da | Java | kartikadhiainfinit/CCTChatService | /src/java/de/infinit/chatservice/Constants.java | UTF-8 | 736 | 1.796875 | 2 | [] | no_license | package de.infinit.chatservice;
public class Constants {
public static final String VERSION = "1.0.4.0";
public static final String TENANT_NAME_DEFAULT = "Telefonica_DE";
// LCA default values
public static final String LCA_HOST_DEFAULT = "localhost";
public static final int LCA_PORT_DEFAULT = 4999;
// GMS Node connection
public static final int GMS_RECONNECTION_TIMEOUT_SEC = 30;
// Configuration
public static final String CONF_PROTOCOL_NAME = "ccwServiceProtocol";
// ooh change event prefix
public static final String OOH_EVENT_PREFIX = "oohChange";
public static final Object MESSAGE_TRANSFERED = "--- Chat wird weitergeleitet... ---";
}
| true |
20fc39b19b40cceb2345db2167070179fe4e974e | Java | jieminy/yzt_demo | /yzt-demo-algorithm/src/main/java/com/yzt/jm/algorithm/search/str/RabinKarpMatcher.java | UTF-8 | 1,571 | 3.171875 | 3 | [] | no_license | package com.yzt.jm.algorithm.search.str;
import java.util.HashMap;
import java.util.Map;
/**
* @description: Rabin-Karp算法
* @author: jiemin
* @date: 2020-09-09 09:16
*/
public class RabinKarpMatcher {
/**
* 时间复杂度 o(n)
* @param majorStr
* @param pattenStr
* @return
*/
public static int match(String majorStr, String pattenStr){
int majorLength = majorStr.length();
int pattenLength = pattenStr.length();
if(majorLength == 0 || pattenLength == 0){
return -1;
}
char[] majors = majorStr.toCharArray();
char[] patten = pattenStr.toCharArray();
int pattenHash = 0;
int[] s = new int[pattenLength];
int[] h = new int[majorLength - pattenLength + 1];
for(int j = 0; j < pattenLength; j ++){
s[pattenLength - j -1] = power(26, pattenLength - j -1);
pattenHash += (patten[j] - 'a') * s[pattenLength - j -1];
h[0] += (majors[j] - 'a') * s[pattenLength - j -1];
}
if(pattenHash == h[0]){
return 0;
}
for(int i=1; i <= majorLength - pattenLength; i++){
h[i] += (h[i-1] - s[pattenLength -1] * (majors[i-1] - 'a')) * 26 + (majors[i + pattenLength - 1] - 'a');
if(pattenHash == h[i]){
return i;
}
}
return -1;
}
public static int power(int a , int b) {
int power = 1;
for (int c = 0; c < b; c++){
power *= a;
}
return power;
}
}
| true |
e82fbf262fce4bde34d809d9d97525031afb2d48 | Java | bobo19870225/LastCPT | /app/src/main/java/www/jingkan/com/view/chart/InterfaceDrawChartStrategy.java | UTF-8 | 725 | 2.34375 | 2 | [] | no_license | /*
* Copyright (c) 2018. 代码著作权归卢声波所有。
*/
package www.jingkan.com.view.chart;
import org.achartengine.util.IndexXYMap;
import java.util.List;
/**
* Created by lushengbo on 2018/1/4.
* 画图策略
*/
public interface InterfaceDrawChartStrategy {
void addOnePointToChart(float[] data);
void addPointsToChart(List<float[]> listData);
void upDataSeriesQc(int index, double x, double y);
void upDataSeriesFs(int index, double x, double y);
void upDataSeriesFa(int index, double x, double y);
IndexXYMap<Double, Double> getSeriesQcData();
IndexXYMap<Double, Double> getSeriesFsData();
IndexXYMap<Double, Double> getSeriesFaData();
void cleanChart();
}
| true |
08d3ff38a4f4f0d0b7c87a8fc1eb95b2df87604a | Java | phil-rice/Arc4Eclipse | /SoftwareFmImages/src/main/java/org/softwareFm/softwareFmImages/BasicImageRegister.java | UTF-8 | 1,814 | 2.28125 | 2 | [] | no_license | package org.softwareFm.softwareFmImages;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.widgets.Display;
import org.softwareFm.softwareFmImages.artifacts.ArtifactsAnchor;
import org.softwareFm.softwareFmImages.backdrop.BackdropAnchor;
import org.softwareFm.softwareFmImages.general.GeneralAnchor;
import org.softwareFm.softwareFmImages.overlays.OverlaysAnchor;
import org.softwareFm.softwareFmImages.smallIcons.SmallIconsAnchor;
import org.softwareFm.swtBasics.images.Images;
public class BasicImageRegister implements IImageRegister {
@Override
public void registerWith(Device device, ImageRegistry imageRegistry) {
Images.registerImages(device, imageRegistry, BackdropAnchor.class, "backdrop", "main", "depressed");
Images.registerImages(device, imageRegistry, ArtifactsAnchor.class, "artifact", //
"jar", "jarClearEclipse", "jarCopyFromSoftwareFm", "jarCopyToSoftwareFm", //
"document", "issues", "license", "mailingList", "merchandise", "organisation", "project",//
"news", "recruitment", "tutorials", "twitter");
Images.registerImages(device, imageRegistry, OverlaysAnchor.class, "overlay", "add", "delete", "edit");
Images.registerImages(device, imageRegistry, SmallIconsAnchor.class, "smallIcon", "softwareFm", "javadoc", "source");
Images.registerImages(device, imageRegistry, GeneralAnchor.class, "general", "browse", "help", "clear");
}
public static void main(String[] args) {
Display device = new Display();
ImageRegistry imageRegistry = new ImageRegistry();
new BasicImageRegister().registerWith(device, imageRegistry);
System.out.println(imageRegistry.get("artifact.jar"));
System.out.println(imageRegistry.get("backdrop.main"));
System.out.println(imageRegistry.get("general.browse"));
}
}
| true |
d8beb4e0151daa425259941f68be8bf2acff23c0 | Java | AmardeepPawar/ATREE | /AtreeGUI/src/controllers/SelectWorkSpaceController.java | UTF-8 | 4,105 | 2.09375 | 2 | [] | no_license | package controllers;
import java.io.File;
import java.util.Map;
import application.ATreeWorkSpace;
import application.KeyValueMapping;
import application.PopUpWindow;
import application.beans.ModulesGroupPropertyBean;
import caseDesigner.CurrentStatusIndicatorVariables;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import popUpWindowBeans.PopUpWindowBeans;
import popUpWindowBeans.SelectModuleTypeBean;
import popUpWindowBeans.SelectWorkSpaceBean;
public class SelectWorkSpaceController implements AtreeSingleStageGUIController{
@FXML
Button okbutton = new Button();
@FXML
Button cancelButton = new Button();
@FXML
Button DirectoryChooser = new Button();
@FXML
TextField workSpaceName = new TextField();
@FXML
Label selectStepMsgBx = new Label();
@FXML
HBox labelHBox = new HBox();
@FXML
Label noteId = new Label();
static boolean flagSW = true;
Stage stage;
static int numberOfRows;
PopUpWindow selModType;
public void initialize() {
selModType = PopUpWindow.getInstance();
KeyValueMapping keyValMap = KeyValueMapping.getInstance();
Map<String,ModulesGroupPropertyBean> modGrpMap = keyValMap.getModulesGroupPropertyBean();
selectStepMsgBx.setMaxWidth(300);
selectStepMsgBx.setMaxHeight(200);
numberOfRows = modGrpMap.size()/2 + modGrpMap.size()%2;
DirectoryChooser.setOnAction(e -> {
javafx.stage.DirectoryChooser directoryChooser = new javafx.stage.DirectoryChooser();
stage = (Stage) cancelButton.getScene().getWindow();
File selectedDirectory = directoryChooser.showDialog(stage);
if (selectedDirectory != null) {
workSpaceName.setText(selectedDirectory.getAbsolutePath());
}
});
/*PopUpWindow.popUPStage.setOnCloseRequest(e -> closeMainWindow());*/
okbutton.setOnAction(e -> {
String workSpace = workSpaceName.getText().trim();
GUIController.setSelectedItem(null);
GUIController.setIconOnDisplay();
File foldername = new File(workSpace);
if (foldername.exists() && foldername.isDirectory()) {
ATreeWorkSpace.setAtreeWorkSpace(workSpace);
GUIController.activeItem = null;
GUIController.displayTreeContent();
stage = (Stage) cancelButton.getScene().getWindow();
stage.close();
flagSW = false;
try {
double sceneHeight = 125;
if (numberOfRows > 2) {
sceneHeight = 125 + (22 * (numberOfRows - 1));
}
PopUpWindowBeans selectModuleTypeBean = SelectModuleTypeBean.getInstaceOfClass();
selectModuleTypeBean.setHeight(sceneHeight);
selModType.prepareStage(selectModuleTypeBean);
//Once new workSpace selected reset/clear all case and step parameters which was active before ws change.
CurrentStatusIndicatorVariables.resetStepParameters();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
selectStepMsgBx.setMaxWidth(350);
labelHBox.setPrefHeight(55);
if((SelectWorkSpaceBean.getInstaceOfClass().getHeight() + 50) == PopUpWindow.getPopUPStage().getHeight()){
selModType.setStageHeight(PopUpWindow.getPopUPStage().getHeight() + 30);
}
noteId.setText("Note: ");
selectStepMsgBx.setText("\"" + workSpace + "\" workspace does not exist.");
selectStepMsgBx.setWrapText(true);
selectStepMsgBx.setTextAlignment(TextAlignment.JUSTIFY);
}
});
cancelButton.setOnAction(e -> {
Stage stage = (Stage) cancelButton.getScene().getWindow();
stage.close();
});
}
/* public void closeMainWindow(){
if(flagSW)
{
Main.closeMainWindow();
}
}*/
@Override
public void clearElementsTextValues() {
// TODO Auto-generated method stub
selectStepMsgBx.setText("");
noteId.setText("");
labelHBox.setPrefHeight(5);
}
@Override
public void setElementsTextValues() {
// TODO Auto-generated method stub
}
}
| true |
ba48985731f67ab3d42c502fcdf70cfa6cf2fb9b | Java | ltto/framework | /framework-core/src/main/java/com/tov2/framework/core/context/bean/AbstractBeanScanner.java | UTF-8 | 1,530 | 2.609375 | 3 | [] | no_license | package com.tov2.framework.core.context.bean;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public abstract class AbstractBeanScanner implements BeanScanner {
public String packageDir(String packagePath) {
return packagePath.replace('.', '/');
}
public Set<Class> scanJarFile(String jarPath) {
JarFile jarFile = null;
Set<Class> set = new TreeSet<>();
try {
jarFile = new JarFile(new File(jarPath));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String classPath = jarEntry.getName();
if (!jarEntry.isDirectory() && classPath.endsWith(".class")) {
String classPackage = classPath.substring(0, classPath.length() - 6).replaceAll("/", ".");
set.add(Class.forName(classPackage));
}
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return set;
}
public Set<Class<?>> scan(String packagePath) {
Reflections reflections = new Reflections(packagePath, new SubTypesScanner(false));
return reflections.getSubTypesOf(Object.class);
}
}
| true |
2b92c10dcae8a0bbc4c9a9ffc9727a62e7e8aee1 | Java | UNAH-IS/IS201-I2020 | /UnidadII/EjemploHerencia/src/clases/Alumno.java | UTF-8 | 1,667 | 3.015625 | 3 | [] | no_license | package clases;
import java.util.Arrays;
public class Alumno extends Persona{
private String cuenta;
private double promedio;
public Alumno(
String identidad,
String nombre,
String apellido,
int edad,
String fechaNacimiento,
Carrera carrera,
String[] clases,
String centroRegional,
String genero,
String cuenta,
double promedio
) {
super(identidad, nombre, apellido, edad, fechaNacimiento, carrera, clases, centroRegional, genero);
this.cuenta = cuenta;
this.promedio = promedio;
}
public String getCuenta() {
return cuenta;
}
public void setCuenta(String cuenta) {
this.cuenta = cuenta;
}
public double getPromedio() {
return promedio;
}
public void setPromedio(double promedio) {
this.promedio = promedio;
}
public void mostrarNombre() {
System.out.println(nombre + " " + apellido);
}
@Override
public String toString() {
return "Alumno [cuenta=" + cuenta + ", promedio=" + promedio + ", identidad=" + identidad + ", nombre=" + nombre
+ ", apellido=" + apellido + ", edad=" + edad + ", fechaNacimiento=" + fechaNacimiento + ", carrera="
+ carrera + ", clases=" + Arrays.toString(clases) + ", centroRegional=" + centroRegional + ", genero="
+ genero + "]";
}
@Override
public void aprobar() {
super.aprobar();
System.out.println("Aprobando al alumno " + nombre + " " + apellido + "("+ cuenta +")");
}
public void cancelarClase() {}
public void cambiarCarrera() {}
@Override
public void reprobar() {//Sobreescritura obligatoria porque son abstractos
}
@Override
public void matricular() {//Sobreescritura obligatoria porque son abstractos
}
}
| true |
4cf1c539ae473456ba51a47cab6540f4e30443ef | Java | chiangho/haoframe | /hao-base/src/main/java/hao/framework/db/page/PaginationInterceptor.java | UTF-8 | 4,909 | 1.875 | 2 | [] | no_license | package hao.framework.db.page;
import java.sql.Connection;
import java.util.Properties;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import hao.framework.db.page.dialect.Dialect;
import hao.framework.db.page.dialect.MySqlDialect;
import hao.framework.utils.ClassUtils;
/***
* 分页连接器
*
* @author chianghao
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class }), })
public class PaginationInterceptor implements Interceptor {
Logger log = LogManager.getLogger(this.getClass());//Logger.getLogger(this.getClass());
protected Dialect dialect;// 对应的插件
@Override
public Object intercept(Invocation invocation) throws Throwable {
Executor exe = (Executor) invocation.getTarget();
Object[] args = invocation.getArgs();
Object parameter = args[1];
MappedStatement ms = (MappedStatement) args[0];
BoundSql boundSql;
Connection connection = exe.getTransaction().getConnection();
if (log.isDebugEnabled()) {
log.info("数据源驱动为:" + connection.getMetaData().getDriverName().toUpperCase());
}
if (connection.getMetaData().getDriverName().toUpperCase().indexOf("MYSQL") != -1) {
dialect = new MySqlDialect();
}
if (dialect != null) {
String id = ms.getId();
Page page = PageHelper.getPage(id);
if (page != null) {
if(log.isDebugEnabled()) {
log.info("--------------执行分页查询-------------");
}
if (args.length == 4) {
// 4 个参数时
boundSql = ms.getBoundSql(parameter);
// cacheKey = exe.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
// 6 个参数时
// cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
String originalSql = boundSql.getSql().trim();
if (originalSql.endsWith(";")) {
originalSql = originalSql.substring(0, originalSql.lastIndexOf(";"));
}
String countSql = dialect.getCountString(originalSql);
page.setRowNum(SQLHelper.getCount(countSql, connection, ms, boundSql.getParameterObject(), boundSql, log));
String pageSql = dialect.getLimitString(originalSql, page.getOffset(), page.getLimit());
if(log.isDebugEnabled()) {
log.info("==>被执行的sql语句为"+pageSql);
}
invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT);
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(),
boundSql.getParameterObject());
if (ClassUtils.getFieldValue(boundSql, "metaParameters") != null) {
MetaObject mo = (MetaObject) ClassUtils.getFieldValue(boundSql, "metaParameters");
ClassUtils.setFieldValue(newBoundSql, "metaParameters", mo);
}
MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
invocation.getArgs()[0] = newMs;
PageHelper.removePage(id);
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null) {
for (String keyProperty : ms.getKeyProperties()) {
builder.keyProperty(keyProperty);
}
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.cache(ms.getCache());
return builder.build();
}
public class BoundSqlSqlSource implements SqlSource {
BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
| true |
0f22c4cff64390490f2451d117d4202c010212a6 | Java | smanasawala52/hnak | /src/main/java/com/hnak/elastic/rest/controller/InsertTempDataController.java | UTF-8 | 38,903 | 1.96875 | 2 | [] | no_license | package com.hnak.elastic.rest.controller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.validator.GenericValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.hnak.elastic.rest.dao.AttributesDao;
import com.hnak.elastic.rest.dao.CategoryDao;
import com.hnak.elastic.rest.dao.ProductDao;
import com.hnak.emis.modal.AttributesModal;
import com.hnak.emis.modal.CategoryModal;
import com.hnak.emis.modal.FiltersModal;
import com.hnak.emis.modal.Locale;
import com.hnak.emis.modal.Product;
import com.hnak.emis.modal.ProductXref;
@RestController
public class InsertTempDataController {
@Autowired
private AttributesDao attributesDao;
@Autowired
private CategoryDao categoryDao;
@Autowired
private ProductDao productDao;
@GetMapping("/insertTemp")
public void insertTemp() {
insertTempCategory();
insertTempAttributes();
insertTempFilters();
insertTempProducts();
insertTempProductsRelations();
}
@GetMapping("/insertTempAttributes")
public void insertTempAttributes() {
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(1);
attributesModel.setLegacyId("1");
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCategory_id(1);
attributesModel.setCode("availability");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Availability");
attrDesc.put(Locale.ar_SA, "Availability-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(2);
attributesModel.setLegacyId("2");
attributesModel.setCategory_id(5);
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCode("specialprice");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Special Price");
attrDesc.put(Locale.ar_SA, "Special Price-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(3);
attributesModel.setLegacyId("3");
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCategory_id(1);
attributesModel.setCode("attr_brand");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Brand");
attrDesc.put(Locale.ar_SA, "Brand-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(4);
attributesModel.setLegacyId("4");
attributesModel.setCategory_id(1);
attributesModel.setActive(true);
attributesModel.setAttr_group("More Info");
attributesModel.setCode("attr_length");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Length");
attrDesc.put(Locale.ar_SA, "Legth-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(5);
attributesModel.setLegacyId("5");
attributesModel.setCategory_id(2);
attributesModel.setActive(true);
attributesModel.setAttr_group("More Info");
attributesModel.setCode("attr_depth");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Depth");
attrDesc.put(Locale.ar_SA, "Depth-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(6);
attributesModel.setLegacyId("6");
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCategory_id(3);
attributesModel.setCode("attr_style");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Style");
attrDesc.put(Locale.ar_SA, "Style-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(7);
attributesModel.setLegacyId("7");
attributesModel.setCategory_id(10);
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCode("attr_colorfinish");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Color FInish");
attrDesc.put(Locale.ar_SA, "Color FInish-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(8);
attributesModel.setLegacyId("8");
attributesModel.setActive(true);
attributesModel.setAttr_group("Basic Classification");
attributesModel.setCategory_id(12);
attributesModel.setCode("attr_seatheightinches");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Seat Height Inches");
attrDesc.put(Locale.ar_SA, "Seat Height Inches-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(9);
attributesModel.setLegacyId("9");
attributesModel.setCategory_id(2);
attributesModel.setActive(true);
attributesModel.setAttr_group("More Info");
attributesModel.setCode("attr_type");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Type");
attrDesc.put(Locale.ar_SA, "Type-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
AttributesModal attributesModel = new AttributesModal();
attributesModel.setId(10);
attributesModel.setLegacyId("10");
attributesModel.setCategory_id(5);
attributesModel.setActive(true);
attributesModel.setAttr_group("More Info");
attributesModel.setCode("attr_stackable");
attributesModel.setConfigurable(false);
attributesModel.setCreateable(true);
attributesModel.setCreatedAt(new Date());
attributesModel.setDatatype("String");
attributesModel.setEditable(true);
attributesModel.setFilterable(false);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "Stackable");
attrDesc.put(Locale.ar_SA, "Stackable-Arabic");
attributesModel.setName(attrDesc);
attributesDao.insertAttributes(attributesModel);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/insertTempFilters")
public void insertTempFilters() {
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(1);
filtersModel.setId(1);
filtersModel.setLegacyId("1");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Ships same day");
desc.put(Locale.ar_SA, "Ships same day-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(2);
filtersModel.setId(2);
filtersModel.setLegacyId("2");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Clearance");
desc.put(Locale.ar_SA, "Clearance-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(3);
filtersModel.setId(3);
filtersModel.setLegacyId("3");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Global Industrial");
desc.put(Locale.ar_SA, "Global Industrial-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(4);
filtersModel.setId(4);
filtersModel.setLegacyId("4");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "FLength 10inches");
desc.put(Locale.ar_SA, "FLength 10inches-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(3);
filtersModel.setId(5);
filtersModel.setLegacyId("5");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Vestil");
desc.put(Locale.ar_SA, "Vestil-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(4);
filtersModel.setId(6);
filtersModel.setLegacyId("6");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "FLength 20inches");
desc.put(Locale.ar_SA, "FLength 20inches-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(5);
filtersModel.setId(7);
filtersModel.setLegacyId("7");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Depth inches 15 inches");
desc.put(Locale.ar_SA, "Depth inches 15 inches-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(5);
filtersModel.setId(8);
filtersModel.setLegacyId("8");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Depth inches 25 inches");
desc.put(Locale.ar_SA, "Depth inches 25 inches-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(6);
filtersModel.setId(9);
filtersModel.setLegacyId("9");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Children's Chair");
desc.put(Locale.ar_SA, "Children's Chair-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(6);
filtersModel.setId(10);
filtersModel.setLegacyId("10");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Adult's Chair");
desc.put(Locale.ar_SA, "Adult's Chair-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(7);
filtersModel.setId(11);
filtersModel.setLegacyId("11");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Red");
desc.put(Locale.ar_SA, "Red-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(7);
filtersModel.setId(12);
filtersModel.setLegacyId("12");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Green");
desc.put(Locale.ar_SA, "Green-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(7);
filtersModel.setId(13);
filtersModel.setLegacyId("13");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Blue");
desc.put(Locale.ar_SA, "Blue-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(8);
filtersModel.setId(14);
filtersModel.setLegacyId("14");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "50");
desc.put(Locale.ar_SA, "50-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(8);
filtersModel.setId(15);
filtersModel.setLegacyId("15");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "100");
desc.put(Locale.ar_SA, "100-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(9);
filtersModel.setId(16);
filtersModel.setLegacyId("16");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Classroom Seating");
desc.put(Locale.ar_SA, "Classroom Seating-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(9);
filtersModel.setId(17);
filtersModel.setLegacyId("17");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Office Seating");
desc.put(Locale.ar_SA, "Office Seating-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(10);
filtersModel.setId(18);
filtersModel.setLegacyId("18");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "Yes");
desc.put(Locale.ar_SA, "Yes-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
try {
FiltersModal filtersModel = new FiltersModal();
filtersModel.setActive(true);
filtersModel.setAttributeId(10);
filtersModel.setId(19);
filtersModel.setLegacyId("19");
Map<Locale, String> desc = new HashMap<>();
desc.put(Locale.en_SA, "No");
desc.put(Locale.ar_SA, "No-Arabic");
filtersModel.setDesc(desc);
attributesDao.insertFilters(filtersModel);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/updateTempCategory")
public CategoryModal updateTempCategory() {
try {
// System.out.println("7");
// insert 1A1A1A
CategoryModal category = new CategoryModal();
category.setId(7);
// //category.setCatCode("1A1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Accessory");
catDesc.put(Locale.ar_SA, "Mobile Accessory-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);
// children and parents data should be calculated and set by the
// program
category.setParentId(5);
categoryDao.updateCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
return categoryDao.getCategoryRaw(7);
}
@GetMapping("/updateTempCategory2")
public CategoryModal updateTempCategory2() {
try {
// System.out.println("7");
// insert 1A1A1A
CategoryModal category = new CategoryModal();
category.setId(7);
// category.setCatCode("1A1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Update Mobile Accessory");
catDesc.put(Locale.ar_SA, "Update Mobile Accessory-Arabic");
category.setName(catDesc);
// List<Integer> attributes = new
// ArrayList<Integer>();attributes.add(1);category.setAttributes(attributes);//category.setAttributeKeys("weight");
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);
// children and parents data should be calculated and set by the
// program
category.setParentId(5);
categoryDao.updateCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
return categoryDao.getCategoryRaw(7);
}
@GetMapping("/insertTempCategory")
public String insertTempCategory() {
try {
// insert 1A
CategoryModal category = new CategoryModal();
category.setId(1);
// category.setCatCode("1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Electronics");
catDesc.put(Locale.ar_SA, "Electronics-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// List<Integer> attributes = new
// ArrayList<Integer>();attributes.add(1);category.setAttributes(attributes);//category.setAttributeKeys("brand,color");
// children data should be calculated by the program and updated
category.setParentId(0);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1B
CategoryModal category = new CategoryModal();
category.setId(2);
// category.setCatCode("1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Cothings");
catDesc.put(Locale.ar_SA, "Cothings-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("brand,size");
// children data should be calculated by the program and updated
category.setParentId(0);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A
CategoryModal category = new CategoryModal();
category.setId(3);
// category.setCatCode("1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile");
catDesc.put(Locale.ar_SA, "Mobile-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("data_size");
// children and parents data should be calculated and set by the
// program
category.setParentId(1);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1B
CategoryModal category = new CategoryModal();
category.setId(4);
// category.setCatCode("1A1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Tablet");
catDesc.put(Locale.ar_SA, "Tablet-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("data_size");
// children and parents data should be calculated and set by the
// program
category.setParentId(1);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1B1A
CategoryModal category = new CategoryModal();
category.setId(5);
// category.setCatCode("1B1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Men's Wear");
catDesc.put(Locale.ar_SA, "Men's Wear-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("length");
// children and parents data should be calculated and set by the
// program
category.setParentId(2);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1B1B
CategoryModal category = new CategoryModal();
category.setId(6);
// category.setCatCode("1B1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Women's Wear");
catDesc.put(Locale.ar_SA, "Women's Wear-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("waist_length");
// children and parents data should be calculated and set by the
// program
category.setParentId(2);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A1A
CategoryModal category = new CategoryModal();
category.setId(7);
// category.setCatCode("1A1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Accessory");
catDesc.put(Locale.ar_SA, "Mobile Accessory-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("weight");
// children and parents data should be calculated and set by the
// program
category.setParentId(3);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A1B
CategoryModal category = new CategoryModal();
category.setId(8);
// category.setCatCode("1A1A1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Charger");
catDesc.put(Locale.ar_SA, "Mobile Charger-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("wire-length");
// children and parents data should be calculated and set by the
// program
category.setParentId(3);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1B1A
CategoryModal category = new CategoryModal();
category.setId(9);
// category.setCatCode("1A1B1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Tablet Accessory");
catDesc.put(Locale.ar_SA, "Tablet Accessory-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("weight");
// children and parents data should be calculated and set by the
// program
category.setParentId(4);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1B1B
CategoryModal category = new CategoryModal();
category.setId(10);
// category.setCatCode("1A1B1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Tablet Charger");
catDesc.put(Locale.ar_SA, "Tablet Charger-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("dimension");
// children and parents data should be calculated and set by the
// program
category.setParentId(4);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1B1A1A
CategoryModal category = new CategoryModal();
category.setId(11);
// category.setCatCode("1B1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mens Jacket");
catDesc.put(Locale.ar_SA, "Mens Jacket-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("belt-length");
// children and parents data should be calculated and set by the
// program
category.setParentId(5);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1B1A1B
CategoryModal category = new CategoryModal();
category.setId(11);
// category.setCatCode("1B1A1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mens Jeans");
catDesc.put(Locale.ar_SA, "Mens Jeans-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("belt-length");
// children and parents data should be calculated and set by the
// program
category.setParentId(5);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A1A1A
CategoryModal category = new CategoryModal();
category.setId(12);
// category.setCatCode("1A1A1A1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Accessory - Battery");
catDesc.put(Locale.ar_SA, "Mobile Accessory - Battery-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("mHAMP");
// children and parents data should be calculated and set by the
// program
category.setParentId(7);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A1A1B
CategoryModal category = new CategoryModal();
category.setId(13);
// category.setCatCode("1A1A1A1B");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Accessory - Screen");
catDesc.put(Locale.ar_SA, "Mobile Accessory - Screen-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("Screen-Color");
// children and parents data should be calculated and set by the
// program
category.setParentId(7);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A1A1A1C
CategoryModal category = new CategoryModal();
category.setId(14);
// category.setCatCode("1A1A1A1C");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Mobile Accessory - Headphones");
catDesc.put(Locale.ar_SA, "Mobile Accessory - Headphones-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("ear
// plugs");
// children and parents data should be calculated and set by the
// program
category.setParentId(7);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A
CategoryModal category = new CategoryModal();
category.setId(15);
// category.setCatCode("1A1C");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Pendrive");
catDesc.put(Locale.ar_SA, "Pendrive-Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("brand,color");
// children data should be calculated by the program and updated
category.setParentId(1);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
try {
// insert 1A
CategoryModal category = new CategoryModal();
category.setId(16);
// category.setCatCode("1A1C1A");
Map<Locale, String> catDesc = new HashMap<>();
catDesc.put(Locale.en_SA, "Pendrive - Snadik");
catDesc.put(Locale.ar_SA, "Pendrive Snadik -Arabic");
category.setName(catDesc);
List<Integer> attributes = new ArrayList<Integer>();
attributes.add(1);
category.setAttributes(attributes);// category.setAttributeKeys("size");
// children data should be calculated by the program and updated
category.setParentId(15);
categoryDao.insertCategory(category);
//
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
@GetMapping("/insertTempProducts")
@ResponseBody
public void insertTempProducts() {
try {
Product product = new Product();
product.setId(1);
product.setName("Test Product 1");
productDao.insertProduct(product);
} catch (Exception e) {
e.printStackTrace();
}
try {
Product product = new Product();
product.setId(2);
product.setName("Test Product 2");
productDao.insertProduct(product);
} catch (Exception e) {
e.printStackTrace();
}
try {
Product product = new Product();
product.setId(3);
product.setName("Test Product 3");
productDao.insertProduct(product);
} catch (Exception e) {
e.printStackTrace();
}
try {
Product product = new Product();
product.setId(4);
product.setName("Test Product 4");
productDao.insertProduct(product);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/insertTempProductsRelationsReflections")
@ResponseBody
public void insertTempProductsRelationsReflections() {
try {
String inputFile = "D:\\Test\\hnak\\prod-relations.txt";
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String line = br.readLine();
while (line != null) {
try {
if (!GenericValidator.isBlankOrNull(line)) {
System.out.println(line);
String[] list = line.split(":");
String id = list[0];
String filterId = list[1];
List<ProductXref> productXrefs = productDao.getProductXrefsRawByProduct(Integer.parseInt(id),
Integer.parseInt(filterId));
if (!CollectionUtils.isEmpty(productXrefs)) {
ProductXref productXref = productXrefs.get(0);
Map<Locale, String> attrDesc = new HashMap<>();
String name = list[2];
String nameAr = list[3];
attrDesc.put(Locale.en_SA, name);
attrDesc.put(Locale.ar_SA, nameAr);
productXref.setName(attrDesc);
productDao.insertProductXref(productXref);
}
}
} catch (Exception e) {
}
line = br.readLine();
}
} catch (
Exception e) {
e.printStackTrace();
}
}
@GetMapping("/insertTempProductsRelations")
@ResponseBody
public void insertTempProductsRelations() {
try {
ProductXref productXref = new ProductXref();
productXref.setId(1);
productXref.setProdId(1);
productXref.setCatId(12);
productXref.setAttrId(1);
productXref.setFilterId(1);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(2);
productXref.setProdId(1);
productXref.setCatId(12);
productXref.setAttrId(3);
productXref.setFilterId(3);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(3);
productXref.setProdId(1);
productXref.setCatId(12);
productXref.setAttrId(4);
productXref.setFilterId(4);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(4);
productXref.setProdId(2);
productXref.setCatId(12);
productXref.setAttrId(1);
productXref.setFilterId(1);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(5);
productXref.setProdId(2);
productXref.setCatId(12);
productXref.setAttrId(3);
productXref.setFilterId(5);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(6);
productXref.setProdId(3);
productXref.setCatId(5);
productXref.setAttrId(4);
productXref.setFilterId(4);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(7);
productXref.setProdId(3);
productXref.setCatId(5);
productXref.setAttrId(5);
productXref.setFilterId(7);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(8);
productXref.setProdId(3);
productXref.setCatId(5);
productXref.setAttrId(10);
productXref.setFilterId(18);
Map<Locale, String> attrDesc = new HashMap<>();
attrDesc.put(Locale.en_SA, "CLR");
attrDesc.put(Locale.ar_SA, "CLR-Arabic");
productXref.setName(attrDesc);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(10);
productXref.setProdId(4);
productXref.setCatId(5);
productXref.setAttrId(5);
productXref.setFilterId(8);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
try {
ProductXref productXref = new ProductXref();
productXref.setId(11);
productXref.setProdId(4);
productXref.setCatId(5);
productXref.setAttrId(10);
productXref.setFilterId(19);
productDao.insertProductXref(productXref);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/insertTempProductsRelationsReflectionsRaw")
@ResponseBody
public void insertTempProductsRelationsReflectionsRaw() {
try {
String inputFile = "D:\\Test\\hnak\\prod-relations-index.txt";
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String line = br.readLine();
while (line != null) {
try {
if (!GenericValidator.isBlankOrNull(line)) {
System.out.println(line);
String[] list = line.split(":");
String index = list[0];
String id = list[1];
Map<Locale, String> attrDesc = new HashMap<>();
String name = list[2];
String nameAr = list[3];
attrDesc.put(Locale.en_SA, name);
attrDesc.put(Locale.ar_SA, nameAr);
Map<String, Object> inputMap = new HashMap<>();
inputMap.put("name", attrDesc);
inputMap.put("index", index);
inputMap.put("id", id);
int status = productDao.updateSpecificFields(inputMap);
if (status == 1) {
System.out.println("Success! Row processed: " + line);
} else {
System.out.println("Error: " + line + " input:" + inputMap);
}
}
} catch (Exception e) {
}
line = br.readLine();
}
} catch (
Exception e) {
e.printStackTrace();
}
}
}
| true |
b8adcb2640d199f7d95cfba591f387d1fdd8a326 | Java | aa41/WawaFramework | /component_share/src/main/java/com/duiba/component_main/service_impl/ShareResServiceImpl.java | UTF-8 | 688 | 1.6875 | 2 | [] | no_license | package com.duiba.component_main.service_impl;
import android.content.Context;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.duiba.component_base.component.share.path.ShareRouterPath;
import com.duiba.component_base.component.share.rpc.IShareResService;
import com.duiba.component_share.R;
/**
* @author: jintai
* @time: 2017/11/6-19:02
* @Email: jintai@duiba.com.cn
* @desc:分享组件资源服务
*/
@Route(path = ShareRouterPath.SHARE_SERVER_RES)
public class ShareResServiceImpl implements IShareResService {
@Override
public int provideGirl() {
return R.mipmap.activity_39;
}
@Override
public void init(Context context) {
}
}
| true |
9a854bdcb1087cba9e52052c477b38e0c3cb536d | Java | ojinxy/roms_web | /src/fsl/ta/toms/roms/amvswebservice/VehFitness.java | UTF-8 | 3,582 | 2.015625 | 2 | [] | no_license | //
// Generated By:JAX-WS RI IBM 2.2.1-07/09/2014 01:53 PM(foreman)- (JAXB RI IBM 2.2.3-07/07/2014 12:56 PM(foreman)-)
//
package fsl.ta.toms.roms.amvswebservice;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for VehFitness complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="VehFitness">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fitnessNo" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="examDepot" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="issueDate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="expDate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VehFitness", propOrder = {
"fitnessNo",
"examDepot",
"issueDate",
"expDate"
})
public class VehFitness
implements Serializable
{
@XmlElement(required = true, nillable = true)
protected String fitnessNo;
@XmlElement(required = true, nillable = true)
protected String examDepot;
@XmlElement(required = true, nillable = true)
protected String issueDate;
@XmlElement(required = true, nillable = true)
protected String expDate;
/**
* Gets the value of the fitnessNo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFitnessNo() {
return fitnessNo;
}
/**
* Sets the value of the fitnessNo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFitnessNo(String value) {
this.fitnessNo = value;
}
/**
* Gets the value of the examDepot property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExamDepot() {
return examDepot;
}
/**
* Sets the value of the examDepot property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExamDepot(String value) {
this.examDepot = value;
}
/**
* Gets the value of the issueDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssueDate() {
return issueDate;
}
/**
* Sets the value of the issueDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssueDate(String value) {
this.issueDate = value;
}
/**
* Gets the value of the expDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExpDate() {
return expDate;
}
/**
* Sets the value of the expDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExpDate(String value) {
this.expDate = value;
}
}
| true |
9d10ce0aac7467f8ee7ff881c837dda74ca6e3f8 | Java | AraceliColmenero/Practica1 | /Instrumento1/src/com/utng/asocicaciones1/Pedido.java | WINDOWS-1250 | 611 | 2.078125 | 2 | [] | no_license | package com.utng.asocicaciones1;
import java.util.Date;
/**
* * @author Araceli Colmenero * Ultima revision: Febrero 2016
*
* * Declaracion de la Clase Pedido *
*
*/
import java.util.List;
public class Pedido {
// Atributos
private double pe_id;
private Date pe_fechaPedido;
private Date pe_fechaNecesidad;
private Date pe_fechaProgramada;
private Date pe_fechaEntrega;
private int pe_estado;
// Agregacin
private List<Articulo> contacts;
public Pedido(List<Articulo> contacts) {
this.contacts = contacts;
// TODO Auto-generated constructor stub
}
}// Fin de la clase
| true |
a89d52d16dec9dfd8996cc46bddc2f74d60a7d32 | Java | jguyet/ABCFile | /src/main/java/com/flagstone/transform/as3/abcfile/trait/Trait_class.java | UTF-8 | 1,858 | 2.265625 | 2 | [
"MIT"
] | permissive | package com.flagstone.transform.as3.abcfile.trait;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ResourceBundle;
import com.flagstone.transform.as3.abcfile.utils.ByteBufferFlash;
import com.flagstone.transform.as3.abcfile.utils.Internatiolizer;
public class Trait_class
implements ITraitKindData {
private int start = 0;
private int end = 0;
private int slot_id;
private int classi;
public void setSlot_id(int slot_id) {
this.slot_id = slot_id;
}
public void setClassi(int classi) {
this.classi = classi;
}
public Trait_class(ByteBufferFlash bbuf)
throws Exception {
trait_class(bbuf);
}
public void trait_class(ByteBufferFlash bbuf)
throws Exception {
this.start = bbuf.position();
this.slot_id = bbuf.unsigned30int();
this.classi = bbuf.unsigned30int();
this.end = (bbuf.position() - 1);
}
public int getSlot_id() {
return this.slot_id;
}
public int getClassi() {
return this.classi;
}
public String toString() {
String wynik = "";
wynik = wynik + "\n---#--- Trait_class \n" + Internatiolizer.msgs.getString("Position") + ": " + this.start + "\n";
wynik = wynik + "slot_id: " + this.slot_id + "\n";
wynik = wynik + "classi: " + this.classi + "\n";
wynik = wynik + Internatiolizer.msgs.getString("Position") + ": " + this.end + "\n---!!--- " + Internatiolizer.msgs.getString("end") + "\n";
return wynik;
}
public byte[] toByteCode() throws IOException {
ByteArrayOutputStream byteDate = new ByteArrayOutputStream();
byteDate.write(ByteBufferFlash.getUI32B(this.slot_id));
byteDate.write(ByteBufferFlash.getUI32B(this.classi));
return byteDate.toByteArray();
}
} | true |
6d119ac8cadc1df327fef3049e67016aeb5ac452 | Java | hollannikas/ssoidh | /src/main/java/fi/rudi/ssoidh/service/UserService.java | UTF-8 | 1,128 | 2.171875 | 2 | [
"MIT"
] | permissive | package fi.rudi.ssoidh.service;
import fi.rudi.ssoidh.domain.User;
import fi.rudi.ssoidh.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* Created by rudi on 11/04/16.
*/
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final Optional<User> user = userRepository.findOneByUsername(username);
final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();
user.ifPresent(detailsChecker::check);
return user.orElseThrow(() -> new UsernameNotFoundException("user not found."));
}
}
| true |
1bda00dafee91596d987317e02feb41bcf586c57 | Java | qunniao/qmfx_api | /core/src/main/java/com/zhancheng/core/vo/UserBandCardVO.java | UTF-8 | 2,080 | 1.867188 | 2 | [] | no_license | package com.zhancheng.core.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* 用户银行卡
* zc_user_address 实体类
*
* @author BianShuHeng
* @email 13525382973@163.com
* @date 2019-11-19 13:06:29
*/
@Data
public class UserBandCardVO{
@ApiModelProperty(name = "id", value = "id")
private Integer id;
@ApiModelProperty(name = "userId", value = "用户id")
private Integer userId;
@ApiModelProperty(name = "cardType", value = "卡类型,1支付宝,2银行卡,3微信号")
private String cardType;
@ApiModelProperty(name = "cardNumber", value = "卡号")
private String cardNumber;
@ApiModelProperty(name = "cardName", value = "卡名称,比如支付宝,中国邮政银行,中国建设银行。。。")
private String cardName;
@ApiModelProperty(name = "realName", value = "真实姓名")
private Integer realName;
@ApiModelProperty(name = "tixian", value = "是否可提现,1可提现,0不可提现")
private Integer tixian;
@ApiModelProperty(name = "bandCode", value = "银行代码")
private String bandCode;
@ApiModelProperty(name = "isDeleted", value = "是否删除 0:未删除; 1:删除 ")
@TableLogic
private Integer isDeleted;
@ApiModelProperty(name = "gmtCreate", value = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date gmtCreate;
@ApiModelProperty(name = "gmtModified", value = "修改时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date gmtModified;
}
| true |
e859f2a4a74523ea9c214ff5e7ac717d0a6b5a81 | Java | myflash163/springboot-demo | /src/main/java/com/example/bean/Person.java | UTF-8 | 1,268 | 2.609375 | 3 | [] | no_license | package com.example.bean;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Getter
@Setter
@ToString
@Component
//添加jsr303数据校验
@Validated
/*
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties不支持SpEL 表达式
* */
@ConfigurationProperties(prefix = "person")
public class Person {
@Value("${person.last-name}")
private String lastName;
/*
* @Value 优先级低于 @ConfigurationProperties
* @Value 不支持map list 复杂类型
* */
@Value("#{11*2}")
private Integer age;
private Boolean boss;
private Date birth;
/*
* 注解校验 仅添加@Validated后有效
* 对@ConfigurationProperties 有效 对@Value无效
* */
@Email
private String email;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
}
| true |
6d90f77707b211d0039177e428e1658c8ebaafa4 | Java | Native-Note/recyclerView-contact-list | /app/src/main/java/com/nativenote/recyclerview/MainActivity.java | UTF-8 | 4,753 | 2.078125 | 2 | [] | no_license | package com.nativenote.recyclerview;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by imtiaz on 3/2/17.
*/
public class MainActivity extends AppCompatActivity {
private List<Contact> contactList = new ArrayList<>();
private RecyclerView recyclerView;
private ContactAdapter mAdapter;
private TextView emptyView;
private static final int PERMISSION_REQUEST_CONTACT = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
emptyView = (TextView) findViewById(R.id.empty_view);
mAdapter = new ContactAdapter(MainActivity.this, contactList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// To show item divider, uncomment below line
// recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
checkPermission();
}
private void prepareData() {
contactList.clear();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new Contact(name, phoneNumber));
}
phones.close();
if (contactList.isEmpty()) {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CONTACT: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
prepareData();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Contacts access needed");
builder.setPositiveButton(android.R.string.ok, null);
builder.setMessage("please confirm Contacts access");
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onDismiss(DialogInterface dialog) {
checkPermission();
}
});
builder.show();
}
return;
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void checkPermission() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.READ_CONTACTS
},
PERMISSION_REQUEST_CONTACT);
} else {
prepareData();
}
}
}
| true |
41d6f71abc338bfaa89b2c3fe92e0c2b6938d20a | Java | liuziangexit/QMR | /QMRWorld/src/com/game/server/gmchat/loader/GMChatConfigXmlLoader.java | UTF-8 | 1,792 | 2.28125 | 2 | [] | no_license | package com.game.server.gmchat.loader;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.game.server.gmchat.config.GMChatConfig;
import com.game.server.http.config.HttpServerConfig;
import com.game.server.http.loader.HttpConfigXmlLoader;
/**
*
* @author 赵聪慧
* @2012-10-10 下午2:56:32
*/
public class GMChatConfigXmlLoader {
private Logger log = Logger.getLogger(HttpConfigXmlLoader.class);
// 初始化服务器配置信息
public GMChatConfig load(String file) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream in = new FileInputStream(file);
Document doc = builder.parse(in);
NodeList list = doc.getElementsByTagName("servers");
if (list.getLength() > 0) {
GMChatConfig config = new GMChatConfig();
Node node = list.item(0);
NodeList childs = node.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
if (("server").equals(childs.item(i).getNodeName())) {
NodeList schilds = childs.item(i).getChildNodes();
for (int j = 0; j < schilds.getLength(); j++) {
if (("server-port").equals(schilds.item(j).getNodeName())) {
config.setPort(Integer.parseInt(schilds.item(j).getTextContent()));
} else if (("server-allow").equals(schilds.item(j).getNodeName())) {
config.setIp(schilds.item(j).getTextContent());
}
}
}
}
in.close();
return config;
}
} catch (Exception e) {
log.error(e);
}
return null;
}
}
| true |
6509af875f33a3cae64556bbad841f56f0d8fd2e | Java | cynepCTAPuk/headFirstJava | /HerbertSchildt/src/chap11_Multithreading/SuspendResume.java | UTF-8 | 2,179 | 4.34375 | 4 | [] | no_license | package chap11_Multithreading;
// Suspending and resuming a thread the modern way
class NewThread5 implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread5(String name) {
this.name = name;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
}
// This is the entry point for the second thread
@Override
public void run() {
try {
for (int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized (this) {
while (suspendFlag) wait();
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted");
}
System.out.println(name + " exiting");
}
synchronized void mySuspend() {
suspendFlag = true;
}
synchronized void myResume() {
suspendFlag = false;
notify();
}
}
public class SuspendResume {
public static void main(String[] args) {
NewThread5 ob1 = new NewThread5("One");
NewThread5 ob2 = new NewThread5("Two");
ob1.t.start(); // Start the thread
ob2.t.start(); // Start the thread
try {
Thread.sleep(1_000);
ob1.mySuspend();
System.out.println("Suspending thread One");
ob1.myResume();
System.out.println("Resuming thread One");
ob2.mySuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1_000);
ob2.myResume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting");
}
}
| true |
01d9931f35b5342a4266b1192c69a69998733b83 | Java | Desperado2/team-job | /src/main/java/com/desperado/teamjob/service/GitLogAnalysisServiceImpl.java | UTF-8 | 9,895 | 2.109375 | 2 | [] | no_license | package com.desperado.teamjob.service;
import com.desperado.teamjob.dao.GitCommitLogDao;
import com.desperado.teamjob.dao.ProjectDao;
import com.desperado.teamjob.domain.GitCommitLogs;
import com.desperado.teamjob.domain.Project;
import com.desperado.teamjob.dto.GitCommitChart;
import com.desperado.teamjob.dto.GitCommitDto;
import com.desperado.teamjob.dto.GitCommitPieChart;
import com.desperado.teamjob.enums.RepositoryType;
import com.desperado.teamjob.thread.GitLogService;
import com.desperado.teamjob.thread.SvnLogService;
import com.desperado.teamjob.utils.DateUtil;
import com.desperado.teamjob.utils.UserUtils;
import com.desperado.teamjob.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service("gitLogAnalysisService")
public class GitLogAnalysisServiceImpl implements GitLogAnalysisService {
@Autowired
private GitLogService gitLogService;
@Autowired
private SvnLogService svnLogService;
@Autowired
private ProjectDao projectDao;
@Autowired
private GitCommitLogDao gitCommitLogDao;
@Override
public void saveOrUpdate() {
List<Project> projects = projectDao.selectAllProject();
for (Project project : projects){
String url = project.getRepositoryUrl();
String name = project.getProjectName();
String realName = project.getProjectRealName();
Date projectDateCreate = project.getProjectDateCreate();
GitCommitLogs newestLog = gitCommitLogDao.getProjectNewestLog(name);
//查询最近的提交记录,如果存在,最近的提交记录时间则为创建时间,避免重复查询
if(newestLog != null){
projectDateCreate = newestLog.getDateCommit();
}
//创建年
int createYear = DateUtil.getYear(projectDateCreate);
//本年
int year = DateUtil.getYear(new Date());
for (int begin = createYear; begin <= year; begin++){
//创建年,从创建周到当年最后一周
int weeks = DateUtil.getWeekOfYear(projectDateCreate);
int maxWeeks = DateUtil.getMaxWeekNumOfYear(createYear);
//如果不是本年也不是创建年,则从第一周到最后一周
if(begin > createYear && begin < year){
weeks = 1;
maxWeeks = DateUtil.getMaxWeekNumOfYear(begin);
}
// 如果创建时间为本年, 则从本年第一周到现在
if(begin == year){
weeks = 1;
maxWeeks = DateUtil.getWeekOfYear(new Date());
}
//如果创建时间为本年,则从创建时间到现在
if(createYear == year){
weeks = DateUtil.getWeekOfYear(projectDateCreate);
maxWeeks = DateUtil.getWeekOfYear(new Date());
}
for (int i=weeks; i <= maxWeeks; i++){
Date firstDayOfWeek = DateUtil.getFirstDayOfWeek(begin, i);
Date lastDayOfWeek = DateUtil.getLastDayOfWeek(begin, i);
int submitDateFrom = (int) (firstDayOfWeek.getTime()/1000);
int submitDateTo = (int) (lastDayOfWeek.getTime()/1000);
List<GitCommitLogs> gitCommitLogs = null;
if(project.getRepositoryType() == RepositoryType.GIT.getCode()){
gitCommitLogs = gitLogService.listAllLinesByTime(url, name, realName,submitDateFrom, submitDateTo);
}
if(project.getRepositoryType() == RepositoryType.SVN.getCode()){
gitCommitLogs = svnLogService.listAllLinesByTime(project,firstDayOfWeek, lastDayOfWeek);
}
if(gitCommitLogs != null && gitCommitLogs.size() > 0){
addLogs(gitCommitLogs);
}
}
}
}
}
@Override
public Result getWeeklyLogs(String yearweek) {
Result result = new Result();
List<GitCommitLogs> logsList = gitCommitLogDao.getWeeklyLogs(yearweek);
Map<String, List<GitCommitLogs>> logsUserMap = logsUserMap(logsList);
List<GitCommitDto> dealLogs = dealLogs(logsUserMap);
GitCommitChart commitChart = getGitCommitChart(dealLogs);
result.setData(commitChart);
return result;
}
@Override
public Result getProjectLogs(String project) {
Result result = new Result();
List<GitCommitLogs> logsList = gitCommitLogDao.getLogByProjectCode(project);
Map<String, List<GitCommitLogs>> logsUserMap = logsUserMap(logsList);
List<GitCommitDto> dealLogs = dealLogs(logsUserMap);
Map<String, List<GitCommitPieChart>> commitChart = getGitCommitPieChart(dealLogs);
result.setData(commitChart);
return result;
}
@Override
public Result lastWeekCommitLogs() {
String yearWeek = DateUtil.getYearWeek(new Date());
String username = UserUtils.getUser().getName();
List<GitCommitLogs> logs = gitCommitLogDao.getWeeklyLogsByAuthor(username, yearWeek);
StringBuilder sb = new StringBuilder();
for (GitCommitLogs log:logs){
sb.append(log.getCommitComment()).append("\n");
}
Result result = new Result();
result.setData(sb.toString());
return result;
}
private Map<String,List<GitCommitLogs>> logsUserMap(List<GitCommitLogs> logsList){
Map<String,List<GitCommitLogs>> map = new HashMap<>();
for (GitCommitLogs logs : logsList){
String author= logs.getAuthor();
if(map.containsKey(author)){
List<GitCommitLogs> gitCommitLogs = map.get(author);
gitCommitLogs.add(logs);
map.put(author,gitCommitLogs);
}else{
List<GitCommitLogs> gitCommitLogs =new ArrayList<>();
gitCommitLogs.add(logs);
map.put(author,gitCommitLogs);
}
}
return map;
}
private List<GitCommitDto> dealLogs(Map<String,List<GitCommitLogs>> maps){
List<GitCommitDto> gitCommitDtoList = new ArrayList<>();
GitCommitDto gitCommitDto;
for (String author : maps.keySet()){
gitCommitDto = new GitCommitDto();
List<GitCommitLogs> gitCommitLogs = maps.get(author);
int totalAddLines = 0;
int totalDelLines = 0;
int totalCommits = 0;
for (GitCommitLogs logs : gitCommitLogs){
totalAddLines += logs.getTotalAddLines();
totalDelLines += logs.getTotalDelLines();
totalCommits += 1;
}
gitCommitDto.setAuthorName(author);
gitCommitDto.setTotalAddLines(totalAddLines);
gitCommitDto.setTotalDelLines(totalDelLines);
gitCommitDto.setTotalCommits(totalCommits);
gitCommitDtoList.add(gitCommitDto);
}
return gitCommitDtoList;
}
private GitCommitChart getGitCommitChart(List<GitCommitDto> dealLogs){
GitCommitChart gitCommitChart = new GitCommitChart();
List<String> users = new ArrayList<>();
List<Integer> addLines = new ArrayList<>();
List<Integer> delLines = new ArrayList<>();
List<Integer> commits = new ArrayList<>();
for(GitCommitDto gitCommitDto : dealLogs){
users.add(gitCommitDto.getAuthorName());
addLines.add(gitCommitDto.getTotalAddLines());
delLines.add(gitCommitDto.getTotalDelLines());
commits.add(gitCommitDto.getTotalCommits());
}
gitCommitChart.setUsers(users);
gitCommitChart.setAddLines(addLines);
gitCommitChart.setDelLines(delLines);
gitCommitChart.setCommits(commits);
return gitCommitChart;
}
private Map<String,List<GitCommitPieChart>> getGitCommitPieChart(List<GitCommitDto> dealLogs){
List<GitCommitPieChart> addList = new ArrayList<>();
List<GitCommitPieChart> delList = new ArrayList<>();
List<GitCommitPieChart> commitList = new ArrayList<>();
GitCommitPieChart gitCommitPieChart = null;
for (GitCommitDto gitCommitDto : dealLogs){
gitCommitPieChart = new GitCommitPieChart();
gitCommitPieChart.setName(gitCommitDto.getAuthorName());
gitCommitPieChart.setValue(gitCommitDto.getTotalAddLines());
addList.add(gitCommitPieChart);
gitCommitPieChart = new GitCommitPieChart();
gitCommitPieChart.setName(gitCommitDto.getAuthorName());
gitCommitPieChart.setValue(gitCommitDto.getTotalDelLines());
delList.add(gitCommitPieChart);
gitCommitPieChart = new GitCommitPieChart();
gitCommitPieChart.setName(gitCommitDto.getAuthorName());
gitCommitPieChart.setValue(gitCommitDto.getTotalCommits());
commitList.add(gitCommitPieChart);
}
Map<String,List<GitCommitPieChart>> map = new HashMap<>();
map.put("add",addList);
map.put("del",delList);
map.put("commit",commitList);
return map;
}
private void addLogs(List<GitCommitLogs> gitCommitLogs){
List<GitCommitLogs> realLogs = new ArrayList<>();
for (GitCommitLogs logs : gitCommitLogs){
String commitId = logs.getCommitId();
GitCommitLogs commitLogs = gitCommitLogDao.getLogsByCommitId(commitId);
if(commitLogs == null){
realLogs.add(logs);
}
}
if(realLogs.size() > 0){
gitCommitLogDao.add(realLogs);
}
}
}
| true |
96f27f783b1842e1cc104ef2ae136824450083a3 | Java | Fatima1375/DOSSIER-JAVA | /geolocalisation(TP5)/src/main/Main.java | UTF-8 | 467 | 2.125 | 2 | [] | no_license | package main;
import sn.isi.entities.Rn;
import sn.isi.entities.Zone;
import sn.isi.traitement.IRn;
import sn.isi.traitement.IZone;
import sn.isi.traitement.RnImpl;
import sn.isi.traitement.ZoneImpl;
import java.util.List;
public class Main {
public static void main(String[] args){
IRn rn = new RnImpl();
//IZone zone = new ZoneImpl();
Rn r = rn.saisieRn();
rn.affichage(r);
// zone.affichage((Zone) zone);
}
}
| true |
e693ca28681b8bff6452ba6371b0c2bbd5003cdf | Java | viper44/JDBC_Practice | /db_practice/src/main/java/lesson3/Main.java | UTF-8 | 778 | 2.390625 | 2 | [] | no_license | package lesson3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// Animal animal = new Animal("momo", 10, true);
// Animal animal1 = new Animal("keke", 2, false);
// animal1.setId(2);
// animal.setId(3);
ClientDetails details = new ClientDetails("misha", 20, "0660660660");
// details.setId(2);
SessionFactory factory = new Configuration()
.configure()
.buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(details);
session.getTransaction().commit();
session.close();
}
}
| true |
7efa5d2855e6e3542e5cd3f15ef76b85a7858260 | Java | nao99/training | /orders/src/main/java/com/luxoft/orders/api/OrderItemDto.java | UTF-8 | 723 | 2.359375 | 2 | [] | no_license | package com.luxoft.orders.api;
import com.luxoft.orders.domain.model.OrderItem;
import java.math.BigDecimal;
/**
* OrderItemDto class
*
* @author Nikolai Osipov <nao99.dev@gmail.com>
* @version 1.0.0
* @since 2021-07-31
*/
public class OrderItemDto {
private final OrderItem item;
public OrderItemDto(OrderItem item) {
this.item = item;
}
public static OrderItemDto of(OrderItem item) {
return new OrderItemDto(item);
}
public Long getId() {
return item.getId();
}
public String getName() {
return item.getName();
}
public int getCount() {
return item.getCount();
}
public BigDecimal getPrice() {
return item.getPrice();
}
}
| true |
c2118fa2cb81608bfc2a41efcce3f1d9bd07a730 | Java | Pawelkrs90/UMCS_DB_SPRING_PROJEKT1 | /pmalek_project/src/main/java/com/project/pmalek_project/repository/model/BookOrder.java | UTF-8 | 1,755 | 2.46875 | 2 | [] | no_license | package com.project.pmalek_project.repository.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
//@Getter
//@Setter
//@NoArgsConstructor
//@AllArgsConstructor
@ToString
public class BookOrder {
private Long id;
private Long bookId;
private Long userId;
private LocalDate bookingDate;
private String type;
public interface Type{
public static final String RENT = "R";
public static final String BUY = "B";
public static final String DESTROY = "D";
}
public BookOrder() {
}
public BookOrder(Long id, Long bookId, Long userId, LocalDate bookingDate, String type) {
this.id = id;
this.bookId = bookId;
this.userId = userId;
this.bookingDate = bookingDate;
this.type = type;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public LocalDate getBookingDate() {
return bookingDate;
}
public void setBookingDate(LocalDate bookingDate) {
this.bookingDate = bookingDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| true |
a5d4a5223cbafe7f731ea63c111ecc3f08f5bb82 | Java | Rune-Status/sotr7-RS876 | /src/com/jagex/Interface57.java | UTF-8 | 255 | 1.570313 | 2 | [] | no_license | package com.jagex;
public interface Interface57 {
byte[] method372(int var1);
byte[] method373(int var1, byte var2);
byte[] method374(int var1);
byte[] method375(int var1);
byte[] method376(int var1);
byte[] method377(int var1);
}
| true |
d7bf82f7f6d84b26439dfcbf058f3bd89e9792b0 | Java | jgromeros/spatha | /src/main/java/co/qcsc/spatha/web/mb/converter/ProductSpecialtyConverter.java | UTF-8 | 258 | 1.609375 | 2 | [] | no_license | package co.qcsc.spatha.web.mb.converter;
import co.qcsc.spatha.domain.product.ProductSpecialty;
import org.springframework.roo.addon.jsf.converter.RooJsfConverter;
@RooJsfConverter(entity = ProductSpecialty.class)
public class ProductSpecialtyConverter {
}
| true |
98bde775236ad954002c94b7b301bfad2d54c98f | Java | zengyang2014/kafka-spike | /kafka-producer/src/main/java/SimpleProducer.java | UTF-8 | 1,814 | 2.78125 | 3 | [] | no_license | //import util.properties packages
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
//import simple producer packages
//import KafkaProducer packages
//import ProducerRecord packages
//Create java class named "SimpleProducer"
public class SimpleProducer {
private Properties props;
private Producer<String, String> producer;
private static Properties setProperty() {
Properties props = new Properties();
//Assign localhost id
props.put("bootstrap.servers", "localhost:9092");
//Set acknowledgements for producer requests.
props.put("acks", "all");
//If the request fails, the producer can automatically retry,
props.put("retries", 0);
//Specify buffer size in config
props.put("batch.size", 16384);
//Reduce the no of requests less than 0
props.put("linger.ms", 1);
//The buffer.memory controls the total amount of memory available to the producer for buffering.
props.put("buffer.memory", 33554432);
props.put("key.serializer", StringSerializer.class.getName());
props.put("value.serializer", StringSerializer.class.getName());
return props;
}
public SimpleProducer() {
this.props = setProperty();
this.producer = new KafkaProducer<String, String>(this.props);
}
public void produceMsg(String msg) {
this.producer.send(new ProducerRecord<String, String>("hello-kafka", msg));
System.out.println("Message sent successfully");
}
public void closeProducer() {
this.producer.close();
}
} | true |
7f1ba727bb902d72c1675fc09a6b135d07fb574e | Java | skokourov/faceId-library | /app/src/main/java/com/ipoint/faceid/lib/Token.java | UTF-8 | 3,107 | 2.3125 | 2 | [] | no_license | package com.ipoint.faceid.lib;
import android.util.Base64;
import com.android.volley.AuthFailureError;
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.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import static com.ipoint.faceid.lib.FaceId.DEFAULT_SERVER_URL;
/**
* Created by spe on 07.02.2017.
*/
public class Token {
private static final String TOKEN_URL = "o/token/";
public interface ReadyCallback {
void onReady();
void onError(String error);
}
private String accessToken;
private String user;
private String password;
private String clientId = "demo";
private String clientSecret = "demo";
private RequestQueue queue;
public Token(String user, String password, String clientId, String clientSecret, RequestQueue queue) {
this.user = user;
this.password = password;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.queue = queue;
}
public void refreshToken(final ReadyCallback readyCallback){
StringRequest request = new StringRequest
(Request.Method.POST, DEFAULT_SERVER_URL + TOKEN_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accessToken = jsonObject.getString("access_token");
} catch (JSONException e) {
readyCallback.onError(e.getMessage());
return;
}
readyCallback.onReady();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
readyCallback.onError(error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String s = clientId + ":" + clientSecret;
headers.put("Authorization", "Basic " + Base64.encodeToString(s.getBytes(), Base64.DEFAULT));
headers.putAll(super.getHeaders());
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("grant_type", "password");
params.put("username", user);
params.put("password", password);
return params;
}
};
queue.add(request);
}
public String getAccessToken() {
return accessToken;
}
}
| true |