blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f90d4b0a558e0ead97d767c5e7321f6c58b0b470 | b0843640efd58416ee4da0344964c572dc092bd1 | /gmail/src/main/java/com/livemymail/android/mailboxapp/utils/EndlessRecyclerViewScrollListener.java | 16cadac748813dbb8754e69112ed65f8f2ca0fcd | [] | no_license | sagarpatel288/EmailApp | e967bf3f2bbb1db93c673b74a2103ec30464b05b | 2354572d975abecadf3d3fac02fca5e1c65b4267 | refs/heads/master | 2020-06-27T12:31:18.678565 | 2019-08-25T18:40:52 | 2019-08-25T18:40:52 | 199,955,208 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,756 | java | package com.livemymail.android.mailboxapp.utils;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
RecyclerView.LayoutManager mLayoutManager;
public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
}
public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
} else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
int lastVisibleItemPosition = 0;
int totalItemCount = mLayoutManager.getItemCount();
if (mLayoutManager instanceof StaggeredGridLayoutManager) {
int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
} else if (mLayoutManager instanceof GridLayoutManager) {
lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
} else if (mLayoutManager instanceof LinearLayoutManager) {
lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
}
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
currentPage++;
onLoadMore(currentPage, totalItemCount, view);
loading = true;
}
}
// Call this method whenever performing new searches
public void resetState() {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = 0;
this.loading = true;
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
}
| [
"sagarpatel288@gmail.com"
] | sagarpatel288@gmail.com |
b7c157d9b9e0a029de4a32931723f19d26789f07 | 02ac6051bd3aa56f61b62cd67015a7317d731a13 | /src/view/LoginView.java | 8ae2c4d82e9ec9fbe228a4cb6b7c48af0f6bfab8 | [] | no_license | Ortega-Dan/Java-JSF-Starting-Project-Full-Base | 9a13428d36cda2f0a67430b5feba3bac3bb28ceb | 5cd985105716766921c13690823efa09761716f8 | refs/heads/master | 2023-03-31T06:35:05.209620 | 2021-05-11T21:16:37 | 2021-05-11T21:16:37 | 172,106,388 | 0 | 0 | null | 2023-03-27T22:17:00 | 2019-02-22T17:25:27 | Java | UTF-8 | Java | false | false | 3,445 | java | package view;
import java.io.Serializable;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.faces.event.ActionEvent;
import control.TimeControl;
import dtos.Llegada;
@ManagedBean
@SessionScoped
public class LoginView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String ipAddress = "";
private String user = "";
private boolean notie = false;
private List<Llegada> listaLlegadas = null;
private String notieText = "";
@PostConstruct
public void init() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
String ipAddressNumba = request.getHeader("X-FORWARDED-FOR");
if (ipAddressNumba == null) {
ipAddressNumba = request.getRemoteAddr();
}
System.out.println("ipAddress:" + ipAddressNumba);
ipAddress = ipAddressNumba;
if (ipAddress.equalsIgnoreCase("20.21.2.198")) {
this.user = "Juliana";
} else if (ipAddress.equalsIgnoreCase("20.21.2.199")) {
this.user = "Claudia";
} else if (ipAddress.equalsIgnoreCase("20.21.2.196")) {
this.user = "Mauber";
} else
this.user = "Otro";
getLlegada();
this.updateListaLlegadas();
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public boolean isNotie() {
return notie;
}
public String getNotieText() {
return notieText;
}
public void setNotieText(String notieText) {
this.notieText = notieText;
}
public void setNotie(boolean notie) {
this.notie = notie;
}
public String getLlegada() {
String llegaste = null;
String llegastetime = null;
try {
llegastetime = TimeControl.verifyIPofUserAndDate(ipAddress, LocalDate.now());
System.out.println("Refresh by" + ipAddress);
if (llegastetime == null) {
llegastetime = LocalTime.now().toString();
TimeControl.insertInfoForIPofUserAndDate(ipAddress, user, LocalDate.now(), llegastetime);
}
llegastetime = LocalTime.parse(llegastetime.replaceAll("0000", ""))
.format(DateTimeFormatter.ofPattern("hh:mm a"));
llegaste = ", hoy " + LocalDate.now().format(DateTimeFormatter.ofPattern("dd-MMM-yyyy"))
+ ", llegaste a las " + llegastetime;
return user + llegaste;
} catch (Exception e) {
e.printStackTrace();
}
return user + llegaste;
}
private void updateListaLlegadas() {
try {
listaLlegadas = new ArrayList<>();
TimeControl.getListOfLast7(user, listaLlegadas);
System.out.println("LIst of last 7");
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Llegada> getUltimos7() {
return listaLlegadas;
}
public String myButtonAction(ActionEvent actionEvent) {
this.notieText = this.notieText.replaceAll("\\s", " ").trim();
if (!this.notieText.isEmpty()) {
TimeControl.updateNote(this.ipAddress, this.user, this.notieText);
}
this.updateListaLlegadas();
return null;
}
public String toggleNotie(ActionEvent actionEvent) {
if (this.notie)
this.notie = false;
else
this.notie = true;
return null;
}
} | [
"ortega.dan2010@gmail.com"
] | ortega.dan2010@gmail.com |
7e4455d3fe848e9fc59993abbdb274a1e7b7d4ec | 441cf0f8354d9e74d706c32dce8744acf49af1bf | /source/desktop/src/server/WebServer.java | 74c430c6f2be2d7b34bb2f9512b7956e84511fd6 | [] | no_license | markrietveld/fuelmf | d9887ffa4eb3fcd4b6e27b360aad19d91f3fd60d | 8f61f53a52eb589e48efc380435c61ddd90d7c62 | refs/heads/master | 2016-09-05T13:25:04.186358 | 2015-04-21T13:30:49 | 2015-04-21T13:30:49 | 34,326,739 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,895 | java | /*
* Copyright 2009 Mark Rietveld
* This file is part of Fuel.
Fuel is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fuel is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Fuel. If not, see <http://www.gnu.org/licenses/>.
*/
package server;
import fuel.Main;
import fuel.lib.Database;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
/**
*
* @author Mark
*/
public class WebServer extends Server{
public static final int SERVER_PORT = 8002;
public WebServer(Database database, Main main){
super(database,main);
}
/**
* Accepts new connections and starts a new instance of WebReceiver
* for each client connection.
*/
public void run(){
try {
database.Query("update server set password = '"+password+"'", false);
} catch (SQLException ex) {ex.printStackTrace();}
isStarted=true;
try{
serverSocket = new ServerSocket(SERVER_PORT);
while(isStarted){
try{
Socket clientSocket = serverSocket.accept();
WebReceiver webReceiver = new WebReceiver(clientSocket, database,password,main);
Thread t = new Thread(webReceiver);
t.start();
}
catch(Exception e){}
}
} catch (IOException e){}
}
}
| [
"markrietveld@e8eac927-644c-3623-d253-ca0f1ed64916"
] | markrietveld@e8eac927-644c-3623-d253-ca0f1ed64916 |
9029933f9b12e9043b2db450653693a87e3021fe | cbed972ecd032534673af74615fc3d1a60089b1d | /src/java/services/MasseUtilisateur.java | c037f1d497a8e6b80d799144fe5d37ebebd9a7be | [] | no_license | haxakl/E-commerce-Musique | e46f49daf124f23b56470ccc8db937436d54dd99 | 6766c224ca899060f792f836e54c6271291912e7 | refs/heads/master | 2021-01-19T09:41:45.370567 | 2014-06-14T10:26:54 | 2014-06-14T10:26:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,691 | java | /*
* 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 services;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utilisateurs.gestionnaires.GestionnaireUtilisateurs;
/**
*
* @author Guillaume
*/
@WebServlet(name = "MasseUtilisateur", urlPatterns = {"/admin/utilisateurs/masse/*"})
public class MasseUtilisateur extends HttpServlet {
@EJB
private GestionnaireUtilisateurs gestionnaireUtilisateurs;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// gestionnaireUtilisateurs.creerUtilisateursDeTest();
response.sendRedirect("/tp2webmiage/admin/utilisateurs");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"golfieri.guillaume@gmail.com"
] | golfieri.guillaume@gmail.com |
291330b2f2cdea0dab0406f128cee5e9c5ff3cb6 | 8469d7386cc868ffff0a4aa1613dd909d73870f9 | /gulimall-member/src/main/java/com/atguigu/gulimall/member/entity/MemberLevelEntity.java | 33e263d05a71de6a049c4b63ae2601f323a10bac | [
"Apache-2.0"
] | permissive | IFADA/gulimall | 8bf760a7f81925a2b1aac629dc1f7baa1b595e08 | ffbde5bac9ac5df92b6cc6546b53f564344d5a6e | refs/heads/master | 2022-12-18T03:28:25.486560 | 2020-09-21T18:08:41 | 2020-09-21T18:08:41 | 289,300,757 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,167 | java | package com.atguigu.gulimall.member.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 会员等级
*
* @author 夏沫止水
* @email HeJieLin@gulimall.com
* @date 2020-05-22 19:42:06
*/
@Data
@TableName("ums_member_level")
public class MemberLevelEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 等级名称
*/
private String name;
/**
* 等级需要的成长值
*/
private Integer growthPoint;
/**
* 是否为默认等级[0->不是;1->是]
*/
private Integer defaultStatus;
/**
* 免运费标准
*/
private BigDecimal freeFreightPoint;
/**
* 每次评价获取的成长值
*/
private Integer commentGrowthPoint;
/**
* 是否有免邮特权
*/
private Integer priviledgeFreeFreight;
/**
* 是否有会员价格特权
*/
private Integer priviledgeMemberPrice;
/**
* 是否有生日特权
*/
private Integer priviledgeBirthday;
/**
* 备注
*/
private String note;
}
| [
"1656959427@qq.com"
] | 1656959427@qq.com |
e3284289f5699ada4f125f81340577d05d4368f2 | f75265fc427aad159834ef48e0a79d86b4e76647 | /src/main/java/org/ubaldino/taller/app/service/ProcessService.java | 1f0bd92c61b0189cd4e6fa043ead29dd23b62a33 | [] | no_license | ubaldino/taller_uno_uajms | a8b25ccd5887ba145f5b7f7091c393322bc2f380 | a1289f674344f8b63b2baf3fa4099ac4bcba8de7 | refs/heads/master | 2021-09-07T15:04:10.367810 | 2018-02-24T14:36:41 | 2018-02-24T14:36:41 | 103,790,309 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,292 | java | package org.ubaldino.taller.app.service;
import java.util.List;
import java.util.Map;
import org.javalite.activejdbc.Base;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.WebRequest;
import org.ubaldino.taller.app.model.Menu;
import org.ubaldino.taller.app.model.Process;
/**
*
* @author ubaldino
*/
@Service
public class ProcessService implements ServiceInterface<Process>{
@Override
public Process get(Long id) {
if(!Base.hasConnection()) Base.open();
Process proceso;
try {
proceso = Process.findById(id);
} catch (Exception e) {
proceso=null;
}
return proceso;
}
@Override
public List<Map<String, Object>> getAll() {
if(!Base.hasConnection()) Base.open();
try{
return Process.findAll().include(Menu.class).toMaps();
}catch( Exception e){
return null;
}
}
public List<Map<String, Object>> getAllSingle() {
if(!Base.hasConnection()) Base.open();
try{
return Process.findAll().orderBy("codp desc").toMaps();
}catch( Exception e){
return null;
}
}
@Override
public Long save(WebRequest request, Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Long create(WebRequest request) {
if(!Base.hasConnection()) Base.open();
try{
Base.openTransaction();
Process proceso=new Process();
proceso.setNombre(request.getParameter("nombre"));
proceso.setEnlace(request.getParameter("enlace"));
proceso.setEstado(1);
proceso.insert();
Base.commitTransaction();
return (Long) proceso.getId();
}catch( Exception e){
Base.rollbackTransaction();
System.out.println(e.getMessage());
System.out.println("¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿");
return Long.parseLong("0");
}
}
@Override
public boolean modify(WebRequest request, Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void disable(Long id) {
if(!Base.hasConnection()) Base.open();
try{
Base.openTransaction();
Process proceso=Process.findById(id);
proceso.setEstado(0);
proceso.saveIt();
Base.commitTransaction();
}catch( Exception e){
System.out.println( e.getMessage() );
Base.rollbackTransaction();
}
}
@Override
public void enable(Long id) {
if(!Base.hasConnection()) Base.open();
try{
Base.openTransaction();
Process proceso=Process.findById(id);
proceso.setEstado(1);
proceso.saveIt();
Base.commitTransaction();
}catch( Exception e){
System.out.println( e.getMessage() );
Base.rollbackTransaction();
}
}
}
| [
"ozzirisc@gmail.com"
] | ozzirisc@gmail.com |
d7bdd42944dca66ed8e1dc6265b0a166f85aae15 | 1b9eaa5353335966e321ea679e6447154c2eddf2 | /Problems/Time/src/Main.java | 8174bff0b166de5fd81d67e60cc1fb4b84dd92b9 | [] | no_license | halpeme/hyperskill-decrypt-encrypt | bc46d4f68186950b01713290f335eb7074c518ef | d9bbcbb4124b8b4a218030c2044ccb7607b5c8fb | refs/heads/master | 2022-12-29T21:46:32.996716 | 2020-10-15T08:26:03 | 2020-10-15T08:26:03 | 304,259,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | class Time {
int hours;
int minutes;
int seconds;
public Time(int hours){
this.hours =hours;
}
public Time(int hours, int minutes){
this.hours = hours;
this.minutes =minutes;
}
public Time(int hours, int minutes, int seconds){
this.hours = hours;
this.minutes =minutes;
this.seconds =seconds;
}
} | [
"david-wi@web.de"
] | david-wi@web.de |
cb4328fbda85d80745d39ff7d6d1443268c36ca9 | 5942680ffdfa07d6c94ddf76aaffcc7eddb87472 | /src/Week4/PracticalExercises/Factorials.java | a119f4ac8d791bfe262a3d6a24ba07c853af01ff | [] | no_license | LKWBrando/CP2406 | ecfec7c968fbbac873e9d07516430e1c9a7879cc | 20be805574b6f0a415233bd35125200ad32a7f6a | refs/heads/master | 2021-03-27T09:38:50.053170 | 2017-09-30T11:24:44 | 2017-09-30T11:24:44 | 97,794,317 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 279 | java | package Week4.PracticalExercises;
public class Factorials {
public static void main(String[] args) {
int culmValue;
culmValue = 1;
for (int i = 1; i<11; i++){
culmValue *= i ;
System.out.println(culmValue);
}
}
}
| [
"brandon.lum@my.jcu.edu.au"
] | brandon.lum@my.jcu.edu.au |
de8ddd2659344dea6406eb04ea1cc5cfd60e5d03 | 5f6acb928fbb8f57c2a053af0bd879411dc9428e | /gtfs-otp/src/main/java/org/opentripplanner/standalone/DateConstants.java | e2a10cb757a5be81d5f84fa71b507d7fc24896c4 | [
"MIT"
] | permissive | ESSimon/gtfs-java | 9bb860d5ad50ab338591ab8fd8c1720c629f5e53 | af77b9decce68bf6591f79fedaed2a0c7a25d24d | refs/heads/master | 2021-01-19T23:26:18.740456 | 2017-05-05T15:26:03 | 2017-05-05T15:26:03 | 88,984,244 | 0 | 0 | null | 2017-04-21T13:01:35 | 2017-04-21T13:01:35 | null | UTF-8 | Java | false | false | 4,819 | java | /* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.standalone;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;
/**
* String Constants - related to date
*
* @author Frank Purcell
* @version $Revision: 1.0 $
* @since 1.0
*/
public interface DateConstants {
public static final List<String> DF_LIST = Collections.unmodifiableList(Arrays.asList(new String[] {
"yyyy.MM.dd.HH.mm.ss", "yyyy.MM.dd.HH.mm",
"yyyy.MM.dd.HH.mm.ss.SS", "M.d.yy h.mm a", "M.d.yyyy h.mm a", "M.d.yyyy h.mma",
"M.d.yyyy h.mm", "M.d.yyyy k.mm", "M.d.yyyy", "yyyy.M.d", "h.mm a"
// NOTE: don't change the order of these strings...the simplest should be on the
// bottom...you risk parsing the wrong thing (and ending up with year 0012)
}));
public static final List<String> SMALL_DF_LIST = Collections.unmodifiableList(
Arrays.asList(new String[] { "M.d.yy", "yy.M.d", "h.mm a" }));
// from apache date utils
public static final String ISO_DATETIME_TIME_ZONE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZZ";
// milli second times
public static final Long ONE_WEEK_MILLI = 604800000L;
public static final Long ONE_DAY_MILLI = 86400000L;
public static final Long ONE_HOUR_MILLI = 3600000L;
public static final Long ONE_MINUTE_MILLI = 60000L;
public static final Long THIRTY_SECOND_MILLI = 30000L;
public static final Long ONE_SECOND_MILLI = 1000L;
public static final Long TEN_MINUTES_MILLI = ONE_MINUTE_MILLI * 10;
public static final Long THIRTY_MINUTES_MILLI = ONE_MINUTE_MILLI * 30;
public static final Long FORTY_5_MINUTES_MILLI = ONE_MINUTE_MILLI * 45;
public static final Long TWELVE_HOUR_MILLI = ONE_HOUR_MILLI * 12;
public static final Integer ONE_DAY_SECONDS = 24 * 60 * 60;
public static final Date NOW = new Date();
public static final Date NEXT_WEEK = new Date(NOW.getTime() + ONE_WEEK_MILLI);
public static final Date NEXT_MONTH = new Date(NOW.getTime() + (ONE_WEEK_MILLI * 4)
+ (ONE_DAY_MILLI * 2));
public static final String SIMPLE_TIME_FORMAT = "h:mm a";
public static final String TIME_FORMAT = "hh:mm:ss a";
public static final String DATE_FORMAT = "MM-dd-yyyy";
public static final String DATE_TIME_FORMAT = "M.d.yy_k.m";
public static final String DATE_TIME_FORMAT_NICE = "MM.dd.yyyy 'at' h:mm:a z";
public static final String PRETTY_DATE_FORMAT = "MMMM d, yyyy";
public static final String PRETTY_DT_FORMAT = PRETTY_DATE_FORMAT + " 'at' h:mm a z";
public final static String DT_FORMAT = "M.d.yyyy h:mm a";
public static final SimpleDateFormat dateSDF = new SimpleDateFormat(DATE_FORMAT);
public static final SimpleDateFormat timeSDF = new SimpleDateFormat(TIME_FORMAT);
public static final SimpleDateFormat simpTimeSDF = new SimpleDateFormat(SIMPLE_TIME_FORMAT);
public static final SimpleDateFormat dateTimeSDF = new SimpleDateFormat(DATE_TIME_FORMAT);
public static final SimpleDateFormat PRETTY_DATE = new SimpleDateFormat(PRETTY_DATE_FORMAT);
public static final SimpleDateFormat PRETTY_DT = new SimpleDateFormat(PRETTY_DT_FORMAT);
public static final SimpleDateFormat YEAR = new SimpleDateFormat("yyyy");
public static final SimpleDateFormat dowSDF = new SimpleDateFormat("E");
public static final SimpleDateFormat standardDateSDF = new SimpleDateFormat("M-d-yyyy");
public static final String DATE = "date";
public static final String EFFECTIVE_DATE = "effectiveDate";
public static final String TODAY = "today";
public static final String TIME = "time";
public static final String HOUR = "Hour";
public static final String MINUTE = "Minute";
public static final String AM_PM = "AmPm";
public static final String MONTH = "Month";
public static final String DAY = "Day";
public static final String WEEK = "week";
public static final String SAT = "sat";
public static final String SUN = "sun";
public static final String AM = "am";
public static final String PM = "pm";
}
| [
"guitrein@yahoo.com.br"
] | guitrein@yahoo.com.br |
d053d264684f2d85a34f78f0602e33d6abe8cdb0 | ad667f9892801d6b942cbc6a467044910ff1c6d8 | /cl-biz/src/main/java/com/cl/service/base/Domain.java | 130d03c54e1eaf85f1238a7ece693f20961a007b | [] | no_license | gspandy/CLH | 5f41000f5417f9ea48eb414dce1bd57088d1794b | abe0224a33e4f642d09efd82bd32683e53d165ec | refs/heads/master | 2023-08-09T16:24:21.341240 | 2017-07-25T04:04:55 | 2017-07-25T04:05:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 156 | java | package com.cl.service.base;
import java.io.Serializable;
public interface Domain extends Serializable {
public void examSelf() throws Exception;
}
| [
"543810522@qq.com"
] | 543810522@qq.com |
b9aa68616f8d9920e7aa1456d5532673cc280d5d | 205d0cf2ac00de52ac46ff1c6535b50a38eb474f | /FileRealtime/src/main/java/com/df/plugin/source/rt/file/config/FileConfig.java | 0a03191081ab62a5b40cc141b8df044a451703fb | [
"Apache-2.0"
] | permissive | aiical/DataFlow-Plugins | af10c895050369d44680b2f1ca5cdb0015bb36ac | ddab6431369dc03415499f30b97f761b1cb9c054 | refs/heads/main | 2023-04-24T09:10:30.093175 | 2021-05-13T10:57:34 | 2021-05-13T10:57:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,369 | java | package com.df.plugin.source.rt.file.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Properties;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.lixiang2114.flow.comps.Flow;
import com.github.lixiang2114.flow.util.CommonUtil;
import com.github.lixiang2114.flow.util.PropertiesReader;
/**
* @author Lixiang
* @description 文件配置
*/
@SuppressWarnings("unchecked")
public class FileConfig {
/**
* 流程对象
*/
public Flow flow;
/**
* 插件目录
*/
public File pluginPath;
/**
* 转存目录
*/
public File transferPath;
/**
* 缓冲日志文件
*/
public File loggerFile;
/**
* 实时文件已经读取的行数
*/
public int lineNumber;
/**
* 实时文件已经读取的字节数量
*/
public long byteNumber;
/**
* 数据扫描模式
*/
public ScanMode scanMode;
/**
* 缓冲日志文件被读完后自动删除
*/
public Boolean delOnReaded;
/**
* 日志(检查点)配置
*/
public Properties loggerConfig;
/**
* 英文逗号正则式
*/
private static final Pattern COMMA_REGEX=Pattern.compile(",");
/**
* 日志工具
*/
private static final Logger log=LoggerFactory.getLogger(FileConfig.class);
public FileConfig(){}
public FileConfig(Flow flow){
this.flow=flow;
transferPath=flow.sharePath;
this.pluginPath=flow.sourcePath;
}
/**
* @param config
*/
public FileConfig config() {
//读取日志文件配置
File configFile=new File(pluginPath,"source.properties");
loggerConfig=PropertiesReader.getProperties(configFile);
//数据扫描模式
String scanModeStr=loggerConfig.getProperty("scanMode","").trim();
scanMode=scanModeStr.isEmpty()?ScanMode.file:ScanMode.valueOf(scanModeStr);
if(ScanMode.channel==scanMode) return this;
//实时自动推送的日志文件
String loggerFileName=loggerConfig.getProperty("loggerFile","").trim();
if(loggerFileName.isEmpty()) {
loggerFile=new File(transferPath,"buffer.log.0");
log.warn("not found parameter: 'loggerFile',will be use default...");
}else{
File file=new File(loggerFileName);
if(file.exists() && file.isDirectory()) {
log.error("loggerFile can not be directory...");
throw new RuntimeException("loggerFile can not be directory...");
}
File filePath=file.getParentFile();
if(!filePath.exists()) filePath.mkdirs();
if(!file.exists()) {
log.warn("file: {} is not exists,it will be create...",file.getAbsolutePath());
try {
file.createNewFile();
} catch (IOException e) {
log.error("create logger file occur error:",e);
throw new RuntimeException(e);
}
}
String fileFullName=file.getAbsolutePath();
if(!fileFullName.contains(".")) file.renameTo(new File(fileFullName+".0"));
loggerFile=file;
}
log.info("realTime logger file is: "+loggerFile.getAbsolutePath());
//是否自动删除缓冲日志文件
String delOnReadedStr=loggerConfig.getProperty("delOnReaded","").trim();
this.delOnReaded=delOnReadedStr.isEmpty()?true:Boolean.parseBoolean(delOnReadedStr);
//实时自动推送的日志文件检查点
String lineNumberStr=loggerConfig.getProperty("lineNumber","").trim();
this.lineNumber=lineNumberStr.isEmpty()?0:Integer.parseInt(lineNumberStr);
String byteNumberStr=loggerConfig.getProperty("byteNumber","").trim();
this.byteNumber=byteNumberStr.isEmpty()?0:Integer.parseInt(byteNumberStr);
log.info("lineNumber is: "+lineNumber+",byteNumber is: "+byteNumber);
return this;
}
/**
* 刷新日志文件检查点
* @throws IOException
*/
public void refreshCheckPoint() throws IOException{
loggerConfig.setProperty("lineNumber",""+lineNumber);
loggerConfig.setProperty("byteNumber",""+byteNumber);
loggerConfig.setProperty("loggerFile", loggerFile.getAbsolutePath());
OutputStream fos=null;
try{
fos=new FileOutputStream(new File(pluginPath,"source.properties"));
log.info("reflesh checkpoint...");
loggerConfig.store(fos, "reflesh checkpoint");
}finally{
if(null!=fos) fos.close();
}
}
/**
* 获取字段值
* @param key 键
* @return 返回字段值
*/
public Object getFieldValue(String key) {
if(null==key) return null;
String attrName=key.trim();
if(attrName.isEmpty()) return null;
try {
Field field=FileConfig.class.getDeclaredField(attrName);
field.setAccessible(true);
Object fieldVal=field.get(this);
Class<?> fieldType=field.getType();
if(!fieldType.isArray()) return fieldVal;
int len=Array.getLength(fieldVal);
StringBuilder builder=new StringBuilder("[");
for(int i=0;i<len;builder.append(Array.get(fieldVal, i++)).append(","));
if(builder.length()>1) builder.deleteCharAt(builder.length()-1);
builder.append("]");
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 设置字段值
* @param key 键
* @param value 值
* @return 返回设置后的值
*/
public Object setFieldValue(String key,Object value) {
if(null==key || null==value) return null;
String attrName=key.trim();
if(attrName.isEmpty()) return null;
try {
Field field=FileConfig.class.getDeclaredField(attrName);
field.setAccessible(true);
Class<?> fieldType=field.getType();
Object fieldVal=null;
if(String[].class==fieldType){
fieldVal=COMMA_REGEX.split(value.toString());
}else if(File.class==fieldType){
fieldVal=new File(value.toString());
}else if(CommonUtil.isSimpleType(fieldType)){
fieldVal=CommonUtil.transferType(value, fieldType);
}else{
return null;
}
field.set(this, fieldVal);
return value;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 收集实时参数
* @return
*/
public String collectRealtimeParams() {
HashMap<String,Object> map=new HashMap<String,Object>();
map.put("loggerFile", loggerFile);
map.put("scanMode", scanMode);
map.put("pluginPath", pluginPath);
map.put("lineNumber", lineNumber);
map.put("byteNumber", byteNumber);
map.put("delOnReaded", delOnReaded);
return map.toString();
}
}
| [
"153082011@qq.com"
] | 153082011@qq.com |
31c6f1007368fe2c259366ccb4fcbf008a2b6c8d | c3417098618897f4ff5a5def474804dd186db284 | /makeBasic_Sprite/src/com/company/sprite/SplitImage.java | 73ea96e63274e962540f32df05aeb75056c74863 | [] | no_license | ood9842/enducation_code | 2ac073897cdf09f7d136d85c26fedd40a8316fda | e2686b1c6ad7816d5d20745bfa3fba7c98a3eaf0 | refs/heads/master | 2021-01-11T00:23:48.338516 | 2016-10-24T05:56:20 | 2016-10-24T05:56:20 | 70,557,496 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 443 | java | package com.company.sprite;
import java.awt.image.BufferedImage;
/**
* Created by Chetsada Chaiprasop on 10/22/2016.
*/
public class SplitImage {
public BufferedImage spriteSheet;
public SplitImage(BufferedImage ss)
{
spriteSheet = ss;
}
public BufferedImage cropImage(int x,int y,int width,int height)
{
BufferedImage temp = spriteSheet.getSubimage(x,y,width,height);
return temp;
}
}
| [
"ood9842@hotmail.com"
] | ood9842@hotmail.com |
9c0ec045e94e7b6977991d150476da0626969acf | 4b75bc0d8c00b9f22653d7895f866efd086147a2 | /yiibai/netty/src/main/java/com/yiibai/netty/time/TimeClientHandler.java | 4095342cb647505b8958780fbef23f60c7b363cd | [
"Apache-2.0"
] | permissive | King-Maverick007/websites | 90e40eeb13ba4086ee1d78e755d8a1e9fc3f7c85 | fd5ddf7f79ce12658e95e26cd58e3488c90749e2 | refs/heads/master | 2022-12-19T01:25:54.795195 | 2019-02-19T06:04:40 | 2019-02-19T06:04:40 | 300,188,105 | 0 | 0 | Apache-2.0 | 2020-10-01T07:33:49 | 2020-10-01T07:30:32 | null | UTF-8 | Java | false | false | 1,033 | java | package com.yiibai.netty.time;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg; // (1)
try {
long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
Date currentTime = new Date(currentTimeMillis);
System.out.println("Default Date Format:" + currentTime.toString());
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
// 转换一下成中国人的时间格式
System.out.println("Date Format:" + dateString);
ctx.close();
} finally {
m.release();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
} | [
"evangel_a@sina.com"
] | evangel_a@sina.com |
8ecd9a4bebd72d6f59cc0c7f6ea189ee6b172a6f | a011294a9ba00a65bc040efdb1853fbf4468a5a1 | /e3-order/e3-order-service/src/main/java/cn/e3mall/order/service/impl/OrderServiceImpl.java | e695a14736656a86d788ac6e2eee3a5ef1cfa933 | [] | no_license | Mathilda11/e3mall | c10f230fcc6a77f67140edb188d591604b7c9cfe | 7d402621e11bde926a6958014c58c3caf2dbc6fe | refs/heads/master | 2020-03-29T08:06:24.377979 | 2018-09-21T01:51:15 | 2018-09-21T01:51:15 | 149,694,500 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,596 | java | package cn.e3mall.order.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.mapper.TbOrderItemMapper;
import cn.e3mall.mapper.TbOrderMapper;
import cn.e3mall.mapper.TbOrderShippingMapper;
import cn.e3mall.order.pojo.OrderInfo;
import cn.e3mall.order.service.OrderService;
import cn.e3mall.pojo.TbOrderItem;
import cn.e3mall.pojo.TbOrderShipping;
/**
* 订单处理服务
* @author 54060
*
*/
@Service
public class OrderServiceImpl implements OrderService {
@Value("${ORDER_ID_GEN_KEY}")
private String ORDER_ID_GEN_KEY;
@Value("${ORDER_ID_START}")
private String ORDER_ID_START;
@Value("${ORDER_DETAIL_ID_GEN_KEY}")
private String ORDER_DETAIL_ID_GEN_KEY;
@Autowired
private TbOrderMapper orderMapper;
@Autowired
private TbOrderItemMapper orderItemMapper;
@Autowired
private TbOrderShippingMapper orderShippingMapper;
@Autowired
private JedisClient jedisClient;
public E3Result createOrder(OrderInfo orderInfo) {
//生成订单号 使用redis的inc生成
if(!jedisClient.exists(ORDER_ID_GEN_KEY)){
jedisClient.set(ORDER_ID_GEN_KEY, ORDER_ID_START);
}
String orderId = jedisClient.incr(ORDER_ID_GEN_KEY).toString();
//补全orderInfo属性
orderInfo.setOrderId(orderId);
//1、未付款,2、已付款,3、未发货,4、已发货,5、交易成功,6、交易关闭
orderInfo.setStatus(1);
orderInfo.setCreateTime(new Date());
orderInfo.setUpdateTime(new Date());
//插入订单表
orderMapper.insert(orderInfo);
//向订单明细表插入数据
List<TbOrderItem> orderItems = orderInfo.getOrderItems();
for (TbOrderItem tbOrderItem : orderItems) {
//生成明细id
String odId = jedisClient.incr(ORDER_DETAIL_ID_GEN_KEY).toString();
//补全pojo的属性
tbOrderItem.setId(odId);
tbOrderItem.setOrderId(orderId);
//向订单明细表插入数据
orderItemMapper.insert(tbOrderItem);
}
//向订单物流表插入数据
TbOrderShipping orderShipping = orderInfo.getOrderShipping();
orderShipping.setOrderId(orderId);
orderShipping.setCreated(new Date());
orderShipping.setUpdated(new Date());
//向物流表插入数据
orderShippingMapper.insert(orderShipping);
//返回E3Result 包含订单号
return E3Result.ok(orderId);
}
}
| [
"yizzhang11@163.com"
] | yizzhang11@163.com |
2ac65e896526a50cf9a10cafba0f6b6bfd0b5152 | 32d7729dc9ca8fa3fecacbfd6c141524b3addef1 | /src/main/java/org/javaswift/joss/command/shared/identity/authentication/KeystoneV3Identity.java | be8069e7bf0fbcf48381702ed616cd6e8a17d574 | [
"Apache-2.0"
] | permissive | melchisedek/joss | 02ca12a27384fb4f210876524e7f42838a78614b | fe25ff0921a5d6b11f217c36d6d05d469a8bedd9 | refs/heads/master | 2023-06-14T16:56:54.822241 | 2023-05-24T11:30:57 | 2023-05-24T11:30:57 | 206,502,856 | 0 | 0 | null | 2021-01-22T12:54:10 | 2019-09-05T07:32:32 | Java | UTF-8 | Java | false | false | 708 | java | package org.javaswift.joss.command.shared.identity.authentication;
import java.util.Collection;
import java.util.Collections;
public class KeystoneV3Identity {
private final Collection<String> methods;
private final KeystoneV3PasswordIdentity passwordIdentity;
public KeystoneV3Identity(String username, String password, String domain) {
this.passwordIdentity = new KeystoneV3PasswordIdentity(username, password, domain);
this.methods = Collections.singletonList(passwordIdentity.getMethodName());
}
public Collection<String> getMethods() {
return methods;
}
public KeystoneV3PasswordIdentity getPassword() {
return passwordIdentity;
}
}
| [
"kevin.conaway@walmart.com"
] | kevin.conaway@walmart.com |
ec65a006dc47d666b775ed43e483ec3781096c61 | d272d570cfe48a4cee827bf28177ee14025d50cd | /Lab07/lab07-prob1/src/main/java/edu/mum/waa/lab07/prob1/entities/Team.java | e5f812c3223f4cb37c6b7e56cd396ea4f7a02682 | [] | no_license | datdoandanh/waa_course | 02e65eefab067492ada83f286d9fea2f1a9211a5 | 28158561aae93d24cbcd7e6dfef4fa3b9a4e82d9 | refs/heads/master | 2021-01-24T11:20:17.665076 | 2018-03-14T02:10:14 | 2018-03-14T02:10:14 | 123,077,132 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,854 | java | package edu.mum.waa.lab07.prob1.entities;
import java.util.List;
public class Team {
private int teamKey;
private String name;
private String city;
private String mascot;
private List<Player> players;
private String homeUniform;
private String visitUniform;
private List<Match> matchesAsHome;
private List<Match> matchesAsVisitor;
public Team(String name, String city, String mascot, String homeUniform, String visitUniform) {
System.out.println("Custom Constructor");
this.name = name;
this.city = city;
this.mascot = mascot;
this.homeUniform = homeUniform;
this.visitUniform = visitUniform;
}
public int getTeamKey() {
return teamKey;
}
public void setTeamKey(int teamKey) {
this.teamKey = teamKey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getMascot() {
return mascot;
}
public void setMascot(String mascot) {
this.mascot = mascot;
}
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
public String getHomeUniform() {
return homeUniform;
}
public void setHomeUniform(String homeUniform) {
this.homeUniform = homeUniform;
}
public String getVisitUniform() {
return visitUniform;
}
public void setVisitUniform(String visitUniform) {
this.visitUniform = visitUniform;
}
public List<Match> getMatchesAsHome() {
return matchesAsHome;
}
public void setMatchesAsHome(List<Match> matchesAsHome) {
this.matchesAsHome = matchesAsHome;
}
public List<Match> getMatchesAsVisitor() {
return matchesAsVisitor;
}
public void setMatchesAsVisitor(List<Match> matchesAsVisitor) {
this.matchesAsVisitor = matchesAsVisitor;
}
}
| [
"doandanhdat852004@gmail.com"
] | doandanhdat852004@gmail.com |
653ad0169d5eefb2f608aed210ab80dca3aca218 | 10a8580aa44d33b7458429023c00de8c01ceda98 | /vendor/protobuf/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java | 18c9c74ec327ec204b22182cde5985966f8449ed | [
"LicenseRef-scancode-protobuf",
"Apache-2.0"
] | permissive | newrelic/newrelic-php-agent | 87ad20e0a5abf0d2855e7d27a25c36454ae4389a | dfb359f0dbb53e4cbc5106b52c8f3807c7fc8d42 | refs/heads/main | 2023-08-15T10:28:24.372352 | 2023-08-14T17:29:31 | 2023-08-14T17:29:31 | 302,112,572 | 116 | 67 | Apache-2.0 | 2023-09-13T18:33:47 | 2020-10-07T17:35:01 | C | UTF-8 | Java | false | false | 5,148 | java | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.google.protobuf;
import protobuf_unittest.UnittestProto;
import java.io.IOException;
import junit.framework.TestCase;
/**
* Tests to make sure the lazy conversion of UTF8-encoded byte arrays to strings works correctly.
*
* @author jonp@google.com (Jon Perlow)
*/
public class LazyStringEndToEndTest extends TestCase {
private static final ByteString TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8 =
ByteString.copyFrom(
new byte[] {
114, 4, -1, 0, -1, 0, -30, 2, 4, -1,
0, -1, 0, -30, 2, 4, -1, 0, -1, 0,
});
private ByteString encodedTestAllTypes;
@Override
protected void setUp() throws Exception {
super.setUp();
this.encodedTestAllTypes =
UnittestProto.TestAllTypes.newBuilder()
.setOptionalString("foo")
.addRepeatedString("bar")
.addRepeatedString("baz")
.build()
.toByteString();
}
/** Tests that an invalid UTF8 string will roundtrip through a parse and serialization. */
public void testParseAndSerialize() throws InvalidProtocolBufferException {
UnittestProto.TestAllTypes tV2 =
UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
ByteString bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
tV2.getOptionalString();
bytes = tV2.toByteString();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, bytes);
}
public void testParseAndWrite() throws IOException {
UnittestProto.TestAllTypes tV2 =
UnittestProto.TestAllTypes.parseFrom(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8);
byte[] sink = new byte[TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8.size()];
CodedOutputStream outputStream = CodedOutputStream.newInstance(sink);
tV2.writeTo(outputStream);
outputStream.flush();
assertEquals(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8, ByteString.copyFrom(sink));
}
public void testCaching() {
String a = "a";
String b = "b";
String c = "c";
UnittestProto.TestAllTypes proto =
UnittestProto.TestAllTypes.newBuilder()
.setOptionalString(a)
.addRepeatedString(b)
.addRepeatedString(c)
.build();
// String should be the one we passed it.
assertSame(a, proto.getOptionalString());
assertSame(b, proto.getRepeatedString(0));
assertSame(c, proto.getRepeatedString(1));
// Ensure serialization keeps strings cached.
proto.toByteString();
// And now the string should stay cached.
assertSame(a, proto.getOptionalString());
assertSame(b, proto.getRepeatedString(0));
assertSame(c, proto.getRepeatedString(1));
}
public void testNoStringCachingIfOnlyBytesAccessed() throws Exception {
UnittestProto.TestAllTypes proto = UnittestProto.TestAllTypes.parseFrom(encodedTestAllTypes);
ByteString optional = proto.getOptionalStringBytes();
assertSame(optional, proto.getOptionalStringBytes());
assertSame(optional, proto.toBuilder().getOptionalStringBytes());
ByteString repeated0 = proto.getRepeatedStringBytes(0);
ByteString repeated1 = proto.getRepeatedStringBytes(1);
assertSame(repeated0, proto.getRepeatedStringBytes(0));
assertSame(repeated1, proto.getRepeatedStringBytes(1));
assertSame(repeated0, proto.toBuilder().getRepeatedStringBytes(0));
assertSame(repeated1, proto.toBuilder().getRepeatedStringBytes(1));
}
}
| [
"joshua_benuck@yahoo.com"
] | joshua_benuck@yahoo.com |
b0e270842015313d318869b0ffceacacb9bb9063 | d423c0f0ee70bfbd427fc4abf983d36649fbda0f | /src/binarytrees/Tree.java | d83dd162adbca3fe00f6094dff5a504f9ba34cb5 | [] | no_license | msaadghouri/DataStructures | 9a8b8e32e51835277e7feedad4234710872f0c63 | 84991db5c6a902aa92aff093e13c89a3d03f507c | refs/heads/master | 2021-09-05T17:52:09.720121 | 2018-01-30T02:29:42 | 2018-01-30T02:29:42 | 113,509,067 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,455 | java | package binarytrees;
public class Tree {
public static void main(String[] args) {
BinaryTree tree= new BinaryTree();
tree.insert(5);
tree.insert(8);
tree.insert(10);
tree.insert(9);
tree.insert(2);
}
}
// Root value is less than the right child and greater than the left child.
class BinaryTree{
Node root;
int minValue=Integer.MAX_VALUE;
public void insert(int data){
Node node= new Node(data);
if(root==null)
root=node; // Is root is null, set first node as root
else{
Node current=root, parent;
while(true){
parent=current;
if(data>current.data){ // If node's value is greater than root, go right.
current=current.rightChild;
if(current==null){
parent.rightChild=node;
return;
}
}else{ // If node's value is less than root, go left.
current=current.leftChild;
if(current==null){
parent.leftChild=node;
return;
}
}
}
}
}
// Iterative process to find a key in Binary tree
public boolean findKey(int key){
Node current=root;
while(current.data!=key){
if(key>current.data)
current=current.rightChild;
else
current=current.leftChild;
if(current==null)
return false;
}
return true;
}
// Inorder prints the tree in the following order: Left node, root, right node
public void printInorder(Node root){
if(root!=null){
printInorder(root.leftChild);
System.out.print(root.data+" ");
printInorder(root.rightChild);
}
}
// Inorder prints the tree in the following order: Root, left node, right node
public void printPreorder(Node root){
if(root!=null){
System.out.print(root.data+" ");
printPreorder(root.leftChild);
printPreorder(root.rightChild);
}
}
// Inorder prints the tree in the following order: Left node, right node, root
public void printPostorder(Node root){
if(root!=null){
printPostorder(root.leftChild);
printPostorder(root.rightChild);
System.out.print(root.data+" ");
}
}
// Recursive way to find a minimum in Binary tree
public void findMinInBT(Node root){
if(root!=null){
findMinInBT(root.leftChild);
if(root.data<minValue){
minValue=root.data;
}
findMinInBT(root.rightChild);
}
}
// The left most node of the tree is the minimum
public Node findMinimumInBST(){
Node current, last = null;
current=root;
while(current!=null){
last=current;
current=current.leftChild; // rightChild for max
}
return last;
}
} | [
"gxmohammads@ualr.edu"
] | gxmohammads@ualr.edu |
a708354e55aa03ea994f0c6f048079588f9f6a1b | 2cd64269df4137e0a39e8e67063ff3bd44d72f1b | /commercetools/commercetools-sdk-java-api/src/main/java-predicates-generated/com/commercetools/api/predicates/query/error/GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl.java | 6aa72834e88399c31722dc46bce32f04a7c8c0f1 | [
"Apache-2.0",
"GPL-2.0-only",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"BSD-3-Clause",
"Classpath-exception-2.0"
] | permissive | commercetools/commercetools-sdk-java-v2 | a8703f5f8c5dde6cc3ebe4619c892cccfcf71cb8 | 76d5065566ff37d365c28829b8137cbc48f14df1 | refs/heads/main | 2023-08-14T16:16:38.709763 | 2023-08-14T11:58:19 | 2023-08-14T11:58:19 | 206,558,937 | 29 | 13 | Apache-2.0 | 2023-09-14T12:30:00 | 2019-09-05T12:30:27 | Java | UTF-8 | Java | false | false | 1,149 | java |
package com.commercetools.api.predicates.query.error;
import com.commercetools.api.predicates.query.*;
public class GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl {
public GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl() {
}
public static GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl of() {
return new GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl();
}
public StringComparisonPredicateBuilder<GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl> code() {
return new StringComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("code")),
p -> new CombinationQueryPredicate<>(p, GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl::of));
}
public StringComparisonPredicateBuilder<GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl> exceededResource() {
return new StringComparisonPredicateBuilder<>(
BinaryQueryPredicate.of().left(new ConstantQueryPredicate("exceededResource")),
p -> new CombinationQueryPredicate<>(p, GraphQLMaxResourceLimitExceededErrorQueryBuilderDsl::of));
}
}
| [
"automation@commercetools.com"
] | automation@commercetools.com |
1039ab74de08c8768680ab9d1018ff71d44277e6 | 044de9c0d511ba277e5dbe2fabcc2123dd9713ca | /Innovo/src/main/java/mandj/appbuildin/codingcoach/innovo/Learn/LearnSpinner.java | c2590cc577e0ab78eb59e9c07297179a07e172da | [] | no_license | joeyfedor/CodingCoach | 73fd844795d0a79e51bbdc3f878f5884ee3d9b66 | df9dbfa430d58b78a0099f67411894b359af53c6 | refs/heads/master | 2020-03-29T20:43:37.796118 | 2018-09-25T20:52:22 | 2018-09-25T20:52:23 | 150,326,127 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,929 | java | package mandj.appbuildin.codingcoach.innovo.Learn;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import mandj.appbuildin.codingcoach.innovo.Feedback;
import mandj.appbuildin.codingcoach.innovo.R;
import mandj.appbuildin.codingcoach.innovo.Settings;
public class LearnSpinner extends AppCompatActivity implements ActionBar.OnNavigationListener, LearnFragment.OnFragmentInteractionListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn_spinner);
// Set up the action bar to show a dropdown list.
Toolbar bar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(bar);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(
actionBar.getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}),
this);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.learn_spinner, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, Settings.class);
intent.putExtra("callingActivity", "Learn");
startActivity(intent);
return true;
}
if (id == R.id.action_feedback) {
Intent intent = new Intent(this, Feedback.class);
intent.putExtra("callingActivity", "Learn");
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
// When the given dropdown item is selected, show its contents in the
// container view.
getFragmentManager().beginTransaction()
.replace(R.id.container, PlaceholderFragment.newIInstance(position + 1, this))
.commit();
return true;
}
@Override
public void onFragmentInteraction(String str) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public static Fragment newIInstance(int sectionNumber, Context context) {
Class<?> clss = LearnFragment.class;
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
Fragment fragment = Fragment.instantiate(context, clss.getName(), args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_learn_spinner, container, false);
return rootView;
}
}
}
| [
"fedJoseph@ultimtek.com"
] | fedJoseph@ultimtek.com |
f60f149d3b70f91ed1c2952ce73387964b28b1d1 | 5d6f0a5ff77a231ab9aaff08817ccf7f4eef1bda | /drools/src/com/intellij/plugins/drools/lang/psi/impl/DroolsLhsPatternBindVariableImpl.java | 8c45634b79309ed5efbb002c244932703cd41b64 | [
"Apache-2.0"
] | permissive | vikrant21st/intellij-plugins | b62a71e3410bc0a96c4d42ecdc0271c2d7d5fd00 | b3b1c5b9079cee182e04a561b9da9a76dd952760 | refs/heads/master | 2023-01-12T20:51:07.916439 | 2022-12-14T19:57:03 | 2022-12-14T22:10:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,168 | java | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.plugins.drools.lang.psi.impl;
import com.intellij.lang.ASTNode;
import com.intellij.plugins.drools.lang.psi.DroolsLhsPatternBind;
import com.intellij.plugins.drools.lang.psi.DroolsNameId;
import com.intellij.plugins.drools.lang.psi.util.DroolsResolveUtil;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiType;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
public abstract class DroolsLhsPatternBindVariableImpl extends DroolsAbstractVariableImpl implements DroolsLhsPatternBind {
public DroolsLhsPatternBindVariableImpl(@NotNull ASTNode node) {
super(node);
}
@Override
public DroolsNameId getNamedIdElement() {
return getNameId();
}
@NotNull
@Override
public PsiType getType() {
final Set<PsiClass> psiClasses = DroolsResolveUtil.getPatternBindType(this.getLhsPatternList());
return psiClasses.size() == 0 ? PsiType.NULL : JavaPsiFacade.getElementFactory(getProject()).createType(psiClasses.iterator().next());
}
}
| [
"intellij-monorepo-bot-no-reply@jetbrains.com"
] | intellij-monorepo-bot-no-reply@jetbrains.com |
1c638714e3499b3747c7de76a66328b372629c6a | 5518b8444885da58a348b027f0f75b592ce41b41 | /src/test/java/ru/stqa/ptf/addressbook/Tests/ContactCreationTest.java | d7232451f1a8f0d827ef483816df45209efa1428 | [
"Apache-2.0"
] | permissive | Svjatoslav2011/Selenium | af15a9adbb134c22c78b9942830f01b13c867fd8 | a4031ff9300ea60212ac6f831569b6ae0cd42532 | refs/heads/master | 2020-04-07T13:00:26.750531 | 2018-12-14T11:11:25 | 2018-12-14T11:11:25 | 158,389,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,707 | java | package com.example.tests;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import ru.stqa.ptf.addressbook.model.ContactData;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.fail;
public class ContactCreationTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
driver = new ChromeDriver();
baseUrl = "https://www.katalon.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
login("admin", "secret");
}
private void login(String username, String password) {
driver.get("http://localhost/addressbook/");
driver.findElement(By.name("user")).click();
driver.findElement(By.name("user")).clear();
driver.findElement(By.name("user")).sendKeys(username);
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(password);
driver.findElement(By.id("LoginForm")).click();
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Password:'])[1]/following::input[2]")).click();
}
@Test
public void testContactCreation() throws Exception {
initContactCreation();
fillContactForm(new ContactData("Svjat", "Vozgrin", "London, 331"));
submitContactCreation();
}
private void submitContactCreation() {
driver.findElement(By.xpath("(.//*[normalize-space(text()) and normalize-space(.)='Notes:'])[1]/following::input[1]")).click();
}
private void fillContactForm(ContactData contactData) {
driver.findElement(By.name("firstname")).click();
driver.findElement(By.name("firstname")).clear();
driver.findElement(By.name("firstname")).sendKeys(contactData.getName());
driver.findElement(By.name("theform")).click();
driver.findElement(By.name("lastname")).click();
driver.findElement(By.name("lastname")).clear();
driver.findElement(By.name("lastname")).sendKeys(contactData.getLastName());
driver.findElement(By.name("address")).clear();
driver.findElement(By.name("address")).sendKeys(contactData.getAddress());
}
private void initContactCreation() {
driver.findElement(By.linkText("add new")).click();
}
@AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| [
"Svjatoslav.Vozgrin@gmail.com"
] | Svjatoslav.Vozgrin@gmail.com |
ddb38886cab66b9b63bda772ff75cdd55ef32b75 | c179bf3dd458835c78e479a057221cffb65c917e | /src/com/Manage/control/RemoteOnlineDeviceControlNews.java | 601d7cf99694efc4754c1b8e5c3e6de422a7e290 | [] | no_license | 1Discount/ylcyManage | b49549b4586865d45cecb471e4637ac52b0d81c5 | 3b10a9e786b6908ab5ca57c8270f23239fa28656 | refs/heads/master | 2021-09-06T06:49:22.169585 | 2018-02-03T12:09:02 | 2018-02-03T12:09:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 40,531 | java | package com.Manage.control;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Case;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.Manage.common.cache.CacheUtils;
import com.Manage.common.constants.Constants;
import com.Manage.common.exception.BmException;
import com.Manage.common.latlng.LocTest;
import com.Manage.common.util.DateUtils;
import com.Manage.common.util.LogUtil;
import com.Manage.common.util.PropertiesLoader;
import com.Manage.common.util.StringUtils;
import com.Manage.entity.AdminOperate;
import com.Manage.entity.AdminUserInfo;
import com.Manage.entity.CountryInfo;
import com.Manage.entity.DeviceInfo;
import com.Manage.entity.DeviceLogs;
import com.Manage.entity.EquipLogs;
import com.Manage.entity.GStrenthData;
import com.Manage.entity.LocTemp;
import com.Manage.entity.OrdersInfo;
import com.Manage.entity.common.Page;
import com.kdt.api.YouzanConfig;
import com.sun.corba.se.spi.orb.StringPair;
@Controller
@RequestMapping("/remote2")
public class RemoteOnlineDeviceControlNews extends BaseController
{
private Logger logger = LogUtil.getInstance(RemoteOnlineDeviceControlNews.class);
@RequestMapping("/index")
public String remoteindex(Model model)
{
AdminUserInfo adminUserInfo = (AdminUserInfo) getSession().getAttribute("User");
if (adminUserInfo == null)
{
return "login";
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("Countries", countries);
return "WEB-INF/views/service/remote_OnlineDevice";
}
@RequestMapping("/Serverindex")
public String Serverindex()
{
return "WEB-INF/views/service/remote_Server";
}
/**
* 跳转到设备日志历史记录
*
* @return
*/
@RequestMapping("/toSNLogs")
public String toSNLogs()
{
return "WEB-INF/views/service/equip_sn_logs";
}
/**
* 限速
*
* @param limitValve
* @param limitSpeed
* @param sn
* @param response
*/
@RequestMapping("/limitspeed")
public void limitspeed(String limitValve, String limitSpeed, String sn, String ps, Model model, HttpServletResponse response)
{
try
{
if (StringUtils.isBlank(limitValve) || StringUtils.isBlank(limitSpeed))
{
response.getWriter().print("-1");
}
else
{
int temp = commandSer2.limitspeed(limitValve, limitSpeed, sn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
if (StringUtils.isNotBlank(ps))
{
// model.addAttribute("sn",sn);
}
// return "WEB-INF/views/service/remote_OnlineDevice";
}
@RequestMapping("/remoteQuery")
public void remoteQuery(String mes, String sn, String ps, Model model, HttpServletResponse response)
{
try
{
if (StringUtils.isBlank(mes))
{
response.getWriter().print("-1");
}
else
{
int temp = commandSer2.remoteQuery(mes, sn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
if (StringUtils.isNotBlank(ps))
{
// model.addAttribute("sn",sn);
}
// return "WEB-INF/views/service/remote_OnlineDevice";
}
@RequestMapping("/modificationAPN")
public void modificationAPN(String apn, String sn, String ps, Model model, HttpServletResponse response)
{
try
{
if (StringUtils.isBlank(apn))
{
response.getWriter().print("-1");
}
else
{
int temp = commandSer2.modificationAPN(apn, sn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
if (StringUtils.isNotBlank(ps))
{
// model.addAttribute("sn",sn);
}
// return "WEB-INF/views/service/remote_OnlineDevice";
}
/**
* 提取日志
*
* @param bm
* @param num
* @param sn
* @param ps
* @param model
* @param response
*/
@RequestMapping("/getDevLogs")
public void getDevLogs(String bm, String num, String sn, String ps, Model model, HttpServletResponse response)
{
try
{
if (StringUtils.isBlank(num))
{
num = "0";
}
int temp = commandSer2.getDevLogs(Integer.parseInt(bm), num, sn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
else if (temp == -2)
{
response.getWriter().print("-3");
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
if (StringUtils.isNotBlank(ps))
{
}
// return "WEB-INF/views/service/remote_OnlineDevice";
}
/**
* 远程升级
*
* @param type
* @param sn
* @param ps
* @param newVersion
* @param fileTypeString
* @param model
* @param response
*/
@RequestMapping("/remoteUpgrade")
public void remoteUpgrade(String type, String sn, String ps, String newVersion, String fileTypeString, Model model, HttpServletResponse response)
{
AdminUserInfo user = (AdminUserInfo) getSession().getAttribute("User");
try
{
int temp = commandSer2.remoteUpgrade(type, sn);
if (temp == 1)
{
// 在这里插入用户操作日志
// 1.获取到文件类型 版本号、操作类型、
String versionNO = newVersion;
String fileType = fileTypeString;
try
{
AdminOperate admin = new AdminOperate();
admin.setOperateID(UUID.randomUUID().toString());// id
admin.setCreatorDate(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));// 创建时间
admin.setCreatorUserID(user.getUserID());// 创建人ID
admin.setCreatorUserName(user.getUserName());// 创建人姓名
admin.setOperateDate(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));// 操作时间
admin.setSysStatus(1);
admin.setOperateContent("远程升级, 用户ID为: " + user.getUserID() + " 名称: " + user.getUserName() + "版本号:" + versionNO + "文件类型:" + fileType + "设备序列号:" + sn);
admin.setOperateMenu("远程服务>远程升级");
admin.setOperateType("升级");
adminOperateSer.insertdata(admin);
}
catch (Exception e)
{
e.printStackTrace();
}
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
else if (temp == -2)
{
response.getWriter().print("-3");
}
}
catch (Exception e)
{
logger.info(e.getMessage());
}
}
/**
* 查看日志入口
*
* @param model
* @return
*/
@RequestMapping("/tologs")
public String tologs(String SN, Model model)
{
model.addAttribute("SN", SN);
return "WEB-INF/views/service/equip_logs_list";
}
/**
* 查看日志列表
*
* @param sn
* @param type
* @param response
*/
@RequestMapping("/getlogs")
public void getlogs(String sn, String type, HttpServletResponse response)
{
try
{
EquipLogs equipLogs = new EquipLogs();
if (StringUtils.isBlank(sn))
{
equipLogs.setSN("000");
}
else
{
equipLogs.setSN(sn);
}
equipLogs.setType(Integer.parseInt(type));
List<EquipLogs> ls = equipLogsSer.getbysn(equipLogs);
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray();
if (ls != null && ls.size() > 0)
{
for (EquipLogs equipLogs2 : ls)
{
JSONObject object2 = JSONObject.fromObject(equipLogs2);
jsonArray.add(object2);
}
object.put("data", jsonArray);
}
else
{
object.put("data", "[]");
}
object.put("success", true);
object.put("totalRows", ls.size());
response.getWriter().print(object.toString());
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
}
/**
* 删除日志
*
* @param id
* @param response
*/
@RequestMapping("/delinfo")
public void delinfo(String id, HttpServletResponse response)
{
try
{
if (id == null || "".equals(id))
{
response.getWriter().print("-1");
return;
}
if (equipLogsSer.delinfo(id))
{
response.getWriter().print("1");
}
else
{
response.getWriter().print("0");
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
}
/**
* 查看日志
*
* @param ID
* @return
*/
@RequestMapping("/logsview")
public String logsview(String ID, Model model)
{
if (!StringUtils.isNotBlank(ID))
{
return "WEB-INF/views/service/equip_logs_list";
}
try
{
EquipLogs equipLogs = new EquipLogs();
equipLogs.setID(ID);
List<EquipLogs> list = equipLogsSer.getbyid(equipLogs);
if (list != null && list.size() == 1)
{
EquipLogs equipLogs2 = list.get(0);
if (equipLogs2.getType() == 1)
{
model.addAttribute("title", "设备" + equipLogs2.getSN() + "的漫游日志:");
model.addAttribute("content", equipLogs2.getContent());
}
else if (equipLogs2.getType() == 2)
{
model.addAttribute("title", "设备" + equipLogs2.getSN() + "的本地日志:");
model.addAttribute("content", equipLogs2.getContent());
}
return "WEB-INF/views/service/equip_logs_content";
}
else
{
model.addAttribute("err", "日志读取失败");
return "WEB-INF/views/service/equip_logs_list";
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
model.addAttribute("err", "日志读取失败");
return "WEB-INF/views/service/equip_logs_list";
}
}
/**
* 消息推送 00 表示都没数据 01表示升级成功 02表示升级失败 10表示日志成 20表示日志失败
*/
@RequestMapping("/mesPush")
public void mesPush(HttpServletResponse response)
{
try
{
if (StringUtils.isNotBlank(CacheUtils.get("logsuccess")))
{
String logsuccess = CacheUtils.get("logsuccess").toString();
if ("1".equals(logsuccess))
{
response.getWriter().print("1");
}
else
{
response.getWriter().print("2");
}
CacheUtils.remove("logsuccess");
}
else
{
response.getWriter().print("0");
}
if (StringUtils.isNotBlank(CacheUtils.get("upgradesuccess")))
{
String logsuccess = CacheUtils.get("upgradesuccess").toString();
if ("1".equals(logsuccess))
{
response.getWriter().print("1");
}
else
{
response.getWriter().print("2");
}
CacheUtils.remove("upgradesuccess");
}
else
{
response.getWriter().print("0");
}
}
catch (Exception e)
{
// TODO: handle exception
}
}
/**
* 远程重插卡
*/
@RequestMapping("/rePlugSIM")
public void rePlugSIM(String SN, HttpServletResponse response)
{
try
{
if (StringUtils.isNotBlank(SN))
{
int temp = commandSer2.rePlugSIM(SN);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
else
{
response.getWriter().print("-1");
}
}
catch (Exception e)
{
// TODO: handle exception
}
}
/**
* 远程换卡
*
* @param SN
* @param response
*/
@RequestMapping("/changeCard")
public void changeCard(String SN, HttpServletResponse response)
{
try
{
if (StringUtils.isNotBlank(SN))
{
int temp = commandSer2.changeCard(SN);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
else
{
response.getWriter().print("-1");
}
}
catch (Exception e)
{
// TODO: handle exception
}
}
/**
* 远程关机
*
* @param SN
* @param response
*/
@RequestMapping("/remoteShutdown")
public void remoteShutdown(String SN, HttpServletResponse response)
{
try
{
if (StringUtils.isNotBlank(SN))
{
int temp = commandSer2.remoteShutdown(SN);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
else
{
response.getWriter().print("-1");
}
}
catch (Exception e)
{
// TODO: handle exception
}
}
@RequestMapping("/modificationAPNServer")
public String modificationAPNServer(String apn, String sn, Model model)
{
try
{
if (StringUtils.isBlank(apn))
{
return "WEB-INF/views/service/remote_Server";
}
int temp = commandSer2.modificationAPN(apn, sn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
return "WEB-INF/views/service/remote_Server";
}
@RequestMapping("/restPwd")
public void restPwd(String SN, HttpServletResponse response)
{
try
{
if (StringUtils.isNotBlank(SN))
{
int temp = commandSer2.restPwd(SN);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
else
{
response.getWriter().print("-1");
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
}
@RequestMapping("/modifyVPN")
public void modifyVPN(String sn, String vpn, HttpServletResponse response, Model model)
{
try
{
if (StringUtils.isNotBlank(sn))
{
int temp = commandSer2.modifyVPN(sn, vpn);
if (temp == 1)
{
response.getWriter().print("1");
}
else if (temp == 0)
{
response.getWriter().print("0");
}
else if (temp == -1)
{
response.getWriter().print("-2");
}
}
else
{
response.getWriter().print("-1");
}
}
catch (Exception e)
{
// TODO: handle exception
logger.info(e.getMessage());
}
// return "WEB-INF/views/service/remote_Server";
}
@RequestMapping("/upload")
public String upload(HttpServletRequest req, HttpSession session, Model model)
{
AdminUserInfo adminUserInfo = (AdminUserInfo) getSession().getAttribute("User");
if (adminUserInfo == null)
{
return "login";
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("Countries", countries);
model.addAttribute("temp", req.getSession().getAttribute("temp"));
req.getSession().setAttribute("temp", ""); // 及时清空, 避免污染其他页面
return "WEB-INF/views/service/remote_upload";
}
/**
* 升级文件上传
*
* @param file
* @param localhost
* @param newVersion
* @param req
* @param resp
* @param session
* @param model
* @return
*/
@RequestMapping("/uploadding")
public String uploadding(@RequestParam("file") MultipartFile file, HttpServletRequest req, HttpServletResponse resp, HttpSession session, Model model)
{
logger.info("开始上传");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
String logoPathDir = "/upload/";
// 得到保存目录的真实路径
String temp = request.getSession().getServletContext().getRealPath(logoPathDir);
// 创建文件保存路径文件夹
File tempFile = new File(temp);
if (!tempFile.exists())
{
tempFile.mkdirs();
}
// 获取到文件
MultipartFile multipartFile = multipartRequest.getFile("file");
logger.info("成功获取文件");
String fName = multipartFile.getOriginalFilename();
String logExcelName = ""; // 原始升级文件名
String newVersion = ""; // 版本号
String fileTypeString = ""; // 文件类型
if (fName.contains("local_client"))
{
fileTypeString = "本地";
logExcelName = "local_client";
if (fName.indexOf("-") > 0)
{
newVersion = fName.split("-")[1];
}
}
else if (fName.contains("xmclient"))
{
fileTypeString = "漫游";
logExcelName = "xmclient";
if (fName.indexOf("-") > 0)
{
newVersion = fName.split("-")[1];
}
}
else if (fName.contains("CellDataUpdaterRoam"))
{
fileTypeString = "漫游APK";
logExcelName = "CellDataUpdaterRoam.apk";
if (fName.indexOf("-") > 0)
{
String temps = fName.split("-")[1];
newVersion = temps.split("\\.")[0];
}
}
else if (fName.contains("CellDataUpdater"))
{
fileTypeString = "本地APK";
logExcelName = "CellDataUpdater.apk";
if (fName.indexOf("-") > 0)
{
String temps = fName.split("-")[1];
String[] tt = temps.split("\\.");
newVersion = tt[0];
}
}
else if (fName.contains("MIP"))
{
fileTypeString = "MIP";
logExcelName = "MIP.ini";
if (fName.indexOf("-") > 0)
{
String temps = fName.split("-")[1];
newVersion = temps.split("\\.")[0];
}
}
else if (fName.contains("Settings"))
{
fileTypeString = "本地Settings";
logExcelName = "Settings.apk";
if (fName.indexOf("-") > 0)
{
String temps = fName.split("-")[1];
newVersion = temps.split("\\.")[0];
}
}
else if (fName.contains("Phone"))
{
fileTypeString = "Phone.apk";
logExcelName = "Phone.apk";
if (fName.indexOf("-") > 0)
{
String temps = fName.split("-")[1];
newVersion = temps.split("\\.")[0];
}
}
else
{
logger.info("上传文件格式不正确");
req.setAttribute("temp", "-1");
return "WEB-INF/views/service/remote_upload";
}
/** 拼成完整的文件保存路径加文件 **/
String fileName = temp + File.separator + logExcelName;
File files = new File(fileName);
logger.info("升级文件的上传路径" + files);
if (files.exists())
{
files.delete();
}
// 获取到文件的最后更新时间
long time = files.lastModified();// lastSaveTime
String lastSaveTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time));
try
{
multipartFile.transferTo(files);
// 在这里存入缓存
Object object = CacheUtils.get("fileCache", "version");
JSONObject json = null;
if (object == null || "".equals(object.toString()))
{
json = new JSONObject();
}
else
{
// 进来说明从缓存里获取到了数据
json = JSONObject.fromObject(object.toString());
CacheUtils.remove("fileCache", "version");
}
if (json.containsKey(logExcelName))
{
json.remove(logExcelName);
}
json.put(logExcelName, newVersion + "," + lastSaveTime);
CacheUtils.put("fileCache", "version", json.toString());
req.setAttribute("temp", "1");
req.setAttribute("fileTypeString", fileTypeString);
req.setAttribute("newVersion", newVersion);
logger.info("上传成功");
return "WEB-INF/views/service/remote_upload";
}
catch (IllegalStateException e)
{
req.setAttribute("temp", "0");
e.printStackTrace();
logger.info("上传失败");
return "WEB-INF/views/service/remote_upload";
}
catch (IOException e)
{
req.setAttribute("temp", "0");
e.printStackTrace();
logger.info("上传失败");
return "WEB-INF/views/service/remote_upload";
}
}
/* 拿到文件对应的版 本号 */
public String getversion(String path, int index)
{
try
{
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String string = br.readLine();
String[] apk = string.split("/");
br.close();
return apk[index];
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/* 写 */
public void writeversion(String txtString, String path) throws IOException
{
FileWriter fw = new FileWriter(path);
BufferedWriter writer = new BufferedWriter(fw);
writer.write(txtString);
writer.flush();
writer.close();
}
/* 读 */
public String replaceversion(String path, int index, String newversion)
{
try
{
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String[] string = br.readLine().split("/");
string[index] = newversion;
String txt = "";
for (int i = 0; i < string.length; i++)
{
if (i == string.length - 1)
{
txt = txt + string[i];
break;
}
txt = txt + string[i] + "/";
}
br.close();
System.out.println(txt);
return txt;
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
/* 下拉框的值改变 */
@RequestMapping("/selectchange")
public void selectchange(String apkName, HttpServletRequest req, HttpServletResponse resp, Model model) throws IOException
{
resp.setCharacterEncoding("utf-8");
String version = gettagString(apkName);
if (StringUtils.isNotBlank(version))
{
version = version.split(",")[0];
}
PrintWriter writer = resp.getWriter();
writer.print(version);
writer.flush();
writer.close();
}
public String gettagString(String sn)
{
Object object = CacheUtils.get("fileCache", "version");
JSONObject json = null;
if (object == null || "".equals(object.toString()))
{
return "";
}
else
{
json = JSONObject.fromObject(object.toString());
if (json.containsKey(sn))
{
return json.getString(sn);
}
else
{
return "";
}
}
}
/* 下载日志 */
@RequestMapping("/savelog")
public String savelog(String fileName, String id, HttpServletResponse response, HttpServletRequest request)
{
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");// inline attachment
response.setHeader("Content-Disposition", "inline;fileName=" + fileName);
try
{
EquipLogs equiplogs = new EquipLogs();
equiplogs.setID(id);
String log = equipLogsSer.getcontent(equiplogs).getContent();
InputStream inputStream = getStringStream(log);
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int length;
while ((length = inputStream.read(b)) > 0)
{
os.write(b, 0, length);
byte[] newLine = "/t".getBytes();
// 写入换行
os.write(newLine);
}
os.close();
inputStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
public static InputStream getStringStream(String sInputString)
{
if (sInputString != null && !sInputString.trim().equals(""))
{
try
{
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
return tInputStringStream;
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return null;
}
/**
* 获取基站信息
*
* @return
*/
@RequestMapping("/mapView")
public String getLatlng(String jizhan, Model model, HttpServletResponse response)
{
logger.info("基站信息转换");
if (StringUtils.isBlank(jizhan))
{
logger.info("基站信息为空");
model.addAttribute("lat", "22.5445376939");
model.addAttribute("lon", "113.9329587977");
model.addAttribute("address", "比克大厦附近");
}
else
{
JSONObject object = LocTest.jizhantojw(jizhan, "50");
if ("OK".equals(object.getString("cause")))
{
logger.info("基站转经纬度成功!");
model.addAttribute("lat", object.getString("lat"));
model.addAttribute("lon", object.getString("lon"));
model.addAttribute("address", object.getString("address"));
// model.addAttribute("radius",object.getString("radius"));
return "WEB-INF/views/service/map";
}
else
{
logger.info("基站转经纬度失败:" + object.getString("cause"));
}
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("Countries", countries);
return "WEB-INF/views/service/map";
}
/**
* 获取基站信息
*
* @return
*/
@RequestMapping("/PosmapView")
public String PosmapView(String jizhan, Model model, HttpServletResponse response)
{
logger.info("基站信息转换");
if (StringUtils.isBlank(jizhan))
{
logger.info("基站信息为空");
model.addAttribute("lat", "22.5414506852");
model.addAttribute("lon", "113.9330059977");
model.addAttribute("address", "比克大厦附近");
}
else
{
JSONObject object = LocTest.jizhantojw(jizhan, "50");
if ("OK".equals(object.getString("cause")))
{
logger.info("基站转经纬度成功!");
model.addAttribute("lat", object.getString("lat"));
model.addAttribute("lon", object.getString("lon"));
model.addAttribute("address", object.getString("address"));
// model.addAttribute("radius",object.getString("radius"));
return "WEB-INF/views/service/map_pos";
}
else
{
logger.info("基站转经纬度失败:" + object.getString("cause"));
}
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("ifopen", Constants.TIMING_ADDJZTEMP);
model.addAttribute("Countries", countries);
return "WEB-INF/views/service/map_pos";
}
/**
* 异步获取基站信息
*
* @return
*/
@RequestMapping("/getLatlng")
public void getLatlngAjax(String jizhan, Model model, HttpServletResponse response)
{
logger.info("基站信息转换");
if (StringUtils.isBlank(jizhan))
{
logger.info("基站信息为空");
}
else
{
JSONObject object = LocTest.jizhantojw(jizhan, "50");
if ("OK".equals(object.getString("cause")))
{
try
{
response.getWriter().print(object.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
logger.info("基站转经纬度失败:" + object.getString("cause"));
try
{
response.getWriter().print(object.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 异步获取基站信息
*
* @return
*/
@RequestMapping("/getLatlngBySN")
public void getLatlngBySN(String SN, Model model, HttpServletResponse response)
{
logger.info("基站信息转换");
if (StringUtils.isBlank(SN))
{
logger.info("SN为空!");
}
else
{
// 查询该SN最近10条不重复的基站信息
DeviceLogs dLogs = new DeviceLogs();
dLogs.setSN(SN);
dLogs.setTableName(Constants.DEVTABLEROOT_STRING + DateUtils.getDate().replace("-", ""));
List<DeviceLogs> dList = deviceLogsSer.getJZ(dLogs);
if (dList != null && dList.size() > 0)
{
JSONArray jArray = new JSONArray();
// 由后到前排序.
for (int i = dList.size() - 1; i > -1; i--)
{
JSONObject object = LocTest.jizhantojw(dList.get(i).getJizhan(), "50");
if ("OK".equals(object.getString("cause")))
{
jArray.add(object);
}
}
try
{
response.getWriter().print(jArray.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 信号强度分析
*
* @param SN
* @param model
* @param response
*/
@RequestMapping("/GStrenth")
public void GStrenth(GStrenthData gd, Model model, HttpServletResponse response)
{
JSONArray jaArray = gStrenthDataSer.getbyMCC(gd);
if (StringUtils.isNotBlank(jaArray))
{
try
{
response.getWriter().print(jaArray.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try
{
response.getWriter().print("0");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@RequestMapping("/getversioninfo")
public void getversioninfo(HttpServletResponse resp)
{
JSONObject object = new JSONObject();
object.put("success", true);
object.put("totalRows", 5);
object.put("curPage", 1);
JSONArray ja = new JSONArray();
List<String> filesList = new ArrayList<>();
filesList.add("manyou");
filesList.add("localhost");
filesList.add("mapk");
filesList.add("lapk");
filesList.add("MIP");
for (String fileName : filesList)
{
String version = gettagString(fileName);
JSONObject obj = new JSONObject();
switch (fileName)
{
case "manyou":
fileName = "漫游";
break;
case "localhost":
fileName = "本地";
break;
case "mapk":
fileName = "漫游apk";
break;
case "lapk":
fileName = "本地apk";
break;
case "MIP":
fileName = "MIP";
break;
}
obj.put("fileName", fileName);
if (StringUtils.isNotBlank(version))
{
obj.put("version", version.split(",")[0]);
obj.put("lastUpdateTime", version.split(",")[1]);
}
else
{
obj.put("version", "");
obj.put("lastUpdateTime", "");
}
ja.add(obj);
}
object.put("data", ja);
try
{
System.out.println(object.toString());
resp.getWriter().print(object.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* String version=gettagString(apkName);
* if(StringUtils.isNotBlank(version)){ version = version.split(",")[0];
* }
*/
}
/**
* 异步获取基站信息
*
* @return
*/
@RequestMapping("/getLatlngArr")
public void getLatlngAjaxArr(String jizhan, Model model, HttpServletResponse response)
{
logger.info("多基站信息转换");
if (StringUtils.isBlank(jizhan))
{
logger.info("基站信息为空");
}
else
{
String[] jizhanStrings = null;
if (jizhan.indexOf(",") > -1)
{
String[] ar = jizhan.split(",");
jizhanStrings = new String[ar.length];
for (int i = 0; i < ar.length; i++)
{
jizhanStrings[i] = ar[i];
}
}
else
{
jizhanStrings = new String[1];
jizhanStrings[0] = jizhan;
}
JSONObject object = LocTest.jizhantojwArray(jizhanStrings);
if ("OK".equals(object.getString("cause")))
{
try
{
response.getWriter().print(object.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
logger.info("基站转经纬度失败:" + object.getString("cause"));
try
{
response.getWriter().print(object.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 进去POS机查询界面
*
* @param model
* @param response
*/
@RequestMapping("/toPosMap")
public void toPosMap(Model model, HttpServletResponse response)
{
// 查询POS机最新基站列表
DeviceLogs de = new DeviceLogs();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
String times = format.format(date);
String tname = "DeviceLogs_" + times;
de.setTableName(tname);
de.setSN(Constants.getConfig("POS.sn"));
List<DeviceLogs> list = deviceLogsSer.getPOSjz(de);
if (list != null && list.size() > 0)
{
String snarrString = Constants.getConfig("POS.sn");
String jdmString = "";
if (snarrString.indexOf(",") > -1)
{
jdmString = deviceInfoSer.getbysn((snarrString.split(",")[1])).getDeviceColour();
}
else
{
jdmString = deviceInfoSer.getbysn(snarrString).getDeviceColour();
}
JSONArray jaArray = new JSONArray();
for (DeviceLogs d : list)
{
String jz = d.getJizhan();
String[] jarr = null;
if (jz.indexOf(",") > -1)
{
jarr = new String[] { jz.split(",")[0], jz.split(",")[1] };
}
else
{
jarr = new String[] { jz };
}
String[] arrtemp1 = jarr[0].split("\\.");
String[] arrtemp2 = jarr[1].split("\\.");
// 查询是否在基站组内.
LocTemp LT = new LocTemp();
LT.setLocalJZ(arrtemp1[0] + "." + arrtemp1[1] + "." + arrtemp1[2] + "." + arrtemp1[3]);
LT.setRoamJZ(arrtemp2[0] + "." + arrtemp2[1] + "." + arrtemp2[2] + "." + arrtemp2[3]);
List<LocTemp> lc = deviceLogsSer.getJWbyLike(LT);
if (lc != null && lc.size() > 0)
{
JSONObject object = new JSONObject();
object.put("lat", lc.get(0).getJW().split(",")[0]);
object.put("lon", lc.get(0).getJW().split(",")[1]);
object.put("SN", d.getSN());
DeviceInfo ddDeviceInfo = deviceInfoSer.getbysn(d.getSN());
object.put("jd", ddDeviceInfo.getRemark());
object.put("jdm", jdmString);
if (StringUtils.isBlank(ddDeviceInfo.getRemark()))
{
object.put("jdmjl", "未设置基点");
}
else
{
String[] re = ddDeviceInfo.getRemark().split(",");
Double double1 = LocTest.Distance(Double.parseDouble(object.getString("lon")), Double.parseDouble(object.getString("lat")), Double.parseDouble(re[1]), Double.parseDouble(re[0]));
String jlstrString = double1.toString().substring(0, double1.toString().indexOf("."));
logger.info(d.getSN() + "距基点:" + jlstrString + "米");
object.put("jdmjl", jlstrString);
}
jaArray.add(object);
}
else
{
// 过滤较远的基站
if (arrtemp1[3].contains("106293") || arrtemp1[3].contains("106493") || arrtemp1[3].contains("106619"))
{
if (jz.split(",").length >= 3)
{
jarr[0] = jz.split(",")[2];
}
}
if (arrtemp2[3].contains("106293") || arrtemp2[3].contains("106493") || arrtemp2[3].contains("106619"))
{
if (jz.split(",").length >= 4)
{
jarr[1] = jz.split(",")[3];
}
else if (jz.split(",").length >= 3)
{
jarr[1] = jz.split(",")[2];
}
}
JSONObject object = LocTest.jizhantojwArray(jarr);
if ("OK".equals(object.getString("cause")))
{
object.put("SN", d.getSN());
DeviceInfo ddDeviceInfo = deviceInfoSer.getbysn(d.getSN());
object.put("jd", ddDeviceInfo.getRemark());
object.put("jdm", jdmString);
if (StringUtils.isBlank(ddDeviceInfo.getRemark()))
{
object.put("jdmjl", "未设置基点");
}
else
{
String[] re = ddDeviceInfo.getRemark().split(",");
Double double1 = LocTest.Distance(Double.parseDouble(object.getString("lon")), Double.parseDouble(object.getString("lat")), Double.parseDouble(re[1]), Double.parseDouble(re[0]));
String jlstrString = double1.toString().substring(0, double1.toString().indexOf("."));
logger.info(d.getSN() + "距基点:" + jlstrString + "米");
object.put("jdmjl", jlstrString);
}
jaArray.add(object);
}
}
}
try
{
response.getWriter().print(jaArray.toString());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try
{
response.getWriter().print("-1");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 设置基点
*
* @param deviceInfo
* @param response
*/
@RequestMapping("/setLoc")
public void setLoc(DeviceInfo deviceInfo, HttpServletResponse response)
{
if (!StringUtils.isBlank(deviceInfo.getRemark()) || !StringUtils.isBlank(deviceInfo.getDeviceColour()))
{
if (StringUtils.isBlank(deviceInfo.getSN()))
{
String snarrString = Constants.getConfig("POS.sn");
if (snarrString.indexOf(",") > -1)
{
deviceInfo.setSN(snarrString.split(",")[1]);
}
else
{
deviceInfo.setSN(snarrString);
}
}
int temp = deviceInfoSer.updateRemark(deviceInfo);
if (temp > 0)
{
try
{
response.getWriter().print("1");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
try
{
response.getWriter().print("-1");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 导入样本数据
*
* @param deviceLogs
* @param dw
* @param response
*/
@RequestMapping("/batchAddJZTemp")
public void batchAddJZTemp(DeviceLogs deviceLogs, String dw, HttpServletResponse response)
{
// 查询原始数据
List<DeviceLogs> lds = deviceLogsSer.getjzlist(deviceLogs);
// 遍历组装,批量插入
if (lds != null && lds.size() > 0)
{
List<LocTemp> listtemp = new ArrayList<LocTemp>();
for (DeviceLogs d : lds)
{
String[] arr1 = d.getJizhan().split(",");
String[] arr2 = arr1[0].split("\\.");
String[] arr3 = arr1[1].split("\\.");
LocTemp LT = new LocTemp();
LT.setJW(dw);
LT.setLocalJZ(arr2[0] + "." + arr2[1] + "." + arr2[2]);
LT.setRoamJZ(arr3[0] + "." + arr3[1] + "." + arr3[2]);
LT.setLocalXH(arr2[3]);
LT.setRoamXH(arr3[3]);
listtemp.add(LT);
}
// 批量插入基站组数据.
int temp = deviceLogsSer.batchAddJZTemp(listtemp);
if (temp > 0)
{
try
{
response.getWriter().print(temp);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try
{
response.getWriter().print("-1");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
try
{
response.getWriter().print("-2");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* @param ifopen
* @param dw
* @param response
*/
@RequestMapping("/batchAddJZTempBtn")
public void batchAddJZTempBtn(String ifopen, String dw, HttpServletResponse response)
{
if ("1".equals(ifopen))
{
Constants.TIMING_ADDJZTEMP = true;
Constants.TIMING_ADDJZTEMP_JW = dw;
try
{
response.getWriter().print("1");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Constants.TIMING_ADDJZTEMP = false;
try
{
response.getWriter().print("2");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@RequestMapping("/index2")
public String remoteindex2(Model model)
{
AdminUserInfo adminUserInfo = (AdminUserInfo) getSession().getAttribute("User");
if (adminUserInfo == null)
{
return "login";
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("Countries", countries);
return "WEB-INF/views/service/remote_OnlineDevice_news";
}
@RequestMapping("/upload2")
public String upload2(HttpServletRequest req, HttpSession session, Model model)
{
AdminUserInfo adminUserInfo = (AdminUserInfo) getSession().getAttribute("User");
if (adminUserInfo == null)
{
return "login";
}
List<CountryInfo> countries = countryInfoSer.getAll("");
model.addAttribute("Countries", countries);
model.addAttribute("temp", req.getSession().getAttribute("temp"));
req.getSession().setAttribute("temp", ""); // 及时清空, 避免污染其他页面
return "WEB-INF/views/service/remote_upload_news";
}
}
| [
"benben683280@126.com"
] | benben683280@126.com |
6820de0476cf3d9eabb968f3c08dff7705212e29 | 81163711127303a602568314bfa00da7aafd38a2 | /meiqiasdk/src/main/java/com/meiqia/meiqiasdk/chatitem/MQConvDividerItem.java | a999327e68651b2f6d2c4626dcd5a85b08a8bba3 | [] | no_license | Meiqia/MeiqiaSDK-Android | 66252bba13cf1b41dc7d3fb4fe9b4bf1d7b034fa | ed7d03855f61b9aa6c2323fc2798c38c99fdf911 | refs/heads/master | 2023-08-26T15:16:47.604465 | 2023-02-16T02:26:07 | 2023-02-16T02:26:07 | 48,363,300 | 203 | 58 | null | 2023-09-04T02:29:29 | 2015-12-21T09:35:46 | Java | UTF-8 | Java | false | false | 833 | java | package com.meiqia.meiqiasdk.chatitem;
import android.content.Context;
import android.widget.TextView;
import com.meiqia.meiqiasdk.R;
import com.meiqia.meiqiasdk.util.MQTimeUtils;
import com.meiqia.meiqiasdk.widget.MQBaseCustomCompositeView;
public class MQConvDividerItem extends MQBaseCustomCompositeView {
private TextView contentTv;
public MQConvDividerItem(Context context, long createTime) {
super(context);
contentTv.setText(MQTimeUtils.partLongToMonthDay(createTime));
}
@Override
protected int getLayoutId() {
return R.layout.mq_item_conv_divider;
}
@Override
protected void initView() {
contentTv = findViewById(R.id.content_tv);
}
@Override
protected void setListener() {
}
@Override
protected void processLogic() {
}
} | [
"312965601@qq.com"
] | 312965601@qq.com |
8f5f416cf68af6d503d2741b7e25bcc3ab514856 | 710aff979c2a4151a28757f3c1de0b77dad5df77 | /fixture/src/main/java/info/matchingservice/fixture/ProfileElementConfig/ProfileElementChoicesForSupply.java | 7746fa8d799972424734bcef5632284e39597b93 | [] | no_license | johandoornenbal/matching | b5500eef829e76096bd47a1fb513894a7d2c40df | d17d35d9d21dfafd335b1cfcbbb3f56ad1fceed1 | refs/heads/master | 2021-01-24T16:10:38.419500 | 2015-12-15T08:09:18 | 2015-12-15T08:09:18 | 21,899,439 | 0 | 5 | null | 2015-04-03T12:59:24 | 2014-07-16T12:19:12 | Java | UTF-8 | Java | false | false | 3,067 | java | /*
* Copyright 2015 Yodo Int. Projects and Consultancy
*
* 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 info.matchingservice.fixture.ProfileElementConfig;
import info.matchingservice.dom.Profile.DemandOrSupply;
import info.matchingservice.dom.Profile.ProfileElementWidgetType;
/**
* Created by jodo on 14/06/15.
*/
public class ProfileElementChoicesForSupply extends ProfileElementChoiceAbstract {
@Override
protected void execute(ExecutionContext executionContext) {
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.TEXTAREA,
"PASSION_ELEMENT",
"createPassionElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.TAGS,
"BRANCHE_TAGS_ELEMENT",
"createBrancheTagElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.TAGS,
"QUALITY_TAGS_ELEMENT",
"createQualityTagElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.TAGS,
"WEEKDAY_TAGS_ELEMENT",
"createWeekdayTagElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.TEXT,
"LOCATION_ELEMENT",
"createLocationElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.NUMBER,
"HOURLY_RATE_ELEMENT",
"createHourlyRateElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.PREDICATE,
"USE_AGE_ELEMENT",
"createUseAgeElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.PREDICATE,
"USE_TIME_PERIOD_ELEMENT",
"createUseTimePeriodElement",
executionContext);
createElement(
DemandOrSupply.SUPPLY,
ProfileElementWidgetType.SELECT,
"EDUCATION_LEVEL",
"createEducationLevelElement",
executionContext);
}
}
| [
"johan@filternet.nl"
] | johan@filternet.nl |
c535a5d05cf5caac91fea015b3cff212ca84c084 | be0786ee1bd83275d57e08ce184b641614a0d42a | /sakura-cron/src/main/java/com/sakura/common/cron/utils/SchedulingRunnable.java | 15185ca499266171ef90f3d5d9b49d3ef16e0535 | [
"Apache-2.0"
] | permissive | RaitoRay/sakura-boot | 864b904997095029228aa5d277c99885364ded95 | 284bec12e567a08888bec5a0168a5d96f0a09fda | refs/heads/master | 2023-08-25T14:40:16.601007 | 2021-10-19T03:35:47 | 2021-10-19T03:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,924 | java | package com.sakura.common.cron.utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.Objects;
/**
* @auther yangfan
* @date 2021/10/18
* @describle Runnable接口实现类,被定时任务线程池调用,用来执行指定bean里面的方法。
*/
public class SchedulingRunnable implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class);
private String beanName;
private String methodName;
private String params;
public SchedulingRunnable(String beanName, String methodName) {
this(beanName, methodName, null);
}
public SchedulingRunnable(String beanName, String methodName, String params) {
this.beanName = beanName;
this.methodName = methodName;
this.params = params;
}
@Override
public void run() {
logger.info("定时任务开始执行 - bean:{},方法:{},参数:{}", beanName, methodName, params);
long startTime = System.currentTimeMillis();
try {
Object target = SpringContextUtils.getBean(beanName);
Method method = null;
if (StringUtils.isNotEmpty(params)) {
method = target.getClass().getDeclaredMethod(methodName, String.class);
} else {
method = target.getClass().getDeclaredMethod(methodName);
}
ReflectionUtils.makeAccessible(method);
if (StringUtils.isNotEmpty(params)) {
method.invoke(target, params);
} else {
method.invoke(target);
}
} catch (Exception ex) {
logger.error(String.format("定时任务执行异常 - bean:%s,方法:%s,参数:%s ", beanName, methodName, params), ex);
}
long times = System.currentTimeMillis() - startTime;
logger.info("定时任务执行结束 - bean:{},方法:{},参数:{},耗时:{} 毫秒", beanName, methodName, params, times);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SchedulingRunnable that = (SchedulingRunnable) o;
if (params == null) {
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
that.params == null;
}
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
params.equals(that.params);
}
@Override
public int hashCode() {
if (params == null) {
return Objects.hash(beanName, methodName);
}
return Objects.hash(beanName, methodName, params);
}
}
| [
"yangfan@sinvie.cn"
] | yangfan@sinvie.cn |
13ba47419b300115f80ddda2a173dec9b9e073ee | 46e9dd8a93857f378a91201f0adbdf580cecc252 | /src/java/com/shadley000/alarms/pages/nov/PageDrawworksLimitChecks.java | 9c4635b19fa2e8a784d6578564a8e892c5feb54c | [] | no_license | Shadley000/A4 | bddcdf0ad29107bdbd82820af139a87eda1b9590 | d67599e5352b798784fb2a82c5360f2d6337fcc7 | refs/heads/master | 2021-05-14T02:33:37.418555 | 2018-02-03T03:52:56 | 2018-02-03T03:52:56 | 116,596,900 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,672 | java | package com.shadley000.alarms.pages.nov;
import com.shadley000.alarms.beans.AlarmRecordBean;
import com.shadley000.alarms.beans.AlarmTypeBean;
import com.shadley000.alarms.beans.LabelsBean;
import com.shadley000.alarms.ReportBean;
import com.shadley000.alarms.db.AlarmsDB;
import com.shadley000.alarms.UserSessionBean;
import com.shadley000.alarms.pages.Page;
import com.shadley000.histogram.Histogram2D;
import com.shadley000.histogram.TimeBin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
public class PageDrawworksLimitChecks extends Page
{
public PageDrawworksLimitChecks()
{
}
public ReportBean build(Connection connection, HttpServletRequest request) throws Exception
{
UserSessionBean userBean = (UserSessionBean) request.getSession().getAttribute(PARAM_USERBEAN);
Histogram2D histogram = new Histogram2D();
PreparedStatement stmt = AlarmsDB.getDrawworksAlarms(connection, userBean);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
AlarmRecordBean record = new AlarmRecordBean(rs);
AlarmTypeBean alarmType = new AlarmTypeBean(rs);
String columnName = TimeBin.findBin(record.getAlarmTime(), TimeBin.DAY);
if (record.getDescription().contains("Floor") || record.getDescription().contains("Crown"))
{
if (!record.getDescription().contains("Brakes released"))
{
histogram.increment(columnName, alarmType, 1);
}
} else if (alarmType.getDescription().contains("Brake"))
{
AlarmTypeBean typeMachineStop = new AlarmTypeBean();
typeMachineStop.setSystem(alarmType.getSystem());
typeMachineStop.setSubSystem(alarmType.getSubSystem());
typeMachineStop.setMessageType(alarmType.getMessageType());
typeMachineStop.setPriority(alarmType.getPriority());
typeMachineStop.setTagName(alarmType.getSubSystem());
typeMachineStop.setDescription("Total Brake Alarms");
histogram.increment(columnName, typeMachineStop, 1);
}
}
rs.close();
stmt.close();
ReportBean reportBean = new ReportBean("/DrawworksLimitChecks.jsp", getName(userBean.getLabelsBean()));
reportBean.setDataObject(ReportBean.DO_ALARM_TYPE_HISTOGRAM, histogram);
return reportBean;
}
public String getName(LabelsBean labelsBean)
{
return labelsBean.getLimit_checks();
}
}
| [
"stephenjhadley@gmail.com"
] | stephenjhadley@gmail.com |
f9a3d7a47488556886ebae4625b59618c041553e | ee3a9ed107d2507530fc985ef7a86d0818cc7339 | /src/main/java/com/assign/word/word/Counter.java | c16e85a4fe51c82faff846b2a19db9e09a38056f | [] | no_license | praveenr78/word-counter-app | e1dd33d5d6d1a3fd4a707a20b55d5bdf28b659d7 | a267292796f71fa68cdd6c4af858e9aa288015ca | refs/heads/master | 2021-01-16T12:09:12.032070 | 2020-02-26T21:34:26 | 2020-02-26T21:34:26 | 243,114,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 906 | java | package com.assign.word.word;
import java.util.Optional;
/**
*
*/
public class Counter {
private final BST bst;
private final Translator translator;
private final Validator validator;
/**
* @param bst
*/
public Counter(final BST bst, final Translator translator, final Validator validator) {
this.bst = bst;
this.translator = translator;
this.validator = validator;
}
/**
* @param word
* @throws Exception
*/
public void addWord(final String word) throws ValidationException {
validator.validate(word);
bst.add(translator.translate(word));
}
/**
* @param word
* @return
*/
public long getCount(final String word) {
Optional<Node> wordNode = Optional.ofNullable(bst.searchByWord(word));
return wordNode.isPresent() ? wordNode.get().getCount() : 0;
}
}
| [
"praveenr.raju@gmail.com"
] | praveenr.raju@gmail.com |
f8c964c3a3d5ab68f6e9bf6a13e6a4c1321bb974 | 24eeeae032a34ed7195c336a0f7d396330272690 | /app/src/main/java/com/example/medic_app/Registro.java | b9f0de9cade4b2d879676d7c65fd694da9d28005 | [] | no_license | johangout/Medic-App | c89f99bd09c0e44c03bb87b0a5a6041f4471b4ed | d5867ad96c00e3312ba8dbc1446aca7b0a3c8533 | refs/heads/master | 2022-11-10T23:34:40.164312 | 2020-07-03T06:02:11 | 2020-07-03T06:02:11 | 276,820,339 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,847 | java | package com.example.medic_app;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.text.BreakIterator;
import java.text.DateFormat;
public class Registro extends AppCompatActivity {
public EditText ide, nombre, apellido, Especi, celular;
public Button button1;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registro);
ide = (EditText) findViewById(R.id.ide1);
nombre = (EditText) findViewById(R.id.nombre1);
apellido = (EditText) findViewById(R.id.apellido1);
Especi = (EditText) findViewById(R.id.Especi1);
celular = (EditText) findViewById(R.id.celular1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String identificacion = ide.getText().toString();
String nomb = nombre.getText().toString();
String ape = apellido.getText().toString();
String espe = Especi.getText().toString();
String cel = celular.getText().toString();
Intent DATO =new Intent(getApplicationContext(),OKRegistro.class);
DATO.putExtra("ide",identificacion);
DATO.putExtra("nomb",nomb);
DATO.putExtra("ape",ape);
DATO.putExtra("espe",espe);
DATO.putExtra("cel",cel);
startActivity(DATO);
}
});
}
}
| [
"johangout@hotmail.com"
] | johangout@hotmail.com |
6775bdf450ef8bb791c554025fbb1ca79d3d340f | a1375add007b782e112a0438ed7405e9acdc78fe | /HibernatePro/src/com/i91/relationShipTest/OneToManyDelete.java | 9ba4f84e5acefa788add920aa621da812535fbb9 | [] | no_license | yuwraj/FirstProjectTest | 0a46a229c6d4df0c3cd69c8b634eb8fc6703fa0f | 5cb5fc05aad36230766c1554c2bca4f4ebd13600 | refs/heads/master | 2022-11-24T02:15:58.543885 | 2020-08-01T06:59:31 | 2020-08-01T06:59:31 | 172,288,273 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 768 | java | package com.i91.relationShipTest;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.i91.beans.Answer;
import com.i91.beans.Question;
import com.i91.beans.oneToOnePkg.Address;
public class OneToManyDelete {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure().addAnnotatedClass(Question.class).addAnnotatedClass(Answer.class);
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Question q = session.get(Question.class, 9);
System.out.println(q.getFullQuestion());
List<Answer> ans = q.getAnswer();
System.out.println(ans.get(0).getActualAnswer());
session.delete(q);
}
}
| [
"yuwrajpuri@yuwrajs-air"
] | yuwrajpuri@yuwrajs-air |
9f20f10ec6362dfa2ccd36eb5564d6345354de70 | 83e9f9580cfc4fa028ed24ad2693a0c305496d15 | /src/examples/Example1.java | f9bcf25c76390c3dc09551ed32fe8e4012928649 | [] | no_license | ChungChainz/Chapter3-Java | 9bad62445ead0afaedbd450d8eb3e53bc5397d84 | 9127bbbe41648fe561c9d583b00e07fbe1947494 | refs/heads/master | 2020-07-22T20:32:24.891717 | 2019-09-13T14:25:00 | 2019-09-13T14:25:00 | 207,319,081 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 412 | java | package examples;
public class Example1
{
public static void main(String[] args)
{
displayMessage();
}
public static void displayMessage()
{
displayAddress();
System.out.println("Hello World");
}
public static void displayAddress()
{
System.out.println("3505 West Locust Street");
System.out.println("Davenport, Iowa 52804");
}
}
| [
"chrismolis12@gmail.com"
] | chrismolis12@gmail.com |
5e38ea74b0f2a00661aafd65f960a326fa1d9e84 | f5412eb0a5e0a1700dc1639d80dd5762bf51a7da | /Pascal_Triangle/PatternPascal.java | 8851813a7acf230c7876430e57aaa14617bff6d4 | [] | no_license | yagnikmer/java-programs | cf6f5960ee9fc562418d749644de0fec678e0163 | f91e93c5fe432fbd2e7ddb5fde2e5fcfd59e5f1b | refs/heads/master | 2020-04-13T08:02:00.027404 | 2018-12-30T22:25:51 | 2018-12-30T22:25:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 667 | java | class PatternPascal
{
public static void main(String[] args)
{
int totalRows =6;
int element=1;
for (int row=0;row<totalRows;row++)
{
for (int space=0;space < totalRows-row; space++)
{
System.out.print(" "); // 2 space
}
for (int value=0; value<=row; value++)
{
if(value == 0 || row == 0)
element=1;
else
element = element * (row - value + 1) / value;
System.out.printf("%4d",element);
}
System.out.println();
}
}
}
| [
"yagnikmer@gmail.com"
] | yagnikmer@gmail.com |
eb9c4341537ab5375271e6b9aab4e0c35894fc29 | 034761b9e125b96e292991165ac89b2de3ecb788 | /src/main/java/cn/edu/sxau/dormitorymanage/utils/StringUtil.java | 6686f204a3873e5c369ed804a2443bc6ac6c3ccb | [] | no_license | 786991884/dormitorymanagesystem | 0723ae5bae6dcf17668657c785fe4653854c48fe | 54e42b576da23917ccdbc2dddc73de3145d8e30f | refs/heads/master | 2021-01-20T22:34:35.094146 | 2017-03-09T06:03:46 | 2017-03-09T06:03:46 | 62,532,680 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 44,136 | java | package cn.edu.sxau.dormitorymanage.utils;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
/**
* String工具类.
*/
public class StringUtil {
/**
* 私有构造方法,防止类的实例化,因为工具类不需要实例化。
*/
private StringUtil() {
}
private static final int INDEX_NOT_FOUND = -1;
private static final String EMPTY = "";
private static final int PAD_LIMIT = 8192;
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 功能:将半角的符号转换成全角符号.(即英文字符转中文字符)
*
* @param str
* 源字符串
* @return String
*/
public static String changeToFull(String str) {
String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?";
String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "︿", "&", "*", "(", ")", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "-", "_", "=", "+", "\", "|", "【", "】", ";", ":", "'",
"\"", ",", "〈", "。", "〉", "/", "?" };
String result = "";
for (int i = 0; i < str.length(); i++) {
int pos = source.indexOf(str.charAt(i));
if (pos != -1) {
result += decode[pos];
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 功能:cs串中是否一个都不包含字符数组searchChars中的字符。
*
* @param cs
* 字符串
* @param searchChars
* 字符数组
* @return boolean 都不包含返回true,否则返回false。
*/
public static boolean containsNone(CharSequence cs, char... searchChars) {
if (cs == null || searchChars == null) {
return true;
}
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like
// String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* 编码为Unicode,格式 '\u0020'.
*
*
* <pre>
* CharUtils.unicodeEscaped(' ') = "\u0020"
* CharUtils.unicodeEscaped('A') = "\u0041"
* </pre>
*
* @param ch
* 源字符串
* @return 转码后的字符串
*/
public static String unicodeEscaped(char ch) {
if (ch < 0x10) {
return "\\u000" + Integer.toHexString(ch);
} else if (ch < 0x100) {
return "\\u00" + Integer.toHexString(ch);
} else if (ch < 0x1000) {
return "\\u0" + Integer.toHexString(ch);
}
return "\\u" + Integer.toHexString(ch);
}
/**
* 进行tostring操作,如果传入的是null,返回空字符串。
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @param obj
* 源
* @return String
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
/**
* 进行tostring操作,如果传入的是null,返回指定的默认值。
*
* <pre>
* ObjectUtils.toString(null, null) = null
* ObjectUtils.toString(null, "null") = "null"
* ObjectUtils.toString("", "null") = ""
* ObjectUtils.toString("bat", "null") = "bat"
* ObjectUtils.toString(Boolean.TRUE, "null") = "true"
* </pre>
*
* @param obj
* 源
* @param nullStr
* 如果obj为null时返回这个指定值
* @return String
*/
public static String toString(Object obj, String nullStr) {
return obj == null ? nullStr : obj.toString();
}
/**
* 只从源字符串中移除指定开头子字符串.
*
* <pre>
* StringUtil.removeStart(null, *) = null
* StringUtil.removeStart("", *) = ""
* StringUtil.removeStart(*, null) = *
* StringUtil.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtil.removeStart("domain.com", "www.") = "domain.com"
* StringUtil.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtil.removeStart("abc", "") = "abc"
* </pre>
*
* @param str
* 源字符串
* @param remove
* 将要被移除的子字符串
* @return String
*/
public static String removeStart(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* 只从源字符串中移除指定结尾的子字符串.
*
* <pre>
* StringUtil.removeEnd(null, *) = null
* StringUtil.removeEnd("", *) = ""
* StringUtil.removeEnd(*, null) = *
* StringUtil.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtil.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtil.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtil.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str
* 源字符串
* @param remove
* 将要被移除的子字符串
* @return String
*/
public static String removeEnd(String str, String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* 将一个字符串重复N次
*
* <pre>
* StringUtil.repeat(null, 2) = null
* StringUtil.repeat("", 0) = ""
* StringUtil.repeat("", 2) = ""
* StringUtil.repeat("a", 3) = "aaa"
* StringUtil.repeat("ab", 2) = "abab"
* StringUtil.repeat("a", -2) = ""
* </pre>
*
* @param str
* 源字符串
* @param repeat
* 重复的次数
* @return String
*/
public static String repeat(String str, int repeat) {
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1:
return repeat(str.charAt(0), repeat);
case 2:
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default:
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* 将一个字符串重复N次,并且中间加上指定的分隔符
*
* <pre>
* StringUtil.repeat(null, null, 2) = null
* StringUtil.repeat(null, "x", 2) = null
* StringUtil.repeat("", null, 0) = ""
* StringUtil.repeat("", "", 2) = ""
* StringUtil.repeat("", "x", 3) = "xxx"
* StringUtil.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str
* 源字符串
* @param separator
* 分隔符
* @param repeat
* 重复次数
* @return String
*/
public static String repeat(String str, String separator, int repeat) {
if (str == null || separator == null) {
return repeat(str, repeat);
} else {
// given that repeat(String, int) is quite optimized, better to rely
// on it than try and splice this into it
String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
}
/**
* 将某个字符重复N次.
*
* @param ch
* 某个字符
* @param repeat
* 重复次数
* @return String
*/
public static String repeat(char ch, int repeat) {
char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
/**
* 字符串长度达不到指定长度时,在字符串右边补指定的字符.
*
* <pre>
* StringUtil.rightPad(null, *, *) = null
* StringUtil.rightPad("", 3, 'z') = "zzz"
* StringUtil.rightPad("bat", 3, 'z') = "bat"
* StringUtil.rightPad("bat", 5, 'z') = "batzz"
* StringUtil.rightPad("bat", 1, 'z') = "bat"
* StringUtil.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str
* 源字符串
* @param size
* 指定的长度
* @param padChar
* 进行补充的字符
* @return String
*/
public static String rightPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(repeat(padChar, pads));
}
/**
* 扩大字符串长度,从左边补充指定字符
*
* <pre>
* StringUtil.rightPad(null, *, *) = null
* StringUtil.rightPad("", 3, "z") = "zzz"
* StringUtil.rightPad("bat", 3, "yz") = "bat"
* StringUtil.rightPad("bat", 5, "yz") = "batyz"
* StringUtil.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtil.rightPad("bat", 1, "yz") = "bat"
* StringUtil.rightPad("bat", -1, "yz") = "bat"
* StringUtil.rightPad("bat", 5, null) = "bat "
* StringUtil.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str
* 源字符串
* @param size
* 扩大后的长度
* @param padStr
* 在右边补充的字符串
* @return String
*/
public static String rightPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
/**
* 扩大字符串长度,从左边补充空格
*
* <pre>
* StringUtil.leftPad(null, *) = null
* StringUtil.leftPad("", 3) = " "
* StringUtil.leftPad("bat", 3) = "bat"
* StringUtil.leftPad("bat", 5) = " bat"
* StringUtil.leftPad("bat", 1) = "bat"
* StringUtil.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str
* 源字符串
* @param size
* 扩大后的长度
* @return String
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
/**
* 扩大字符串长度,从左边补充指定的字符
*
* <pre>
* StringUtil.leftPad(null, *, *) = null
* StringUtil.leftPad("", 3, 'z') = "zzz"
* StringUtil.leftPad("bat", 3, 'z') = "bat"
* StringUtil.leftPad("bat", 5, 'z') = "zzbat"
* StringUtil.leftPad("bat", 1, 'z') = "bat"
* StringUtil.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str
* 源字符串
* @param size
* 扩大后的长度
* @param padStr
* 补充的字符
* @return String
*/
public static String leftPad(String str, int size, char padChar) {
if (str == null) {
return null;
}
int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return repeat(padChar, pads).concat(str);
}
/**
* 扩大字符串长度,从左边补充指定的字符
*
* <pre>
* StringUtil.leftPad(null, *, *) = null
* StringUtil.leftPad("", 3, "z") = "zzz"
* StringUtil.leftPad("bat", 3, "yz") = "bat"
* StringUtil.leftPad("bat", 5, "yz") = "yzbat"
* StringUtil.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtil.leftPad("bat", 1, "yz") = "bat"
* StringUtil.leftPad("bat", -1, "yz") = "bat"
* StringUtil.leftPad("bat", 5, null) = " bat"
* StringUtil.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str
* 源字符串
* @param size
* 扩大后的长度
* @param padStr
* 补充的字符串
* @return String
*/
public static String leftPad(String str, int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* 扩大字符串长度并将现在的字符串居中,被扩大部分用空格填充。
*
* <pre>
* StringUtil.center(null, *) = null
* StringUtil.center("", 4) = " "
* StringUtil.center("ab", -1) = "ab"
* StringUtil.center("ab", 4) = " ab "
* StringUtil.center("abcd", 2) = "abcd"
* StringUtil.center("a", 4) = " a "
* </pre>
*
* @param str
* 源字符串
* @param size
* 扩大后的长度
* @return String
*/
public static String center(String str, int size) {
return center(str, size, ' ');
}
/**
* 将字符串长度修改为指定长度,并进行居中显示。
*
* <pre>
* StringUtil.center(null, *, *) = null
* StringUtil.center("", 4, ' ') = " "
* StringUtil.center("ab", -1, ' ') = "ab"
* StringUtil.center("ab", 4, ' ') = " ab"
* StringUtil.center("abcd", 2, ' ') = "abcd"
* StringUtil.center("a", 4, ' ') = " a "
* StringUtil.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str
* 源字符串
* @param size
* 指定的长度
* @param padStr
* 长度不够时补充的字符串
* @return String
* @throws IllegalArgumentException
* 如果被补充字符串为 null或者 empty
*/
public static String center(String str, int size, char padChar) {
if (str == null || size <= 0) {
return str;
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* 将字符串长度修改为指定长度,并进行居中显示。
*
* <pre>
* StringUtil.center(null, *, *) = null
* StringUtil.center("", 4, " ") = " "
* StringUtil.center("ab", -1, " ") = "ab"
* StringUtil.center("ab", 4, " ") = " ab"
* StringUtil.center("abcd", 2, " ") = "abcd"
* StringUtil.center("a", 4, " ") = " a "
* StringUtil.center("a", 4, "yz") = "yayz"
* StringUtil.center("abc", 7, null) = " abc "
* StringUtil.center("abc", 7, "") = " abc "
* </pre>
*
* @param str
* 源字符串
* @param size
* 指定的长度
* @param padStr
* 长度不够时补充的字符串
* @return String
* @throws IllegalArgumentException
* 如果被补充字符串为 null或者 empty
*/
public static String center(String str, int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = " ";
}
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
/**
* 检查字符串是否全部为小写.
*
* <pre>
* StringUtil.isAllLowerCase(null) = false
* StringUtil.isAllLowerCase("") = false
* StringUtil.isAllLowerCase(" ") = false
* StringUtil.isAllLowerCase("abc") = true
* StringUtil.isAllLowerCase("abC") = false
* </pre>
*
* @param cs
* 源字符串
* @return String
*/
public static boolean isAllLowerCase(String cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLowerCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* 检查是否都是大写.
*
* <pre>
* StringUtil.isAllUpperCase(null) = false
* StringUtil.isAllUpperCase("") = false
* StringUtil.isAllUpperCase(" ") = false
* StringUtil.isAllUpperCase("ABC") = true
* StringUtil.isAllUpperCase("aBC") = false
* </pre>
*
* @param cs
* 源字符串
* @return String
*/
public static boolean isAllUpperCase(String cs) {
if (cs == null || StringUtil.isEmpty(cs)) {
return false;
}
int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isUpperCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* 反转字符串.
*
* <pre>
* StringUtil.reverse(null) = null
* StringUtil.reverse("") = ""
* StringUtil.reverse("bat") = "tab"
* </pre>
*
* @param str
* 源字符串
* @return String
*/
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* 字符串达不到一定长度时在右边补空白.
*
* <pre>
* StringUtil.rightPad(null, *) = null
* StringUtil.rightPad("", 3) = " "
* StringUtil.rightPad("bat", 3) = "bat"
* StringUtil.rightPad("bat", 5) = "bat "
* StringUtil.rightPad("bat", 1) = "bat"
* StringUtil.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str
* 源字符串
* @param size
* 指定的长度
* @return String
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
/**
* 从右边截取字符串.</p>
*
* <pre>
* StringUtil.right(null, *) = null
* StringUtil.right(*, -ve) = ""
* StringUtil.right("", *) = ""
* StringUtil.right("abc", 0) = ""
* StringUtil.right("abc", 2) = "bc"
* StringUtil.right("abc", 4) = "abc"
* </pre>
*
* @param str
* 源字符串
* @param len
* 长度
* @return String
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* 截取一个字符串的前几个.
*
* <pre>
* StringUtil.left(null, *) = null
* StringUtil.left(*, -ve) = ""
* StringUtil.left("", *) = ""
* StringUtil.left("abc", 0) = ""
* StringUtil.left("abc", 2) = "ab"
* StringUtil.left("abc", 4) = "abc"
* </pre>
*
* @param str
* 源字符串
* @param len
* 截取的长度
* @return the String
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* 得到tag字符串中间的子字符串,只返回第一个匹配项。
*
* <pre>
* StringUtil.substringBetween(null, *) = null
* StringUtil.substringBetween("", "") = ""
* StringUtil.substringBetween("", "tag") = null
* StringUtil.substringBetween("tagabctag", null) = null
* StringUtil.substringBetween("tagabctag", "") = ""
* StringUtil.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str
* 源字符串。
* @param tag
* 标识字符串。
* @return String 子字符串, 如果没有符合要求的,返回{@code null}。
*/
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag);
}
/**
* 得到两个字符串中间的子字符串,只返回第一个匹配项。
*
* <pre>
* StringUtil.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtil.substringBetween(null, *, *) = null
* StringUtil.substringBetween(*, null, *) = null
* StringUtil.substringBetween(*, *, null) = null
* StringUtil.substringBetween("", "", "") = ""
* StringUtil.substringBetween("", "", "]") = null
* StringUtil.substringBetween("", "[", "]") = null
* StringUtil.substringBetween("yabcz", "", "") = ""
* StringUtil.substringBetween("yabcz", "y", "z") = "abc"
* StringUtil.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str
* 源字符串
* @param open
* 起字符串。
* @param close
* 末字符串。
* @return String 子字符串, 如果没有符合要求的,返回{@code null}。
*/
public static String substringBetween(String str, String open, String close) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* 得到两个字符串中间的子字符串,所有匹配项组合为数组并返回。
*
* <pre>
* StringUtil.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtil.substringsBetween(null, *, *) = null
* StringUtil.substringsBetween(*, null, *) = null
* StringUtil.substringsBetween(*, *, null) = null
* StringUtil.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str
* 源字符串
* @param open
* 起字符串。
* @param close
* 末字符串。
* @return String 子字符串数组, 如果没有符合要求的,返回{@code null}。
*/
public static String[] substringsBetween(String str, String open, String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
int strLen = str.length();
if (strLen == 0) {
return new String[0];
}
int closeLen = close.length();
int openLen = open.length();
List<String> list = new ArrayList<String>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String[list.size()]);
}
/**
* 功能:切换字符串中的所有字母大小写。<br/>
*
* <pre>
* StringUtil.swapCase(null) = null
* StringUtil.swapCase("") = ""
* StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
*
* @param str
* 源字符串
* @return String
*/
public static String swapCase(String str) {
if (StringUtil.isEmpty(str)) {
return str;
}
char[] buffer = str.toCharArray();
boolean whitespace = true;
for (int i = 0; i < buffer.length; i++) {
char ch = buffer[i];
if (Character.isUpperCase(ch)) {
buffer[i] = Character.toLowerCase(ch);
whitespace = false;
} else if (Character.isTitleCase(ch)) {
buffer[i] = Character.toLowerCase(ch);
whitespace = false;
} else if (Character.isLowerCase(ch)) {
if (whitespace) {
buffer[i] = Character.toTitleCase(ch);
whitespace = false;
} else {
buffer[i] = Character.toUpperCase(ch);
}
} else {
whitespace = Character.isWhitespace(ch);
}
}
return new String(buffer);
}
/**
* 功能:截取出最后一个标志位之后的字符串.<br/>
* 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
* 如果expr长度为0,直接返回sourceStr。<br/>
* 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
*
* @param sourceStr
* 被截取的字符串
* @param expr
* 分隔符
* @return String
*/
public static String substringAfterLast(String sourceStr, String expr) {
if (isEmpty(sourceStr) || expr == null) {
return sourceStr;
}
if (expr.length() == 0) {
return sourceStr;
}
int pos = sourceStr.lastIndexOf(expr);
if (pos == -1) {
return sourceStr;
}
return sourceStr.substring(pos + expr.length());
}
/**
* 功能:截取出最后一个标志位之前的字符串.<br/>
* 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
* 如果expr长度为0,直接返回sourceStr。<br/>
* 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
*
* @param sourceStr
* 被截取的字符串
* @param expr
* 分隔符
* @return String
*/
public static String substringBeforeLast(String sourceStr, String expr) {
if (isEmpty(sourceStr) || expr == null) {
return sourceStr;
}
if (expr.length() == 0) {
return sourceStr;
}
int pos = sourceStr.lastIndexOf(expr);
if (pos == -1) {
return sourceStr;
}
return sourceStr.substring(0, pos);
}
/**
* 功能:截取出第一个标志位之后的字符串.<br/>
* 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
* 如果expr长度为0,直接返回sourceStr。<br/>
* 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
*
* @param sourceStr
* 被截取的字符串
* @param expr
* 分隔符
* @return String
*/
public static String substringAfter(String sourceStr, String expr) {
if (isEmpty(sourceStr) || expr == null) {
return sourceStr;
}
if (expr.length() == 0) {
return sourceStr;
}
int pos = sourceStr.indexOf(expr);
if (pos == -1) {
return sourceStr;
}
return sourceStr.substring(pos + expr.length());
}
/**
* 功能:截取出第一个标志位之前的字符串.<br/>
* 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
* 如果expr长度为0,直接返回sourceStr。<br/>
* 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
* 如果expr在sourceStr中存在不止一个,以第一个位置为准。
*
* @param sourceStr
* 被截取的字符串
* @param expr
* 分隔符
* @return String
*/
public static String substringBefore(String sourceStr, String expr) {
if (isEmpty(sourceStr) || expr == null) {
return sourceStr;
}
if (expr.length() == 0) {
return sourceStr;
}
int pos = sourceStr.indexOf(expr);
if (pos == -1) {
return sourceStr;
}
return sourceStr.substring(0, pos);
}
/**
* 功能:检查这个字符串是不是空字符串。<br/>
* 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。
*
* @param chkStr
* 被检查的字符串
* @return boolean
*/
public static boolean isEmpty(String chkStr) {
if (chkStr == null) {
return true;
} else {
return "".equals(chkStr.trim()) ? true : false;
}
}
/**
* 如果字符串没有超过最长显示长度返回原字符串,否则从开头截取指定长度并加...返回。
*
* @param str
* 原字符串
* @param length
* 字符串最长显示的长度
* @return 转换后的字符串
*/
public static String trimString(String str, int length) {
if (str == null) {
return "";
} else if (str.length() > length) {
return str.substring(0, length - 3) + "...";
} else {
return str;
}
}
/**
* 替换字符串
*
* @param from
* String 原始字符串
* @param to
* String 目标字符串
* @param source
* String 母字符串
* @return String 替换后的字符串
*/
public static String replace(String from, String to, String source) {
if (source == null || from == null || to == null)
return null;
StringBuffer bf = new StringBuffer("");
int index = -1;
while ((index = source.indexOf(from)) != -1) {
bf.append(source.substring(0, index) + to);
source = source.substring(index + from.length());
index = source.indexOf(from);
}
bf.append(source);
return bf.toString();
}
/**
* 替换字符串,能能够在HTML页面上直接显示(替换双引号和小于号)
*
* @param str
* String 原始字符串
* @return String 替换后的字符串
*/
public static String htmlencode(String str) {
if (str == null) {
return null;
}
return replace("\"", """, replace("<", "<", str));
}
/**
* 替换字符串,将被编码的转换成原始码(替换成双引号和小于号)
*
* @param str
* String
* @return String
*/
public static String htmldecode(String str) {
if (str == null) {
return null;
}
return replace(""", "\"", replace("<", "<", str));
}
private static final String _BR = "<br/>";
/**
* 在页面上直接显示文本内容,替换小于号,空格,回车,TAB
*
* @param str
* String 原始字符串
* @return String 替换后的字符串
*/
public static String htmlshow(String str) {
if (str == null) {
return null;
}
str = replace("<", "<", str);
str = replace(" ", " ", str);
str = replace("\r\n", _BR, str);
str = replace("\n", _BR, str);
str = replace("\t", " ", str);
return str;
}
/**
* 返回指定字节长度的字符串
*
* @param str
* String 字符串
* @param length
* int 指定长度
* @return String 返回的字符串
*/
public static String toLength(String str, int length) {
if (str == null) {
return null;
}
if (length <= 0) {
return "";
}
try {
if (str.getBytes("GBK").length <= length) {
return str;
}
} catch (Exception ex) {
}
StringBuffer buff = new StringBuffer();
int index = 0;
char c;
length -= 3;
while (length > 0) {
c = str.charAt(index);
if (c < 128) {
length--;
} else {
length--;
length--;
}
buff.append(c);
index++;
}
buff.append("...");
return buff.toString();
}
/**
* 判断是不是合法字符 c 要判断的字符
*/
public static boolean isLetter(String c) {
boolean result = false;
if (c == null || c.length() < 0) {
return false;
}
// a-z
if (c.compareToIgnoreCase("a") >= 0 && c.compareToIgnoreCase("z") <= 0) {
return true;
}
// 0-9
if (c.compareToIgnoreCase("0") >= 0 && c.compareToIgnoreCase("9") <= 0) {
return true;
}
// . - _
if (c.equals(".") || c.equals("-") || c.equals("_")) {
return true;
}
return result;
}
/**
*
* @param source
* 源字符
* @param charset
* 源字符编码
* @return
*/
public static String decodeUTF8(String source, String charset) {
try {
return new String(source.getBytes(charset), "UTF-8");
} catch (Exception E) {
}
return source;
}
/**
* 人民币转成大写
*
* @param value
* @return String
*/
public static String hangeToBig(double value) {
char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
char[] vunit = { '万', '亿' }; // 段名表示
char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
long midVal = (long) (value * 100); // 转化成整形
String valStr = String.valueOf(midVal); // 转化成字符串
String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
String rail = valStr.substring(valStr.length() - 2); // 取小数部分
String prefix = ""; // 整数部分转化的结果
String suffix = ""; // 小数部分转化的结果
// 处理小数点后面的数
if (rail.equals("00")) { // 如果小数部分为0
suffix = "整";
} else {
suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
}
// 处理小数点前面的数
char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
char zero = '0'; // 标志'0'表示出现过0
byte zeroSerNum = 0; // 连续出现0的次数
for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
int idx = (chDig.length - i - 1) % 4; // 取段内位置
int vidx = (chDig.length - i - 1) / 4; // 取段位置
if (chDig[i] == '0') { // 如果当前字符是0
zeroSerNum++; // 连续0次数递增
if (zero == '0') { // 标志
zero = digit[0];
} else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
prefix += vunit[vidx - 1];
zero = '0';
}
continue;
}
zeroSerNum = 0; // 连续0次数清零
if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
prefix += zero;
zero = '0';
}
prefix += digit[chDig[i] - '0']; // 转化该数字表示
if (idx > 0)
prefix += hunit[idx - 1];
if (idx == 0 && vidx > 0) {
prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
}
}
if (prefix.length() > 0)
prefix += '圆'; // 如果整数部分存在,则有圆的字样
return prefix + suffix; // 返回正确表示
}
// 过滤特殊字符
public static String encoding(String src) {
if (src == null)
return "";
StringBuilder result = new StringBuilder();
if (src != null) {
src = src.trim();
for (int pos = 0; pos < src.length(); pos++) {
switch (src.charAt(pos)) {
case '\"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\'':
result.append("'");
break;
case '&':
result.append("&");
break;
case '%':
result.append("&pc;");
break;
case '_':
result.append("&ul;");
break;
case '#':
result.append("&shap;");
break;
case '?':
result.append("&ques;");
break;
default:
result.append(src.charAt(pos));
break;
}
}
}
return result.toString();
}
// 反过滤特殊字符
public static String decoding(String src) {
if (src == null)
return "";
String result = src;
result = result.replace(""", "\"").replace("'", "\'");
result = result.replace("<", "<").replace(">", ">");
result = result.replace("&", "&");
result = result.replace("&pc;", "%").replace("&ul", "_");
result = result.replace("&shap;", "#").replace("&ques", "?");
return result;
}
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static byte[] getBytes(String str) {
if (str != null) {
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
} else {
return null;
}
}
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static String toString(byte[] bytes) {
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
/**
* 是否包含字符串
*
* @param str
* 验证字符串
* @param strs
* 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(StringUtils.trim(s))) {
return true;
}
}
}
return false;
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (StringUtils.isBlank(html)) {
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param html
* @return
*/
public static String replaceMobileHtml(String html) {
if (html == null) {
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param txt
* @return
*/
public static String toHtml(String txt) {
if (txt == null) {
return "";
}
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " ");
}
/**
* 缩略字符串(不区分中英文字符)
*
* @param str
* 目标字符串
* @param length
* 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
}
StringBuffer result = new StringBuffer();
int n = 0;
char temp;
boolean isCode = false; // 是不是HTML代码
boolean isHTML = false; // 是不是HTML特殊字符,如
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (n <= length - 3) {
result.append(temp);
} else {
result.append("...");
break;
}
}
// 取出截取字符串中的HTML标记
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
// 去掉不需要结素标记的HTML标记
temp_result = temp_result.replaceAll("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", "");
// 去掉成对的HTML标记
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
// 用正则表达式取出标记
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List<String> endHTML = Lists.newArrayList();
while (m.find()) {
endHTML.add(m.group(1));
}
// 补全不成对的HTML标记
for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("</");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val) {
if (val == null) {
return 0D;
}
try {
return Double.valueOf(StringUtils.trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(Object val) {
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val) {
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val) {
return toLong(val).intValue();
}
/**
* 获得用户远程地址
*/
public static String getRemoteAddr(HttpServletRequest request) {
String remoteAddr = request.getHeader("X-Real-IP");
if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("X-Forwarded-For");
} else if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("Proxy-Client-IP");
} else if (StringUtils.isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
*
* @return toCamelCase("hello_world") == "helloWorld" toCapitalizeCamelCase("hello_world") == "HelloWorld" toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 如果不为空,则设置值
*
* @param target
* @param source
*/
public static void setValueIfNotBlank(String target, String source) {
if (StringUtils.isNotBlank(source)) {
target = source;
}
}
/**
* 转换为JS获取对象值,生成三目运算返回结果
*
* @param objectString
* 对象串 例如:row.user.id 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = StringUtils.split(objectString, ".");
for (int i = 0; i < vals.length; i++) {
val.append("." + vals[i]);
result.append("!" + (val.substring(1)) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}
} | [
"xubh@mapbar.com"
] | xubh@mapbar.com |
53a1a2d2016ac873e291038d5db6f7e72e3a6d7a | d6783fe9bd4f4093d924a809c753b58fd8f1fc4c | /app_frame/src/main/java/com/zxz/www/base/utils/StringUtil.java | 50ced308a946171f01bb13b4601c96ce65c15a8c | [] | no_license | zengzhaoxing/app | 141c1295efed5ede81ae3f75cf02b24c44776077 | 594ac87549838385e7d7dd8f9b98be8fa5a9561e | refs/heads/master | 2020-03-17T20:56:03.991129 | 2019-03-27T09:46:09 | 2019-03-27T09:46:09 | 133,935,765 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,149 | java | package com.zxz.www.base.utils;
import android.content.Context;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
private static final String TAG = "StringUtils";
private static final String MAIL_REGEX = "^([a-z0-9A-Z]+[-_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
private StringUtil() {
throw new AssertionError();
}
public static String utf8Encode(String str) {
if (!isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
}
}
return str;
}
public static String formatInteger(int number) {
return String.format("%,d", number);
}
public static String formatFloat(float number) {
if (number == (int) (number)) return String.format("%,.0f", number);
return String.format("%,.2f", number);
}
public static String formatDouble(double number) {
if (number == (int) (number)) return String.format("%,.0f", number);
return String.format("%,.2f", number);
}
public static boolean isNumberOrLetter(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c)) {
return false;
}
}
return true;
}
public static boolean isValidEmail(String email) {
if (email == null || isEmpty(email) || email.length() > 30) {
return false;
} else if (email.contains("@") && email.contains(".")) {
Pattern pattern = Pattern.compile(MAIL_REGEX);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
} else {
return false;
}
}
public static boolean isValidatePhoneNumber(String phoneNumber) {
return phoneNumber != null && !isEmpty(phoneNumber) && isNumber(phoneNumber) && ((phoneNumber.length() == 11 && (phoneNumber.startsWith("13") || phoneNumber.startsWith("15") || phoneNumber.startsWith("18") || phoneNumber.startsWith("17")
|| phoneNumber.startsWith("14"))));
}
public static boolean isLengthBetween(String s, int from, int to) {
if (s == null) {
return false;
} else {
return s.length() > from && s.length() <= to;
}
}
public static boolean isEqual(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
} else if (s1 == null || s2 == null) {
return false;
} else {
return s1.equals(s2);
}
}
public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
public static boolean isEmpty(CharSequence str) {
return (str == null || str.length() == 0);
}
public static boolean isEquals(String actual, String expected) {
if (actual == null && expected == null) {
return true;
} else if (actual != null && expected != null) {
return actual.equals(expected);
}else{
return false;
}
}
public static int length(CharSequence str) {
return str == null ? 0 : str.length();
}
public static boolean isLetter(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetter(c)) {
return false;
}
}
return true;
}
public static boolean isNumber(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
public static boolean isIdCardNo(String idCardNO) {
boolean isID = false;
if (idCardNO == null){
return false;
}
int len = idCardNO.length();
if (len != 18) {
return false;
} else {
// 排除最后一位是:X的情况
for (int i = 0; i < len; i++) {
try {
isID = (idCardNO.charAt(i) + "").equalsIgnoreCase("X")|| Integer.parseInt("" + idCardNO.charAt(i)) > -1;
} catch (NumberFormatException e) {
return false;
}
}
}
return isID;
}
}
| [
"zengxianzi@yougola.com"
] | zengxianzi@yougola.com |
9adb42d8cbbe362689d8cb0dd1a6379fe32ef267 | 8bfb5a8b6aa67dd32ffa2a38b08b00d1ea6987bc | /src/main/java/com/financegeorgia/echosign/pojo/SecurityOptions.java | fd125e3be74ce06d061d06e41d434a6a4c0ee289 | [] | no_license | viplavfauzdar/tommy | f148d0ab97f3c6c36095a21b925ebfb972448b82 | 72f75cf5595df8c255ca0375b369c7d47c2ded4b | refs/heads/master | 2021-01-20T12:22:15.337659 | 2017-07-13T01:47:12 | 2017-07-13T01:47:12 | 28,530,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,936 | java |
package com.financegeorgia.echosign.pojo;
import com.google.gson.annotations.Expose;
public class SecurityOptions {
@Expose
private String passwordProtection;
@Expose
private String kbaProtection;
@Expose
private String webIdentityProtection;
@Expose
private String protectOpen;
@Expose
private String internalPassword;
@Expose
private String externalPassword;
@Expose
private String openPassword;
/**
*
* @return
* The passwordProtection
*/
public String getPasswordProtection() {
return passwordProtection;
}
/**
*
* @param passwordProtection
* The passwordProtection
*/
public void setPasswordProtection(String passwordProtection) {
this.passwordProtection = passwordProtection;
}
/**
*
* @return
* The kbaProtection
*/
public String getKbaProtection() {
return kbaProtection;
}
/**
*
* @param kbaProtection
* The kbaProtection
*/
public void setKbaProtection(String kbaProtection) {
this.kbaProtection = kbaProtection;
}
/**
*
* @return
* The webIdentityProtection
*/
public String getWebIdentityProtection() {
return webIdentityProtection;
}
/**
*
* @param webIdentityProtection
* The webIdentityProtection
*/
public void setWebIdentityProtection(String webIdentityProtection) {
this.webIdentityProtection = webIdentityProtection;
}
/**
*
* @return
* The protectOpen
*/
public String getProtectOpen() {
return protectOpen;
}
/**
*
* @param protectOpen
* The protectOpen
*/
public void setProtectOpen(String protectOpen) {
this.protectOpen = protectOpen;
}
/**
*
* @return
* The internalPassword
*/
public String getInternalPassword() {
return internalPassword;
}
/**
*
* @param internalPassword
* The internalPassword
*/
public void setInternalPassword(String internalPassword) {
this.internalPassword = internalPassword;
}
/**
*
* @return
* The externalPassword
*/
public String getExternalPassword() {
return externalPassword;
}
/**
*
* @param externalPassword
* The externalPassword
*/
public void setExternalPassword(String externalPassword) {
this.externalPassword = externalPassword;
}
/**
*
* @return
* The openPassword
*/
public String getOpenPassword() {
return openPassword;
}
/**
*
* @param openPassword
* The openPassword
*/
public void setOpenPassword(String openPassword) {
this.openPassword = openPassword;
}
}
| [
"VXF4071@C9100970EE68973.amer.homedepot.com"
] | VXF4071@C9100970EE68973.amer.homedepot.com |
fa75ca0aa57c8a636915f26b39fd22d017d7a2d4 | be8604cbee8333e174e90ff7204de1d401cabee3 | /src/main/java/beahavioral/state/second/TState.java | 740a023b5fd1d1026971ae6cf42098098ebbf289 | [] | no_license | xiaolong-hub/design-patterns | d996e5556e577539653db2b308d71dd435c7ff8f | 37a716d4d95e0db8fa3cdbed061e6eb81d0016c6 | refs/heads/master | 2020-12-11T02:55:49.174249 | 2020-01-14T06:29:17 | 2020-01-14T06:29:17 | 233,772,313 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 162 | java | package beahavioral.state.second;
import beahavioral.state.first.Context;
public abstract class TState {
public abstract void Handle(TContext Tcontext);
}
| [
"13653264785@163.com"
] | 13653264785@163.com |
17b4f6b159a4325867b96da385b1e580bc401d9d | 788208ee09cd7d720faf4427b34576bdc5651766 | /core/src/Login_Register/LoginState.java | b058499e71635fe4c7625d68423feb5d0bb8151e | [] | no_license | aKhfagy/Chemical-Reactions-Game | 561a62c95fdce5040bec831a996def0356d10372 | 5ef18c7f70a429c1acfa1f8e38d5c9964af2a2cb | refs/heads/master | 2022-12-04T18:32:10.284015 | 2020-08-24T07:46:43 | 2020-08-24T07:46:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,813 | java | package Login_Register;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.utils.Align;
import Game.GameDemo;
import States.GameStateManager;
import States.MenuState;
import States.State;
public class LoginState extends State {
private TextField textField;
private LoginRegisterConnection loginDbConnection = new LoginRegisterConnection();
private Stage stage;
private Skin skin;
private BitmapFont font;
public LoginState(GameStateManager gsm, SpriteBatch sb) {
super(gsm);
bg = new Texture("LoginBg.jpeg");
stage = new Stage();
skin = new Skin(Gdx.files.internal("uiskin.json"));
Gdx.input.setInputProcessor(stage);
createTextField();
this.sb = sb;
}
public void createTextField() {
textField = new TextField("", skin);
textField.setX(590);
textField.setY(250);
textField.setWidth(200);
textField.setHeight(30);
stage.addActor(textField);
}
@Override
public void handleInput() {
int x = Gdx.input.getX();
int y = Gdx.input.getY();
if (Gdx.input.justTouched()) {
//System.out.println("x: " + Gdx.input.getX() + " y: " + Gdx.input.getY());
if (x >= 561 && x <= 793 && y >= 339 && y <= 382) {
if (loginDbConnection.LoginCheck(textField.getText())) //Correct login
{
sound.play(0.7f);
gsm.push(new MenuState(gsm, sb));
}
else { //Incorrect login
sound.play(0.7f);
showDialogBox("Please go to register page");
}
}
if (x >= 619 && x <= 727 && y >= 437 && y <= 456) { // Register button
sound.play(0.7f);
gsm.push(new RegisterState(gsm, sb));
}
}
}
@Override
public void update(float dt) {
handleInput();
}
@Override
public void render(SpriteBatch sb) {
stage.act(Gdx.graphics.getDeltaTime());
stage.getBatch().begin();
stage.getBatch().draw(bg, 0, 0, GameDemo.WIDTH, GameDemo.HEIGHT);
font = new BitmapFont();
font.getData().setScale(2, 2);
stage.getBatch().end();
stage.draw();
}
private void showDialogBox(String dialogText) {
Dialog dialog = new Dialog("", skin) ;
dialog.text(dialogText);
dialog.button("OK", true);
dialog.key(Keys.ENTER, true);
dialog.show(stage);
dialog.setSize(300.0f, 200.0f);
dialog.setPosition(Gdx.graphics.getWidth() / 2.0f, Gdx.graphics.getHeight() / 2.0f, Align.center);
}
@Override
public void dispose() {
stage.dispose();
System.out.println("Login Disposed");
}
}
| [
"saranor@gmail.com"
] | saranor@gmail.com |
f88712663b9c96db4e9d6d7b42c25cc336c620fe | 2efc3b1d8bb00b40e947edc46da2fdec11f49d49 | /src/main/java/zx/soft/similarity/word/hownet/concept/ConceptLinkedList.java | 466aa6151197bb905ca46032208f099d13d2c5a3 | [] | no_license | CoolWell/semantic-similarity | 30e8b990dbecb0d4ca6d90c46d7704a1f7111c33 | 686499e6c5d662ff636a7b2e35f0ccdb7ecf54d0 | refs/heads/master | 2021-01-22T19:03:22.495852 | 2014-10-13T23:28:09 | 2014-10-13T23:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | package zx.soft.similarity.word.hownet.concept;
import java.util.LinkedList;
/**
* 用于概念处理的LinkedList
*
* @param <T>
* @deprecated
*/
@Deprecated
@SuppressWarnings("serial")
public class ConceptLinkedList extends LinkedList<Concept> {
/**
* 删除链表中最后面的size个元素
* @param size
*/
public void removeLast(int size) {
for (int i = 0; i < size; i++) {
this.removeLast();
}
}
/**
* 根据概念的定义判断是否已经加入到链表中
* @param concept
*/
public void addByDefine(Concept concept) {
for (Concept c : this) {
if (c.getDefine().equals(concept.getDefine())) {
return;
}
}
this.add(concept);
}
}
| [
"krisibm@163.com"
] | krisibm@163.com |
913c9dee43718d938f8f133f19614c490126fdbf | ae5d142001fe2b2857dbdcf3419421335b5f6aca | /src/com/example/leedcode/Q763.java | a6808fdb9bb116c626644afcfe38ea6480ca5c88 | [] | no_license | pengllrn/AlgotirhmTest | c3de44cc8d6be4a345fbe9bef2afb59ecd543b1e | 19f3f2d3579ca8e393d893609cae552131aaacb8 | refs/heads/master | 2020-07-22T12:13:22.613622 | 2019-09-09T01:29:14 | 2019-09-09T01:29:14 | 207,198,943 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,298 | java | package com.example.leedcode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Q763 {
public static void main(String[] args) {
List<Integer> integers = new PartitionString().partitionLabels2("ababcbacadefegdehijhklij");
System.out.println(integers);
}
}
class PartitionString {
public List<Integer> partitionLabels(String s) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0)
return list;
int[] freq = new int[26];
for (char c : s.toCharArray()) {
freq[c - 'a']++;
}
int cnt = 0;
Set<Character> set = new HashSet<>();
Character cur = null;
for (char c : s.toCharArray()) {
if (cur == null)
cur = c;
set.add(c);
freq[c - 'a']--;
cnt++;
if (c == cur && freq[cur - 'a'] == 0) {
while (cur != null && freq[cur - 'a'] == 0) {
set.remove(cur);
if (set.iterator().hasNext())
cur = set.iterator().next();
else
cur = null;
}
if (set.isEmpty()) {
list.add(cnt);
cnt = 0;//重置计数器
}
}
}
return list;
}
public List<Integer> partitionLabels2(String s) {
List<Integer> list = new ArrayList<>();
if (s == null || s.length() == 0)
return list;
int[] lastIndexOfChar = new int[26];
for (int i = 0; i < s.length(); i++) {
lastIndexOfChar[s.charAt(i) - 'a'] = i;
}
int firstIndex = 0;
while (firstIndex < s.length()) {
int lastIndex = firstIndex;
for (int i = firstIndex; i <= lastIndex; i++) {
int index = lastIndexOfChar[s.charAt(i) - 'a'];
if (index > lastIndex) {//在这个范围内出现了更大的lastIndex,则进行更新
lastIndex = index;
}
}
list.add(lastIndex - firstIndex + 1);
firstIndex = lastIndex + 1;
}
return list;
}
} | [
"1256880407@qq.com"
] | 1256880407@qq.com |
5b824fd5d206491c321272ca0724c1ddbc81ec46 | f62adbf5c1d1d89a169f5f625804c4571405c77a | /src/main/java/com/lolo/lo/config/FeignConfiguration.java | abed311632608547d2c5e90ad28ddcfac0e43eec | [] | no_license | SabriChtioui/jhipster-sample-application | 39eb6939644a3d900bd10193ebb72de02ef45a51 | ec78a72246eb2a75ba0dcd08794d893ab9fcdd7e | refs/heads/master | 2020-06-26T05:21:19.935718 | 2019-07-30T00:38:15 | 2019-07-30T00:38:15 | 199,545,976 | 0 | 0 | null | 2019-10-31T10:31:36 | 2019-07-30T00:38:07 | Java | UTF-8 | Java | false | false | 660 | java | package com.lolo.lo.config;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@EnableFeignClients(basePackages = "com.lolo.lo")
@Import(FeignClientsConfiguration.class)
public class FeignConfiguration {
/**
* Set the Feign specific log level to log client REST requests.
*/
@Bean
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
09496a3711773aae1a7db74de69fa93c069971ef | d452d267def74415e417ddf3d1c7c73131543dc7 | /spring-09-proxy/src/main/java/com/lei/demo02/UserProxy.java | 0214977219241d002f7c5ba21e0a81032433646f | [] | no_license | leirongfa/springstudy | e4160d3b687b64ed1e41d80f00222681fdfc3df0 | ba7de09299ff1b0bdcfdb184a1828e91dadffb91 | refs/heads/master | 2022-12-21T03:29:37.761857 | 2019-12-29T02:24:19 | 2019-12-29T02:24:19 | 230,692,262 | 0 | 0 | null | 2022-12-16T00:41:07 | 2019-12-29T02:21:57 | Java | UTF-8 | Java | false | false | 695 | java | package com.lei.demo02;
public class UserProxy implements UserService {
private UserServiceImpI userServiceImpI;
public UserProxy(UserServiceImpI userServiceImpI) {
this.userServiceImpI = userServiceImpI;
}
@Override
public void add() {
log("add");
userServiceImpI.add();
}
@Override
public void query() {
log("query");
userServiceImpI.query();
}
@Override
public void delet() {
log("delet");
userServiceImpI.delet();
}
@Override
public void select() {
log("select");
userServiceImpI.select();
}
public void log(String msg){
System.out.println("使用"+msg+"方法");
}
}
| [
"1270617099@qq.com"
] | 1270617099@qq.com |
7bf8a22f938c6950b70bc3132e25ec2e70e27b16 | c3debbc571031781ec2f156783ae0d17fb663d90 | /qa/carbon-TestAutomation-Framework/component-test-framework/test-components/mediators-switch/src/test/java/org/wso2/carbon/mediator/switchm/test/TestRunner.java | fd66064c168f12624d114f76a792d163c7c58a60 | [] | no_license | manoj-kristhombu/commons | 1e0b24ed25a21691dfa848b8debaf95a47b9a8e0 | 4928923d66a345a3dca15c6f2a6f1fe9b246b2e8 | refs/heads/master | 2021-05-28T15:53:21.146705 | 2014-11-17T14:53:18 | 2014-11-17T14:53:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,290 | java | package org.wso2.carbon.mediator.switchm.test;
/*
* Copyright (c) WSO2 Inc. (http://wso2.com) All Rights Reserved.
WSO2 Inc. 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.
*
*/
import junit.framework.Test;
import junit.framework.TestSuite;
import org.wso2.carbon.authenticator.proxy.test.utils.FrameworkSettings;
public class TestRunner extends TestSuite {
public static Test suite() throws Exception {
FrameworkSettings.getProperty();
String frameworkPath = FrameworkSettings.getFrameworkPath();
System.setProperty("java.util.logging.config.file", frameworkPath + "/lib/log4j.properties");
TestSuite testSuite = new TestSuite();
testSuite.addTestSuite(SwitchMediatorTest.class);
return testSuite;
}
}
| [
"hasini@a5903396-d722-0410-b921-86c7d4935375"
] | hasini@a5903396-d722-0410-b921-86c7d4935375 |
1a343fbc81afd387b382f5669ac5733aad9fe824 | 8c46665f4e3c2cbc9ddbd09b2cd37f979ea75c59 | /code/up_parent/.svn/pristine/0c/0cb6015bb91d9479e2587718ef1050d085a7495f.svn-base | 3fbb0b52a1ac10cddaf9ae8551aab4a90cf23282 | [] | no_license | yangleixxjava/yxsw | 724ac2e07ae22806891328e7166c8a6dc61f5b69 | 6a55989f7b59522a9d0520a760626fcafe4555b6 | refs/heads/master | 2021-07-20T18:54:11.041991 | 2017-10-31T04:08:56 | 2017-10-31T04:08:56 | 108,939,663 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 318 | package com.upsoft.systemweb.service;
import java.util.List;
import com.upsoft.system.entity.SystemTLog;
public interface SystemLogService {
/**
* 存储系统日志
*
* @date 2017年3月9日 下午4:21:18
* @author 陈涛
* @param systemTLog
*/
void saveSystemLog(List<SystemTLog> systemTLog);
}
| [
"1906594100@qq.com"
] | 1906594100@qq.com | |
ed84b625eb2d2fc5e9a4d410ba3b16bcadabf6a4 | 7db5477d5ddfcbb11b95009b6324631d439f357c | /practika16/InternetOrder.java | 36959f387d3d23042ac65a34d560e493218a5801 | [] | no_license | Druzai/ikbo-03-19 | 9415f9c79c64bce9593405958a46079cd70c45f5 | a57a3057637f964f74055d642048767bae9ebfec | refs/heads/master | 2023-02-02T16:27:29.119010 | 2020-12-21T12:43:02 | 2020-12-21T12:43:02 | 292,049,467 | 0 | 0 | null | 2020-09-01T16:25:52 | 2020-09-01T16:25:51 | null | UTF-8 | Java | false | false | 6,934 | java | package ru.mirea.practika16;
public class InternetOrder implements Order {
private ListNode front;
private int size;
public InternetOrder() {
front = null;
}
public InternetOrder(RestaurantOrder order) {
Dish[] dishes = order.getAllDishes();
Drink[] drinks = order.getAllDrinks();
for (Dish dish : dishes) {
add(dish);
}
for (Drink drink : drinks) {
add(drink);
}
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public boolean add(Drink drink) {
try {
if (isEmpty())
front = new ListNode(drink);
else {
ListNode temp = front;
front = new ListNode(null, drink, temp);
front.next.prev = front;
}
size++;
return true;
}
catch (Exception e)
{
return false;
}
}
public boolean add(Dish dish) {
try {
if (isEmpty())
front = new ListNode(dish);
else {
ListNode temp = front;
front = new ListNode(null, dish, temp);
front.next.prev = front;
}
size++;
return true;
}
catch (Exception e)
{
return false;
}
}
public boolean remove(String name) {
if (isEmpty())
return false;
if (front.dish != null) {
if (front.dish.getName().equals(name)) {
front = front.next;
size--;
return true;
}
}
if (front.drink != null) {
if (front.drink.getName().equals(name)) {
front = front.next;
size--;
return true;
}
}
ListNode current = front;
boolean flag = true;
while (flag){
current = current.next;
if(current == null){
flag = false;
}
else if (current.dish != null){
if(current.dish.getName().equals(name)){
flag = false;
}
}
else if (current.drink != null){
if(current.drink.getName().equals(name)){
flag = false;
}
}
}
if (current == null)
return false;
if (current.next != null)
current.next.prev = current.prev;
current.prev.next = current.next;
size--;
return true;
}
public void removeAll(String name) {
boolean flag = true;
while (flag){
if(!remove(name)){
flag = false;
}
}
}
public int getSize() {
return size;
}
public RestaurantOrder getOrder(){
RestaurantOrder order = new RestaurantOrder();
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.dish != null){
order.add(temp.dish);
}
else if (temp.drink != null){
order.add(temp.drink);
}
temp = temp.next;
}
}
return order;
}
public double CostTotal(){
double cost = 0;
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.dish != null){
cost += temp.dish.getCost();
}
else if (temp.drink != null){
cost += temp.drink.getCost();
}
temp = temp.next;
}
}
return cost;
}
public double CostTotal(String s){
double cost = 0;
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.dish != null){
cost += temp.dish.getCost();
}
else if (temp.drink != null){
cost += temp.drink.getCost();
}
temp = temp.next;
}
}
return cost;
}
public int getOrderQuantity(String name){
int quantity = 0;
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.dish != null){
if(temp.dish.getName().equals(name)) {
quantity++;
}
}
else if (temp.drink != null){
if(temp.drink.getName().equals(name)) {
quantity++;
}
}
temp = temp.next;
}
}
return quantity;
}
public Drink[] getDrinks(){
Drink[] drinks = new Drink[6];
boolean flag = true;
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.drink != null){
for (int i = 0; i < 6; i++){
if (drinks[i] != null) {
if (temp.drink.getName().equals(drinks[i].getName())) {
flag = false;
}
}
}
if(flag) {
for (int i = 0; i < 6; i++){
if (drinks[i] == null){
drinks[i] = temp.drink;
break;
}
}
}
flag = true;
}
temp = temp.next;
}
}
return drinks;
}
public Dish[] getDish(){
Dish[] dishes = new Dish[6];
boolean flag = true;
if (!isEmpty()){
ListNode temp = front;
while (temp != null) {
if (temp.dish != null){
for (int i = 0; i < 6; i++){
if (dishes[i] != null) {
if (temp.dish.getName().equals(dishes[i].getName())) {
flag = false;
}
}
}
if(flag) {
for (int i = 0; i < 6; i++){
if (dishes[i] == null){
dishes[i] = temp.dish;
break;
}
}
}
flag = true;
}
temp = temp.next;
}
}
return dishes;
}
}
| [
"j7world@yandex.ru"
] | j7world@yandex.ru |
f23d4296d618d99234277b380d038d740328c9eb | 7f817d71fabec581592e997aa3c4c6545149d956 | /src/main/java/elicode/parkour/region/selection/RegionSelection.java | f5fd660d74e2fc7713d0b54f7c62227f05ab2992 | [] | no_license | Elic0de/Parkour | 952c375d4e8127d07f08fa57643eb7d3e9d51541 | 4c21d1efc12c6fa17caa00e4551263370573555c | refs/heads/master | 2021-03-23T09:30:32.372227 | 2020-12-08T11:14:04 | 2020-12-08T11:14:04 | 252,155,729 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,088 | java | package elicode.parkour.region.selection;
import org.bukkit.World;
import elicode.location.ImmutableLocation;
import elicode.location.Location;
import elicode.location.MutableLocation;
import elicode.parkour.region.Region;
import elicode.parkour.util.text.Text;
public class RegionSelection {
public final MutableLocation boundaryCorner1 = new MutableLocation(null, 0, 0, 0);
public final MutableLocation boundaryCorner2 = new MutableLocation(null, 0, 0, 0);
public void setWorld(World world){
boundaryCorner1.world = boundaryCorner2.world = world;
}
public void setBoundaryCorner1(Location location){
setBoundaryCorner1(location.getWorld(), location.getIntX(), location.getIntY(), location.getIntZ());
}
public void setBoundaryCorner1(org.bukkit.Location location){
setBoundaryCorner1(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
public void setBoundaryCorner1(World world, int x, int y, int z){
boundaryCorner1.world = world;
boundaryCorner1.x = x;
boundaryCorner1.y = y;
boundaryCorner1.z = z;
}
public void setBoundaryCorner2(Location location){
setBoundaryCorner2(location.getWorld(), location.getIntX(), location.getIntY(), location.getIntZ());
}
public void setBoundaryCorner2(org.bukkit.Location location){
setBoundaryCorner2(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
public void setBoundaryCorner2(World world, int x, int y, int z){
boundaryCorner2.world = world;
boundaryCorner2.x = x;
boundaryCorner2.y = y;
boundaryCorner2.z = z;
}
public World getWorld(){
return boundaryCorner1.world;
}
public ImmutableLocation getLesserBoundaryCorner(){
return new ImmutableLocation(
boundaryCorner1.world,
Math.min(boundaryCorner1.x, boundaryCorner2.x),
Math.min(boundaryCorner1.y, boundaryCorner2.y),
Math.min(boundaryCorner1.z, boundaryCorner2.z)
);
}
public ImmutableLocation getGreaterBoundaryCorner(){
return new ImmutableLocation(
boundaryCorner1.world,
Math.max(boundaryCorner1.x, boundaryCorner2.x),
Math.max(boundaryCorner1.y, boundaryCorner2.y),
Math.max(boundaryCorner1.z, boundaryCorner2.z)
);
}
public Region makeRegion(){
return new Region(getLesserBoundaryCorner(), getGreaterBoundaryCorner());
}
@Override
public String toString(){
World world = getWorld();
ImmutableLocation lesserBoundaryCorner = getLesserBoundaryCorner();
ImmutableLocation greaterBoundaryCorner = getGreaterBoundaryCorner();
return Text.stream("$world,$lesser_x,$lesser_y,$lesser_z,$greater_x,$greater_y,$greater_z")
.setAttribute("$world", world != null ? world.getName() : "null")
.setAttribute("$lesser_x", lesserBoundaryCorner.getIntX())
.setAttribute("$lesser_y", lesserBoundaryCorner.getIntY())
.setAttribute("$lesser_z", lesserBoundaryCorner.getIntZ())
.setAttribute("$greater_x", greaterBoundaryCorner.getIntX())
.setAttribute("$greater_y", greaterBoundaryCorner.getIntY())
.setAttribute("$greater_z", greaterBoundaryCorner.getIntZ())
.toString();
}
}
| [
"lpondboy@gmail.com"
] | lpondboy@gmail.com |
889ef119ac0634562c3fab5e0c5ee9094bab4e79 | 11dc0d47eefc481dbfacac834c1774006511873f | /src/files/text/Mp3RandomAccessDao.java | 092e99848fdf2aa21e52d6efa6fa16f97948d79d | [] | no_license | gerrymcdonnell/JavaFileHandlingExamples | 4ab8a1dfb007ad6888092d7b218ec325ca924cfb | fd4d15788260951285a420c377c4415a69670b7c | refs/heads/master | 2021-08-30T00:40:20.685853 | 2017-12-15T11:53:51 | 2017-12-15T11:53:51 | 114,365,397 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,982 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package files.text;
import files.IO.RandomFileAccessIO;
import files.business.Mp3File;
import files.exceptions.DaoException;
import files.interfaces.Mp3FileDao;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gerry
*/
public class Mp3RandomAccessDao implements Mp3FileDao{
File mp3RandomAccessFile=null;
RandomAccessFile rndOut=null;
public Mp3RandomAccessDao()
{
mp3RandomAccessFile=new File("randomaccess.txt");
rndOut=RandomFileAccessIO.getWriteRandomAccessFile(mp3RandomAccessFile);
}
public void saveFile(ArrayList<Mp3File> mp3List) throws DaoException {
for(int x=0;x<mp3List.size();x++)
{
//RandomAccessFile rndout,Mp3File mp3,int recordNum)
RandomFileAccessIO.writeRandomAccessMp3File(rndOut, mp3List.get(x), x);
}
}
public ArrayList<Mp3File> findAll() throws DaoException {
ArrayList <Mp3File> inputList=new ArrayList();
try {
inputList = RandomFileAccessIO.getRecordsFromRandomFile(rndOut);
} catch (IOException ex) {
Logger.getLogger(Mp3RandomAccessDao.class.getName()).log(Level.SEVERE, null, ex);
}
return inputList;
}
public void add(Mp3File mp3) throws DaoException {
throw new UnsupportedOperationException("Not supported yet.");
}
public int update(Mp3File mp3, int iRecordNumber) throws DaoException {
throw new UnsupportedOperationException("Not supported yet.");
}
public int delete(int recordID) throws DaoException {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getFileName()
{
return mp3RandomAccessFile.toString();
}
}
| [
"irishbloke@gmail.com"
] | irishbloke@gmail.com |
10b73d8ba9cf30c8410f46aba903a6754b0a3c5b | 8b064db95584819a12a8d434aa1fe3d30fdc2cec | /PlayGoMoKu.java | c17f75a5915ef4cece67d8f9fe34251d1dd008f9 | [] | no_license | parkerqi/Connect_Dots_Game | dfc00e99918cbaa7aa15c24e19ea8e8f3e45a0ce | 405e7a2f9e4b226f363b11f30f9ead805779f976 | refs/heads/master | 2022-06-08T06:38:03.540926 | 2020-04-29T20:08:14 | 2020-04-29T20:08:14 | 259,818,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,189 | java | import java.util.InputMismatchException;
import java.util.Scanner;
/**
* This is the runner class for playing GoMoKu between two players
* @author Parker Qi
* @author parker.qi@hotmail.com
* @version 1.0
*/
public class PlayGoMoKu {
private static Scanner sc = new Scanner(System.in);
/**
* The runner method for the game
* @param arg accepts two integers, the size of board and the connects to be made to win the game
*/
public static void main(String[] arg) {
//Board board = new Board(3, 3);
Board board = new Board(Integer.parseInt(arg[0]) , Integer.parseInt(arg[1]));
System.out.println("Select mode: PvP => p, PvC => c");
boolean gameOver = false;
while (!gameOver) {
try {
String c = sc.next();
if (c.equals("p")) {
playPvP(board);
gameOver = true;
} else if (c.equals("c")) {
playPvC(board);
gameOver = true;
} else {
System.out.println("Select mode again");
}
} catch(InputMismatchException e) {
System.out.println("Select mode again");
}
}
sc.close();
}
private static void playPvP(Board board) {
Player player1 = new Player(true);
Player player2 = new Player(false);
char gameStatus = 'E';
board.printBoard();
while (gameStatus == 'E') {
int x = -1;
int y = -1;
boolean ifNextTurn = false;
do {
try {
//player 1's turn
System.out.println("Player 1's turn.");
System.out.println("Type your piece's x axis.");
x = sc.nextInt() - 1;
System.out.println("Type your piece's y axis.");
y = sc.nextInt() - 1;
if (!player1.place(x, y, board)) {
System.out.println("Your coordinate is invalid.");
ifNextTurn = false;
} else {
ifNextTurn = true;
}
} catch (InputMismatchException e) {
System.out.println("Your coordinate is invalid.");
sc.next();
ifNextTurn = false;
}
} while (!ifNextTurn);
board.printBoard();
//check game status
gameStatus = board.checkWin();
if (gameStatus == 'X') {
System.out.println("Player 1 wins.");
} else if (gameStatus == 'T') {
System.out.println("Player 1 wins.");
} else {
do {
try {
//player 2's turn
System.out.println("Player 2's turn.");
System.out.println("Type your piece's x axis.");
x = sc.nextInt() - 1;
System.out.println("Type your piece's y axis.");
y = sc.nextInt() - 1;
if (!player2.place(x, y, board)) {
System.out.println("Your coordinate is invalid.");
ifNextTurn = false;
} else {
ifNextTurn = true;
}
} catch (InputMismatchException e) {
System.out.println("Your coordinate is invalid.");
sc.next();
ifNextTurn = false;
}
} while (!ifNextTurn);
board.printBoard();
//check game status
gameStatus = board.checkWin();
if (gameStatus == 'O') {
System.out.println("Player 2 wins.");
} else if (gameStatus == 'T') {
System.out.println("TIE!");
}
}
}
}
/**
* play PvC with this method, the human always goes first
* @param board the board to place PvC on
*/
private static void playPvC(Board board) {
AI ai = new AI(false);
Player player = new Player(true);
char gameStatus = 'E';
board.printBoard();
while (gameStatus == 'E') {
int x = -1;
int y = -1;
boolean ifNextTurn = false;
do {
try {
//player's turn
System.out.println("Your turn.");
System.out.println("Type your piece's x axis.");
x = sc.nextInt() - 1;
System.out.println("Type your piece's y axis.");
y = sc.nextInt() - 1;
if (!player.place(x, y, board)) {
System.out.println("Your coordinate is invalid.");
ifNextTurn = false;
} else {
ifNextTurn = true;
}
} catch (InputMismatchException e) {
System.out.println("Your coordinate is invalid.");
sc.next();
ifNextTurn = false;
}
} while (!ifNextTurn);
board.printBoard();
//check game status
gameStatus = board.checkWin();
if (gameStatus == 'X') {
System.out.println("You win.");
} else if (gameStatus == 'T') {
System.out.println("TIE!");
} else {
//AI's turn
ai.placePiece(board);
System.out.println("AI's turn.");
board.printBoard();
//check game status
gameStatus = board.checkWin();
if (gameStatus == 'O') {
System.out.println("AI wins.");
} else if (gameStatus == 'T') {
System.out.println("TIE!");
}
}
}
}
} | [
"parker.qi@hotmail.com"
] | parker.qi@hotmail.com |
2997e2a9d6c1df2e62b35fb11c432ea4faba1536 | 76237a1a80d637fed910a04a6bea63b600da6c43 | /Spring-Security/src/main/webapp/java/com/spring/security/controller/DemoController.java | 172002a90bd77cb3368f9eb2a7162a3d3177f47c | [] | no_license | david2999999/Spring-and-Hibernate | e9d0855be08aac2890c9c99be792a0a244e54728 | 851bb44088b40ca34ec65552ccbac630a429725c | refs/heads/master | 2021-09-10T05:29:25.227786 | 2018-03-21T05:07:46 | 2018-03-21T05:07:46 | 116,302,854 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 275 | java | package com.spring.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("/")
public String showHome() {
return "home";
}
}
| [
"djiang86@binghamton.edu"
] | djiang86@binghamton.edu |
09c211052a6f073eec1c5e30477754f8b2b164e5 | 8bdfa2cc1049f2aef448581f7bda92b5b86cdc50 | /app/src/main/java/controller/ActivityCollector.java | faa55b39e7baf5f06bcc190a6c0dbad6e47031fe | [
"Apache-2.0"
] | permissive | ChineseTang/TaskRecord | ca0ee8b00b82f75f5c2091d9f077e657528ed344 | dc413683b7c21bd3c0bfb21d9850b6b193ad26b0 | refs/heads/master | 2021-01-19T01:58:15.350071 | 2016-11-07T13:23:49 | 2016-11-07T13:23:49 | 67,578,287 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 746 | java | package controller;
/**
* Created by tangzhijing on 2016/8/31.
*/
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<Activity>();
//add a activity into the ArrayList
public static void addActivity(Activity activity) {
activities.add(activity);
}
//remove a activity into the ArrayList
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
// log out all the activities
public static void finishAll() {
for(Activity ac : activities) {
if(!ac.isFinishing()) {
ac.finish();
}
}
}
} | [
"tzjsmile@qq.com"
] | tzjsmile@qq.com |
8feb36fc110f73c441dfb93e93d8feb844065494 | b1683de3902cc81dc95d685916cf01e893a612ed | /src/main/java/epsilveira/league/persistence/Contest.java | fa9778b873ef8aa250379f10001ca91c4eb01688 | [] | no_license | VirtualEvan/LeagueJPA | b00c6223a4a6c5315b7e68c7aa4918bf2c66d46e | 63dae2693c1f320cd7f855b9a2d19406ff7713fd | refs/heads/master | 2021-09-04T14:16:02.803940 | 2018-01-19T11:27:51 | 2018-01-19T11:27:51 | 110,955,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,493 | java | package epsilveira.league.persistence;
import exception.MirrorMatchException;
import javax.persistence.*;
import java.sql.Date;
@Entity
@Table(name="Contest", uniqueConstraints={
@UniqueConstraint(columnNames = {"blueTeam_id", "redTeam_id", "schedule"})
})
public class Contest {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private Date schedule;
@ManyToOne
private Team blueTeam;
@ManyToOne
private Team redTeam;
public int getId() {
return id;
}
public Date getSchedule() {
return schedule;
}
public void setSchedule(Date schedule) {
this.schedule = schedule;
}
public void setContest(Team blueTeam, Team redTeam, Date schedule) throws MirrorMatchException {
if(blueTeam == redTeam)
throw new MirrorMatchException();
this.blueTeam = blueTeam;
this.redTeam = redTeam;
this.schedule = schedule;
}
public Team getBlueTeam() {
return blueTeam;
}
public void setBlueTeam(Team blueTeam) throws MirrorMatchException{
if(blueTeam == this.redTeam)
throw new MirrorMatchException();
this.blueTeam = blueTeam;
}
public Team getRedTeam() {
return redTeam;
}
public void setRedTeam(Team redTeam) throws MirrorMatchException {
if(redTeam == this.blueTeam)
throw new MirrorMatchException();
this.redTeam = redTeam;
}
}
| [
"virtualevan@gmail.com"
] | virtualevan@gmail.com |
c1fc7caed473bcebba139568016a1499c2567712 | 7a2bcd4a7f4ed43e34e0c1684602fb15e3d41aaa | /src/com/linpinger/foxbook/Fragment_ShowPage4Eink.java | 20a452bd2ad1d275a254b45fbd8c3e8c75858000 | [] | no_license | linpinger/foxbook-android | dccdc0ea00fb233914dc45fc1e4395f9cbd84f3b | 282a9a18a932c4081377f1ae46beee1de867de9b | refs/heads/master | 2021-07-05T16:53:44.242171 | 2021-06-02T06:58:27 | 2021-06-02T06:58:27 | 18,581,406 | 7 | 5 | null | null | null | null | UTF-8 | Java | false | false | 26,272 | java | package com.linpinger.foxbook;
import java.io.File;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.linpinger.misc.BackHandledFragment;
import com.linpinger.misc.View_FoxTextView;
import com.linpinger.novel.NV;
import com.linpinger.novel.NovelManager;
import com.linpinger.novel.Site1024;
import com.linpinger.tool.FoxZipReader;
import com.linpinger.tool.ToolAndroid;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class Fragment_ShowPage4Eink extends BackHandledFragment {
public static Fragment_ShowPage4Eink newInstance(NovelManager novelMgr, Bundle iArgs) {
Fragment_ShowPage4Eink fc = new Fragment_ShowPage4Eink();
fc.nm = novelMgr;
fc.setArguments(iArgs);
return fc;
}
public interface OnReadFinishListener {
public void OnOnReadFinish(String fmlPath, int bookIDX, int pageIDX);
}
private OnReadFinishListener offlsner;
public void setOnReadFinishListener(OnReadFinishListener inListner) { // 如果需要获取返回的阅读进度
offlsner = inListner;
}
@Override
public void onDestroy() {
if ( offlsner != null) {
offlsner.OnOnReadFinish(nm.getShelfFile().getPath(), this.bookIDX, this.pageIDX);
}
super.onDestroy();
}
private boolean isEink = false ;
@Override
public void onAttach(Activity activity) { // 1
super.onAttach(activity);
settings = PreferenceManager.getDefaultSharedPreferences(activity);
editor = settings.edit(); // 获取设置
if ( settings.getBoolean("isFullScreen", false) )
activity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 3
ctx = container.getContext();
this.isEink = ToolAndroid.isEink();
myBGcolor = settings.getString("myBGcolor", myBGcolor);
isProcessLongOneLine = settings.getBoolean("isProcessLongOneLine", isProcessLongOneLine);
isAdd2CNSpaceBeforeLine = settings.getBoolean("isAdd2CNSpaceBeforeLine", isAdd2CNSpaceBeforeLine);
mv = new FoxTextView(ctx); // 自定义View
setBGcolor(myBGcolor);
mv.setBodyBold(settings.getBoolean("isBodyBold", false));
mv.setOnTouchListener(new OnTouchListener(){ // 触摸事件
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
cX = arg1.getX(); // 获取的坐标给click使用
cY = arg1.getY(); // getRawX getRawY
return false;
}
});
mv.setOnClickListener(new OnClickListener(){ // 单击事件
@Override
public void onClick(View v) {
int vy = v.getHeight();
if ( cY <= vy / 3 ) { // 小于1/3屏高
int vx = v.getWidth(); // 屏幕宽度
if ( cX >= vx * 0.6666 ) { // 右上角1/3宽处
showConfigPopupWindow(v);
} else if (cX <= vx * 0.333) { // 左上角
back();
} else {
mv.clickPrev(); // 上中
}
} else {
mv.clickNext();
}
}
});
mv.setOnLongClickListener(new OnLongClickListener(){
@Override
public boolean onLongClick(View v) {
int vy = v.getHeight();
if ( cY <= vy / 3 ) { // 小于1/3屏高
int vx = v.getWidth(); // 屏幕宽度
if ( cX >= vx * 0.6666 ) { // 右上角1/3宽处
mv.setNextText() ; // 下一章
mv.postInvalidate();
} else if (cX <= vx * 0.333) { // 左上角
back();
} else { // 上中
mv.setPrevText(); // 上一章
mv.postInvalidate();
}
} else {
mv.clickPrev(); // 手机显示上一屏
}
return true;
}
});
tLastPushEinkButton = System.currentTimeMillis();
isMapUpKey = settings.getBoolean("isMapUpKey", isMapUpKey);
fontsize = settings.getFloat("fontsize", (float)ToolAndroid.sp2px(ctx, 18.5f)); // 字体大小
// fontsize = settings.getFloat("fontsize", fontsize);
mv.setFontSize(fontsize);
paddingMultip = settings.getFloat("paddingMultip", paddingMultip);
mv.setPadding(String.valueOf(paddingMultip) + "f");
lineSpaceingMultip = settings.getFloat("lineSpaceingMultip", lineSpaceingMultip);
mv.setLineSpaceing(String.valueOf(lineSpaceingMultip) + "f");
// { Fragment里监听虚拟按键和实体按键的返回事件
mv.setFocusable(true);
mv.setFocusableInTouchMode(true);
mv.requestFocus();
mv.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(View v, int kc, KeyEvent event) {
// 莫名其妙的按一个按钮出现两个keyCode
if ( ( event.getAction() == KeyEvent.ACTION_UP ) & ( KeyEvent.KEYCODE_PAGE_DOWN == kc | KeyEvent.KEYCODE_PAGE_UP == kc | KeyEvent.KEYCODE_VOLUME_UP == kc | KeyEvent.KEYCODE_VOLUME_DOWN == kc ) ) {
if ( System.currentTimeMillis() - tLastPushEinkButton < 1000 ) { // 莫名其妙的会多按,也是醉了
tLastPushEinkButton = System.currentTimeMillis();
return true ;
}
// 2016-8-15: BOOX C67ML Carta 左右翻页健对应: KEYCODE_PAGE_UP = 92, KEYCODE_PAGE_DOWN = 93
if ( ! isMapUpKey ) {
if ( KeyEvent.KEYCODE_PAGE_UP == kc | KeyEvent.KEYCODE_VOLUME_UP == kc ) {
mv.clickPrev();
tLastPushEinkButton = System.currentTimeMillis();
return true;
}
}
mv.clickNext();
tLastPushEinkButton = System.currentTimeMillis();
return true;
}
if ( KeyEvent.KEYCODE_PAGE_DOWN == kc | KeyEvent.KEYCODE_PAGE_UP == kc | KeyEvent.KEYCODE_VOLUME_UP == kc | KeyEvent.KEYCODE_VOLUME_DOWN == kc ) {
return true;
}
if ( KeyEvent.KEYCODE_MENU == kc & event.getAction() == KeyEvent.ACTION_UP ) {
showConfigPopupWindow(mv);
return true;
}
return false;
}
});
// } Key
Bundle itt = getArguments(); // 传入参数
ittAction = itt.getInt(AC.action);
bookIDX = itt.getInt(NV.BookIDX, -1);
pageIDX = itt.getInt(NV.PageIDX, -1);
if ( ittAction == AC.aShowPageInMem ) { // 1024DB3
if ( nm.getBookInfo(bookIDX).get(NV.BookURL).toString().contains("zip://") )
ittAction = AC.aShowPageInZip1024 ;
}
switch ( ittAction ) {
case AC.aAnotherAppShowContent: // 51用来传递title, content供其他应用直接调用
mv.setText(itt.getString("title"), " " + itt.getString("content").replace("\n", "\n "), "从其他应用传来的内容");
break;
case AC.aAnotherAppShowOnePageIDX: //"fmlPath": 52需传递bookIDX, pageIDX,
case AC.aShowPageInMem:
if ( AC.aAnotherAppShowOnePageIDX == ittAction ) {
this.nm = new NovelManager(new File(itt.getString("fmlPath")));
}
Map<String, Object> page = nm.getPage(bookIDX, pageIDX);
String pagetext = page.get(NV.Content).toString();
if ( null == pagetext | pagetext.length() < 5 )
pagetext = "本章节内容还没下载,请回到列表,更新本书或本章节" ;
pagetext = ProcessLongOneLine(pagetext);
if ( isAdd2CNSpaceBeforeLine ) {
mv.setText(page.get(NV.PageName).toString()
, " " + pagetext.replace("\n", "\n ")
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
} else {
mv.setText(page.get(NV.PageName).toString()
, pagetext
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
}
break;
case AC.aShowPageOnNet: // NET
final String pageTitle = itt.getString(NV.PageName);
final String fullPageURL = itt.getString(NV.PageFullURL);
new Thread( new Runnable() {
@Override
public void run() {
String text = nm.updatePage(fullPageURL) ;
HashMap<String, String> page = new HashMap<String, String>(2);
page.put(NV.PageName, pageTitle);
page.put(NV.Content, text);
page.put(NV.PageFullURL, fullPageURL);
handler.obtainMessage(IS_REFRESH, page).sendToTarget();
}
}).start();
break;
case AC.aShowPageInZip1024: // ZIP文件
String zipPageFullURL = itt.getString(NV.PageFullURL);
Matcher mat = Pattern.compile("(?i)^zip://([^@]*?)@([^@]*)$").matcher(zipPageFullURL);
String zipRelPath = "";
String zipItemName = "";
while (mat.find()) {
zipRelPath = mat.group(1) ;
zipItemName = mat.group(2) ;
}
ZIPFILE = new File(nm.getShelfFile().getParent() + "/" + zipRelPath);
String html = FoxZipReader.getUtf8TextFromZip(ZIPFILE, zipItemName);
String content = "";
String pageName = "";
if ( html.contains("\"tpc_content\"") ) {
HashMap<String, Object> xx = new Site1024().getContentTitle(html);
pageName = xx.get(NV.PageName).toString();
content = xx.get(NV.Content).toString();
}
if ( isAdd2CNSpaceBeforeLine ) {
mv.setText(pageName , " " + content.replace("\n", "\n ")
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
} else {
mv.setText(pageName , content
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
}
break;
}
return mv;
} // oncreate 结束
private class onViewClickListener implements View.OnClickListener { // 单击
@Override
public void onClick(View v) {
switch ( v.getId() ) {
case R.id.pc_chap_prev:
mv.setPrevText(); // 上一章
mv.postInvalidate();
break;
case R.id.pc_chap_next:
mv.setNextText() ; // 下一章
mv.postInvalidate();
break;
case R.id.pc_size_add:
changeView(11); // 增大字体
break;
case R.id.pc_size_sub:
changeView(9); // 减小字体
break;
case R.id.pc_size_text:
changeView(10); // 默认 字体
break;
case R.id.pc_line_add:
changeView(21); // 加 行间距
break;
case R.id.pc_line_sub:
changeView(19); // 减 行间距
break;
case R.id.pc_line_text:
changeView(20); // 默认 行间距
break;
case R.id.pc_left_add:
changeView(31); // 增大页边距
break;
case R.id.pc_left_sub:
changeView(29); // 减小页边距
break;
case R.id.pc_left_text:
changeView(30); // 默认 页边距
break;
case R.id.pc_bg_a:
setBGcolor("green");
break;
case R.id.pc_bg_b:
setBGcolor("gray");
break;
case R.id.pc_bg_c:
setBGcolor("white");
break;
case R.id.pc_bg_d:
setBGcolor("default");
break;
case R.id.pc_useFont:
changeView(66);
break;
case R.id.pc_setting:
changeView(99);
break;
} // switch end
}
}
private void showConfigPopupWindow(View view) {
// 一个自定义的布局,作为显示的内容
View popView = LayoutInflater.from(ctx).inflate(R.layout.popupwin_showpage, null);
popView.findViewById(R.id.pc_chap_prev).setOnLongClickListener(olcl_exit);
onViewClickListener cl = new onViewClickListener();
// 设置按钮的点击事件
popView.findViewById(R.id.pc_chap_prev).setOnClickListener(cl);
popView.findViewById(R.id.pc_chap_next).setOnClickListener(cl);
popView.findViewById(R.id.pc_size_add).setOnClickListener(cl);
popView.findViewById(R.id.pc_size_sub).setOnClickListener(cl);
popView.findViewById(R.id.pc_size_text).setOnClickListener(cl);
popView.findViewById(R.id.pc_line_add).setOnClickListener(cl);
popView.findViewById(R.id.pc_line_sub).setOnClickListener(cl);
popView.findViewById(R.id.pc_line_text).setOnClickListener(cl);
popView.findViewById(R.id.pc_left_sub).setOnClickListener(cl);
popView.findViewById(R.id.pc_left_add).setOnClickListener(cl);
popView.findViewById(R.id.pc_left_text).setOnClickListener(cl);
popView.findViewById(R.id.pc_bg_a).setOnClickListener(cl);
popView.findViewById(R.id.pc_bg_b).setOnClickListener(cl);
popView.findViewById(R.id.pc_bg_c).setOnClickListener(cl);
popView.findViewById(R.id.pc_bg_d).setOnClickListener(cl);
popView.findViewById(R.id.pc_useFont).setOnClickListener(cl);
popView.findViewById(R.id.pc_useFont).setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
changeView(67);
return true;
}
});
popView.findViewById(R.id.pc_setting).setOnClickListener(cl);
popView.findViewById(R.id.pc_setting).setOnLongClickListener(olcl_exit); // e-ink: 27.5 1.7 0.8
popView.setFocusable(true);
popView.setFocusableInTouchMode(true);
popView.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_MENU && event.getAction() == KeyEvent.ACTION_UP) {
configPopWin.dismiss();
isMenuShow = false;
return true;
}
return false;
}
});
configPopWin = new PopupWindow(popView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
true); // MATCH_PARENT
configPopWin.setTouchable(true);
configPopWin.setOutsideTouchable(true);
configPopWin.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return false; // 这里如果返回true的话,touch事件将被拦截,拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
}
});
// 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
// 我觉得这里是API的一个bug
configPopWin.setBackgroundDrawable(new ColorDrawable(0));
// 设置好参数之后再show
//configPopWin.showAsDropDown(view);
configPopWin.showAtLocation(view, Gravity.CENTER, 0, 0); // 中间
isMenuShow = true;
// 有个小bug不知道怎么排除: 按menu键: 显示,消失,显示,显示,消失,显显消...
}
private class FoxTextView extends View_FoxTextView {
public FoxTextView(Context context) {
super(context);
}
private int setPrevOrNextText(boolean isNextPage) {
if ( -1 == pageIDX ) { // 网络,应重定义为-1
foxtip("亲,ID 为 -1");
return -1;
}
Map<String, Object> mp ;
String strNoMoreTip ;
if ( isNextPage ) {
mp = nm.getNextPage(bookIDX, pageIDX);
strNoMoreTip = "亲,没有下一页了";
} else {
mp = nm.getPrevPage(bookIDX, pageIDX);
strNoMoreTip = "亲,没有上一页了";
}
if ( null == mp ) {
foxtip(strNoMoreTip);
return -2;
}
if ( ittAction == AC.aShowPageInZip1024 ) {
String html = FoxZipReader.getUtf8TextFromZip(ZIPFILE, mp.get(NV.PageURL).toString());
if ( html.contains("\"tpc_content\"") )
mp.putAll(new Site1024().getContentTitle(html));
}
String newBookAddWJX = "★" ;
if ( (Integer)mp.get(NV.BookIDX) == bookIDX )
newBookAddWJX = "" ;
bookIDX = (Integer) mp.get(NV.BookIDX);
pageIDX = (Integer) mp.get(NV.PageIDX);
String pagetext = mp.get(NV.Content).toString();
if ( pagetext.length() == 0 ) {
foxtip("内容未下载: " + mp.get(NV.PageName));
return -3;
}
pagetext = ProcessLongOneLine(pagetext);
if ( isAdd2CNSpaceBeforeLine ) {
mv.setText(newBookAddWJX + mp.get(NV.PageName).toString()
, " " + pagetext.replace("\n", "\n ")
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
} else {
mv.setText(newBookAddWJX + mp.get(NV.PageName).toString()
, pagetext
, nm.getBookInfo(bookIDX).get(NV.BookName).toString()
+ " " + nm.getPagePosAtShelfPages(bookIDX, pageIDX));
}
return 0;
}
@Override
public int setPrevText() {
return setPrevOrNextText(false); // 上一
}
@Override
public int setNextText() {
return setPrevOrNextText(true); // 下一
}
@Override
public void clickPrev() {
super.clickPrev();
if ( isEink ) { ToolAndroid.c67ml_FullRefresh(this); }
}
@Override
public void clickNext() {
super.clickNext();
if ( isEink ) { ToolAndroid.c67ml_FullRefresh(this); }
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (0 != (event.getSource() & InputDevice.SOURCE_CLASS_POINTER)) { // 2020-05-24: 鼠标滚轮事件的响应
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
//获得垂直坐标上的滚动方向,也就是滚轮向下滚
if( event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f){
clickNext();
} else{ //获得垂直坐标上的滚动方向,也就是滚轮向上滚
clickPrev();
}
return true;
}
}
return super.onGenericMotionEvent(event);
}
}
void changeView(int actionID) {
switch (actionID) {
case 9: // 减小 字体
case 10: // 默认 字体
case 11: // 增大 字体
if ( 9 == actionID ) {
fontsize -= 0.5f ;
} else if ( 10 == actionID ) {
fontsize = 36.5f;
if ( isEink ) { fontsize = 27.5f;}
} else if ( 11 == actionID ) {
fontsize += 0.5f ;
}
mv.setFontSize(fontsize).postInvalidate();
editor.putFloat("fontsize", fontsize).commit();
((TextView) configPopWin.getContentView().findViewById(R.id.pc_size_text)).setText(new DecimalFormat("#.0").format(fontsize));
// foxtip("字体大小: " + fontsize);
break;
case 19: // 减小 行间距
case 20: // 默认 行间距
case 21: // 增大 行间距
if ( 19 == actionID ) {
lineSpaceingMultip -= 0.05f ;
} else if ( 20 == actionID ) {
lineSpaceingMultip = 1.55f;
if ( isEink ) { lineSpaceingMultip = 1.7f;}
} else if ( 21 == actionID ) {
lineSpaceingMultip += 0.05f ;
}
mv.setLineSpaceing(String.valueOf(lineSpaceingMultip) + "f").postInvalidate();
editor.putFloat("lineSpaceingMultip", lineSpaceingMultip).commit();
((TextView) configPopWin.getContentView().findViewById(R.id.pc_line_text)).setText(new DecimalFormat("#.00").format(lineSpaceingMultip));
// foxtip("行间距: " + lineSpaceingMultip);
break;
case 29: // 减小 页边距
case 30: // 默认 页边距
case 31: // 增大 页边距
if ( 29 == actionID ) {
paddingMultip -= 0.1f ;
} else if ( 30 == actionID ) {
paddingMultip = 0.5f;
if ( isEink ) { paddingMultip = 0.8f;}
} else if ( 31 == actionID ) {
paddingMultip += 0.1f ;
}
mv.setPadding(String.valueOf(paddingMultip) + "f").postInvalidate();
editor.putFloat("paddingMultip", paddingMultip).commit();
((TextView) configPopWin.getContentView().findViewById(R.id.pc_left_text)).setText(new DecimalFormat("0.0").format(paddingMultip));
// foxtip("页边距: " + paddingMultip);
break;
case 66:
String nowFontPath = settings.getString("selectfont", "/sdcard/fonts/foxfont.ttf") ;
if ( ! mv.setUserFontPath(nowFontPath) ) {
foxtip("字体不存在:\n\n" + nowFontPath + "\n\n现在选择字体文件");
selectFile();
} else {
mv.postInvalidate();
}
break;
case 67:
selectFile();
break;
case 99:
startFragment( new Fragment_Setting() );
break;
}
}
// public void selectFile() { // todo
// Fragment_FileChooser fc = Fragment_FileChooser.newInstance( android.os.Environment.getExternalStorageDirectory().getPath() );
// fc.setOnFileChoosenListener(new Fragment_FileChooser.OnFileChoosenListener(){
// @Override
// public void OnFileChoosen(File selectedFile) {
// if ( selectedFile != null ) {
// String newFont = selectedFile.getPath();
// String nowPATH = newFont.toLowerCase() ;
// if ( nowPATH.endsWith(".ttf") | nowPATH.endsWith(".ttc") | nowPATH.endsWith(".otf") ) {
// editor.putString("selectfont", newFont).commit();
// foxtip(newFont);
// mv.setUserFontPath(newFont);
// mv.postInvalidate();
// } else {
// foxtip("要选择后缀为.ttf/.ttc/.otf的字体文件");
// }
// }
// }
// });
// startFragment( fc );
// }
public void selectFile() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 9);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 9: // 响应文件选择器的选择
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
// 判断文件名后缀
String newFont = new File(uri.getPath()).getAbsolutePath();
if ( newFont.contains("/document/primary:") ) { // 神奇的路径
newFont = "/sdcard/" + newFont.split(":")[1];
}
String nowPATH = newFont.toLowerCase() ;
if ( nowPATH.endsWith(".ttf") | nowPATH.endsWith(".ttc") | nowPATH.endsWith(".otf") ) {
editor.putString("selectfont", newFont);
editor.commit();
foxtip("\n" + uri.getPath() + "\n" + newFont);
mv.setUserFontPath(newFont);
mv.postInvalidate();
} else {
foxtip("要选择后缀为.ttf/.ttc/.otf的字体文件");
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setBGcolor(String bgcolor) {
myBGcolor = bgcolor ;
editor.putString("myBGcolor", myBGcolor).commit();
if ( myBGcolor.equalsIgnoreCase("white") )
mv.setBackgroundResource(R.color.qd_mapp_bg_white); // 白色背景
if ( myBGcolor.equalsIgnoreCase("green") )
mv.setBackgroundResource(R.color.qd_mapp_bg_green);
if ( myBGcolor.equalsIgnoreCase("default") )
mv.setBackgroundResource(R.drawable.parchment_paper); // 绘制两次
if ( myBGcolor.equalsIgnoreCase("gray") )
mv.setBackgroundResource(R.color.qd_mapp_bg_grey); // 灰色
}
private String ProcessLongOneLine(String iText) {
if ( ! isProcessLongOneLine )
return iText ;
// long sTime = System.currentTimeMillis();
int sLen = iText.length(); // 字符数
if ( sLen == 0 )
return "";
int lineCount = 0 ; // 行数
try {
LineNumberReader lnr = new LineNumberReader(new StringReader(iText));
while ( null != lnr.readLine() )
++ lineCount;
} catch ( Exception e ) {
e.toString();
}
if ( ( sLen / lineCount ) > 200 ) { // 小于200(也许可以定到130)意味着换行符够多,处理的时候不会太卡,大于阈值200就得处理得到足够多的换行符
// Log.e("XX", "Cal : " + sLen + " / " + lineCount + " >= 200 ");
iText = iText.replace("。", "。\n");
iText = iText.replace("\n\n", "\n");
}
// Log.e("TT", "Time=" + ( System.currentTimeMillis() - sTime ) );
return iText;
}
OnLongClickListener olcl_exit = new OnLongClickListener() { // 专门用于长按退出
@Override
public boolean onLongClick(View arg0) {
back();
return true;
}
};
private void foxtip(String sinfo) { // Toast消息
Toast.makeText(ctx, sinfo, Toast.LENGTH_SHORT).show();
}
Handler handler = new Handler(new WeakReference<Handler.Callback>(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if ( msg.what == IS_REFRESH ) {
HashMap<String, String> page = (HashMap<String, String>)msg.obj;
String sText = page.get(NV.Content);
if ( sText.length() < 9 ) {
mv.setText("错误", " 啊噢,可能处理的时候出现问题了哦\n\nURL: "
+ page.get(NV.PageFullURL)
+ "\nPageName: " + page.get(NV.PageName)
+ "\nContent:" + sText);
} else {
sText = ProcessLongOneLine(sText);
if ( isAdd2CNSpaceBeforeLine ) {
mv.setText(page.get(NV.PageName).toString(), " " + sText.replace("\n", "\n "));
} else {
mv.setText(page.get(NV.PageName).toString(), sText);
}
}
mv.postInvalidate();
}
return true;
}
}).get());
Context ctx;
// { Var Init
private NovelManager nm;
private int ittAction = 0; // 传入数据
private int bookIDX = -1 ; // 翻页时使用
private int pageIDX = -1 ; // 翻页时使用
FoxTextView mv;
private float cX = 0 ; // 点击View的坐标
private float cY = 0 ; // 点击View的坐标
SharedPreferences settings;
SharedPreferences.Editor editor;
private String myBGcolor = "green"; // 背景:默认羊皮纸
private boolean isMapUpKey = false; // 是否映射上翻为下翻键
// 2018-06 : phone: 36.5 1.55 0.5 e-ink: 27.5 1.7 0.8
private float fontsize = 36.5f; // 字体大小
private float lineSpaceingMultip = 1.55f ; // 行间距倍数
private float paddingMultip = 0.5f ; // 页边距 = 字体大小 * paddingMultip
private boolean isProcessLongOneLine = true; // 处理超长单行 > 4K
private boolean isAdd2CNSpaceBeforeLine = true ; // 自动添加两空白
private long tLastPushEinkButton ;
private final int IS_REFRESH = 5 ;
private File ZIPFILE ;
PopupWindow configPopWin;
boolean isMenuShow = false;
// } Var Init
}
| [
"linpinger@gmail.com"
] | linpinger@gmail.com |
2e57b3a644d93b6a44c21165325316532c68ac92 | 31fea38d5e68fa1ec7d297f135a8f5ac4bc3a2c0 | /jabeja-peersim/src/peersim/jabeja/JabejaNode.java | 6f0e0041039506e6c4679d9451341fab575cc9aa | [] | no_license | payberah/jabeja | 1bd9c6463c94ce15d1126b477c639a4b710f216a | 69c9e69ee2c57baa68672586798d9f10e95cef80 | refs/heads/master | 2021-01-10T05:26:27.207418 | 2015-05-27T14:09:06 | 2015-05-27T14:09:06 | 36,371,034 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,666 | java | package peersim.jabeja;
import java.util.ArrayList;
import java.util.HashMap;
import peersim.cdsim.CDProtocol;
import peersim.config.Configuration;
import peersim.core.CommonState;
import peersim.core.Node;
import peersim.jabeja.JabejaOverlay;
import peersim.jabeja.Newscast;
import peersim.jabeja.NodeAddress;
import peersim.jabeja.Tman;
public class JabejaNode implements CDProtocol {
private static final String NEWSCAST_PROTOCOL = "newscast";
private final int newscastPID;
private Newscast newscast;
private static final String TMAN_PROTOCOL = "tman";
private final int tmanPID;
private Tman tman;
private static final String OVERLAY_PROTOCOL = "overlay";
private final int overlayPID;
private JabejaOverlay overlay;
private static final String NOISE = "noise";
private static final String NOISE_DELTA = "noisedelta";
private static final String POW = "power";
private static int NUM_OF_WALKS = 1;
private static double LOCALITY = 1000;
private int protocolId;
private NodeAddress self;
private int color;
private int numColors;
private int walkLength = 1;
public double noise;
private double noiseDelta;
private int power;
private static int numberOfSwaps = 0;
private static int numberOfLocalSwaps = 0;
public int initialColor;
//---------------------------------------------------------------------
public JabejaNode(String prefix) {
this.newscastPID = Configuration.getPid(prefix + "." + NEWSCAST_PROTOCOL);
this.tmanPID = Configuration.getPid(prefix + "." + TMAN_PROTOCOL);
this.overlayPID = Configuration.getPid(prefix + "." + OVERLAY_PROTOCOL);
this.noise = Configuration.getDouble(prefix + "." + NOISE);
this.noiseDelta = Configuration.getDouble(prefix + "." + NOISE_DELTA);
this.power = Configuration.getInt(prefix + "." + POW);
}
//---------------------------------------------------------------------
public Object clone() {
JabejaNode partitionNode = null;
try {
partitionNode = (JabejaNode)super.clone();
} catch(CloneNotSupportedException e) {
// never happens
}
return partitionNode;
}
//--------------------------------------------------------------------
public void init(Node node, int id, int color, int numColors, int protocolId) {
this.self = new NodeAddress(node, id);
this.color = color;
this.initialColor = color;
this.numColors = numColors;
this.protocolId = protocolId;
this.newscast = (Newscast)node.getProtocol(this.newscastPID);
this.tman = (Tman)node.getProtocol(this.tmanPID);
this.overlay = (JabejaOverlay)node.getProtocol(this.overlayPID);
}
//--------------------------------------------------------------------
public int getId() {
return this.self.getId();
}
//--------------------------------------------------------------------
public Node getNode() {
return this.self.getNode();
}
//--------------------------------------------------------------------
public int getColor() {
return this.color;
}
//--------------------------------------------------------------------
public void assignColor(int color) {
this.color = color;
}
//--------------------------------------------------------------------
public HashMap<Integer, Integer> getNeighboursColors() {
int nodeColor;
Integer neighbourColor;
JabejaNode neighbourNode;
HashMap<Integer, Integer> neighboursColors = new HashMap<Integer, Integer>();
for (int i = 0; i < this.numColors; i++)
neighboursColors.put(i, 0);
ArrayList<Node> neighbours = this.overlay.getNeighbors();
for (Node node : neighbours) {
neighbourNode = (JabejaNode)node.getProtocol(this.protocolId);
nodeColor = neighbourNode.getColor();
neighbourColor = neighboursColors.get(nodeColor);
neighboursColors.put(nodeColor, neighbourColor + 1);
}
return neighboursColors;
}
//--------------------------------------------------------------------
public void nextCycle(Node n, int protocolId) {
this.swap(n, protocolId);
}
//--------------------------------------------------------------------
public void swap(Node n, int protocolId) {
JabejaNode bestNode = null;
double highestBenefit = 0;
Node next = null;
JabejaNode selfNode = (JabejaNode)n.getProtocol(protocolId);
ArrayList<JabejaNode> randomNodes = new ArrayList<JabejaNode>();
ArrayList<Node> newscastNodes = this.newscast.getNeighbors();
ArrayList<Node> tmanNodes = this.tman.getNeighbors();
int selfNodeColor = selfNode.getColor();
HashMap<Integer, Integer> selfNodeNeighboursColors = selfNode.getNeighboursColors();
// random walk
for (int j = 0; j < NUM_OF_WALKS; j++) {
JabejaNode randomNode = selfNode;
ArrayList<Node> visited = new ArrayList<Node>();
visited.add(this.self.getNode());
for (int i = 0; i < this.walkLength; i++) {
next = randomNode.getRandomNode();
randomNode = (JabejaNode)next.getProtocol(protocolId);
}
randomNodes.add(randomNode);
}
// calculate the cost function
for (JabejaNode tempNode : randomNodes) {
int tempNodeColor = tempNode.getColor();
if (tempNodeColor == this.color)
continue;
HashMap<Integer, Integer> tempNodeNeighboursColors = tempNode.getNeighboursColors();
int c1SelfNodeBenefit = selfNodeNeighboursColors.get(selfNodeColor);
int c1TempNodeBenefit = tempNodeNeighboursColors.get(tempNodeColor);
int c2SelfNodeBenefit = selfNodeNeighboursColors.get(tempNodeColor);
int c2TempNodeBenefit = tempNodeNeighboursColors.get(selfNodeColor);
double oldBenefit = Math.pow(c1SelfNodeBenefit, this.power) + Math.pow(c1TempNodeBenefit, this.power);
double newBenefit = Math.pow(c2SelfNodeBenefit, this.power) + Math.pow(c2TempNodeBenefit, this.power);
if (this.initialColor == tempNode.initialColor) {
newBenefit *= LOCALITY;
oldBenefit *= LOCALITY;
}
if (newBenefit * this.noise > oldBenefit && newBenefit > highestBenefit) {
bestNode = tempNode;
highestBenefit = newBenefit;
}
}
// try with the newscast nodes
if (bestNode == null) {
randomNodes.clear();
for (Node node : newscastNodes) {
if (node != null)
randomNodes.add((JabejaNode)node.getProtocol(protocolId));
}
for (JabejaNode tempNode : randomNodes) {
int tempNodeColor = tempNode.getColor();
if (tempNodeColor == this.color)
continue;
HashMap<Integer, Integer> tempNodeNeighboursColors = tempNode.getNeighboursColors();
int c1SelfNodeBenefit = selfNodeNeighboursColors.get(selfNodeColor);
int c1TempNodeBenefit = tempNodeNeighboursColors.get(tempNodeColor);
int c2SelfNodeBenefit = selfNodeNeighboursColors.get(tempNodeColor);
int c2TempNodeBenefit = tempNodeNeighboursColors.get(selfNodeColor);
double oldBenefit = Math.pow(c1SelfNodeBenefit, this.power) + Math.pow(c1TempNodeBenefit, this.power);
double newBenefit = Math.pow(c2SelfNodeBenefit, this.power) + Math.pow(c2TempNodeBenefit, this.power);
if (this.initialColor == tempNode.initialColor) {
newBenefit *= LOCALITY;
oldBenefit *= LOCALITY;
}
if (newBenefit * this.noise > oldBenefit && newBenefit > highestBenefit) {
bestNode = tempNode;
highestBenefit = newBenefit;
}
}
}
// try with the tman nodes
if (bestNode == null && tmanNodes != null) {
randomNodes.clear();
for (Node node : tmanNodes) {
if (node != null)
randomNodes.add((JabejaNode)node.getProtocol(protocolId));
}
for (JabejaNode tempNode : randomNodes) {
int tempNodeColor = tempNode.getColor();
if (tempNodeColor == this.color)
continue;
HashMap<Integer, Integer> tempNodeNeighboursColors = tempNode.getNeighboursColors();
int c1SelfNodeBenefit = selfNodeNeighboursColors.get(selfNodeColor);
int c1TempNodeBenefit = tempNodeNeighboursColors.get(tempNodeColor);
int c2SelfNodeBenefit = selfNodeNeighboursColors.get(tempNodeColor);
int c2TempNodeBenefit = tempNodeNeighboursColors.get(selfNodeColor);
double oldBenefit = Math.pow(c1SelfNodeBenefit, this.power) + Math.pow(c1TempNodeBenefit, this.power);
double newBenefit = Math.pow(c2SelfNodeBenefit, this.power) + Math.pow(c2TempNodeBenefit, this.power);
if (this.initialColor == tempNode.initialColor) {
newBenefit *= LOCALITY;
oldBenefit *= LOCALITY;
}
if (newBenefit * this.noise > oldBenefit && newBenefit > highestBenefit) {
bestNode = tempNode;
highestBenefit = newBenefit;
}
}
}
// swap the colors
if (bestNode != null) {
selfNode.assignColor(bestNode.color);
bestNode.assignColor(selfNodeColor);
numberOfSwaps++;
if (selfNode.initialColor == bestNode.initialColor)
numberOfLocalSwaps++;
}
if (this.noise > 1)
this.noise -= this.noiseDelta;
if (this.noise < 1)
this.noise = 1;
}
//--------------------------------------------------------------------
public Node getRandomNode() {
Node next = null;
JabejaNode partitionNode;
int degree = this.overlay.degree();
ArrayList<Node> neighbours = this.overlay.getNeighbors();
while(true) {
if (degree == 0) {
next = this.self.getNode();
break;
} else if (degree == 1)
next = neighbours.get(0);
else
next = neighbours.get(CommonState.r.nextInt(degree));
partitionNode = (JabejaNode)next.getProtocol(this.protocolId);
if (partitionNode.getId() != this.getId())
break;
}
return next;
}
//--------------------------------------------------------------------
public ArrayList<Node> getNeighbours() {
return this.overlay.getNeighbors();
}
//--------------------------------------------------------------------
public int hasDiffColorNeibour() {
int diffColorCount = 0;
JabejaNode neighbourNode;
ArrayList<Node> neighbours = this.overlay.getNeighbors();
for (Node node : neighbours) {
neighbourNode = (JabejaNode)node.getProtocol(this.protocolId);
if (this.color != neighbourNode.getColor())
diffColorCount++;
}
return diffColorCount;
}
//--------------------------------------------------------------------
public static int getNumberOfSwaps() {
return numberOfSwaps;
}
//--------------------------------------------------------------------
public static int getNumberOfLocalSwaps() {
return numberOfLocalSwaps;
}
//--------------------------------------------------------------------
public static void resetNumberOfSwaps() {
numberOfSwaps = 0;
numberOfLocalSwaps = 0;
}
//--------------------------------------------------------------------
@Override
public String toString() {
return this.self.getId() + "";
}
} | [
"amir@sics.se"
] | amir@sics.se |
782e58bd1bc69dc4d28431e226fee54b77b9c5d7 | 70361e5bfde53137c9d9ecaf87e75de314ceb320 | /app_reto5/src/main/java/co/utp/misiontic2022/c2/App.java | fb7de0acd03abf4a1c3e2adde1f392c3db3ab96d | [] | no_license | MigkGonzalez/Reto_5 | 3b2cdb181a1a4104cd4c3cc789278e79c8733e09 | 1eeb5341e5a8b2efe0837ae4db13104ee669e3f9 | refs/heads/main | 2023-07-05T14:17:20.802995 | 2021-08-20T21:38:39 | 2021-08-20T21:38:39 | 398,403,671 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package co.utp.misiontic2022.c2;
import co.utp.misiontic2022.c2.view.WindowReq;
public class App
{
public static void main(String[] args) {
var view = new WindowReq();
view.setVisible(true);
}
}
| [
"mfgonzaleza@unal.edu.co"
] | mfgonzaleza@unal.edu.co |
db39d62c2a1bdb9323834b1390b3c52ee92e751e | cfc22ac3e5b784ab5b0ea5bbf648b12c086a6731 | /TestTasks/test_project_car_hierarchy/src/fighter_hd/com/car/Car.java | 83317c21157c99c02663f0888f09ee4ac770c0d3 | [] | no_license | fighter-hd/MyProjects | 2b63976cc53434d67c12bc832240eb6174ba8980 | 7817a64af3f876e841a1a0c547f97dafb09d7879 | refs/heads/master | 2020-06-15T23:24:43.179789 | 2020-01-11T02:05:22 | 2020-01-11T02:05:22 | 195,420,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,905 | java | package fighter_hd.com.car;
import fighter_hd.com.details.body.Body;
import fighter_hd.com.details.body.BodyType;
import fighter_hd.com.details.engines.Engine;
import fighter_hd.com.details.transmission.Transmission;
import fighter_hd.com.details.transmission.TransmissionType;
import java.util.Date;
public abstract class Car {
protected String brand;
protected String model;
protected int manufactureYear;
protected int doorsCount;
protected int wheelsCount;
protected float maxSpeed;
protected float weight;
protected float power;
protected String color;
protected BodyType bodyType;
protected TransmissionType transmissionType;
protected Body body;
protected Transmission transmission;
protected Engine[] engines;
public Car(String brand, String model, int doorsCount, int wheelsCount, float maxSpeed, String color,
BodyType bodyType, TransmissionType transmissionType) {
this.brand = brand;
this.model = model;
this.doorsCount = doorsCount;
this.wheelsCount = wheelsCount;
this.maxSpeed = maxSpeed;
this.color = color;
this.bodyType = bodyType;
this.transmissionType = transmissionType;
this.manufactureYear = new Date().getYear();
this.body = new Body(bodyType, color, wheelsCount, doorsCount);
this.transmission = new Transmission(transmissionType);
}
public void startEngine() {
for (Engine engine : engines) {
if ( ! engine.isWorking()) {
engine.start();
} else {
System.out.println("Engine working already");
}
}
}
public void stopEngine() {
for (Engine engine : engines) {
if (engine.isWorking()) {
engine.stop();
} else {
System.out.println("Engine stopped already");
}
}
}
public void increaseSpeed() {
transmission.shiftUp();
for (Engine engine : engines) {
engine.increaseRPM();
}
}
public void decreaseSpeed() {
transmission.shiftDown();
for (Engine engine : engines) {
engine.decreaseRPM();
}
}
public void turnLeft() {
System.out.println("Turning left");
}
public void turnRight() {
System.out.println("Turning right");
}
protected static float calculateWeight(Body body, Transmission transmission, Engine[] engines) {
float resultWeight = body.getWeight() + transmission.getWeight();
for (Engine engine : engines) {
resultWeight += engine.getWeight();
}
return resultWeight;
}
protected static float calculatePower(Engine[] engines) {
float resultPower = 0;
for (Engine engine : engines) {
resultPower += engine.getPower();
}
return resultPower;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public int getManufactureYear() {
return manufactureYear;
}
public int getDoorsCount() {
return doorsCount;
}
public int getWheelsCount() {
return wheelsCount;
}
public float getMaxSpeed() {
return maxSpeed;
}
public float getWeight() {
return weight;
}
public float getPower() {
return power;
}
public String getColor() {
return color;
}
public BodyType getBodyType() {
return bodyType;
}
public TransmissionType getTransmissionType() {
return transmissionType;
}
public Body getBody() {
return body;
}
public Transmission getTransmission() {
return transmission;
}
public Engine[] getEngines() {
return engines;
}
}
| [
"deng19081994@mail.ru"
] | deng19081994@mail.ru |
fe7ba34ee6ec3e25d563b0ec9004931a8e79f30d | 74922284971e2bc09dfc3adc7d6584040b092675 | /Java-Codes-master/Java projects/AWT class work/Trail1/Registration.java | 1a90de0b53a57ac59f1cba954743e7a4b7b3d6fc | [] | no_license | annesha-dash/Java-Codes-master | af7fd4701dd060392ecca7c5d17bd6175df91dfd | 3b99588f570e7aef386e2f44d6fff4cd9301b0b4 | refs/heads/master | 2020-03-17T10:25:10.006101 | 2018-05-15T12:05:10 | 2018-05-15T12:05:10 | 133,511,023 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,627 | java | import java.awt.*;
class Registration extends Frame{
TextField t1,t2,t3,t4,t5,t6;
Button b1,b2;
Registration(){
setLayout(new FlowLayout());
this.setLayout(null);
Label l1 = new Label("First name",Label.CENTER);
t1 = new TextField(40);
this.add(l1);
this.add(t1);
Label l2 = new Label("Last name",Label.CENTER);
t2 = new TextField(40);
this.add(l2);
this.add(t2);
Label l3 = new Label("Username",Label.CENTER);
t3 = new TextField(40);
this.add(l3);
this.add(t3);
Label l4 = new Label("Password",Label.CENTER);
t4 = new TextField(40);
t4.setEchoChar('*');
this.add(l4);
this.add(t4);
Label l5 = new Label("Confirm Password",Label.CENTER);
t5 = new TextField(40);
t5.setEchoChar('*');
this.add(l5);
this.add(t5);
Label l6 = new Label("Contact Number",Label.CENTER);
t6 = new TextField(40);
this.add(l6);
this.add(t6);
b1 = new Button("Cancel");
b2 = new Button("Confirm");
this.add(b1);
this.add(b2);
l1.setBounds(10,20,40,40);
l2.setBounds(10,100,40,40);
l3.setBounds(10,170,40,40);
l4.setBounds(10,240,40,40);
l5.setBounds(10,310,40,40);
l6.setBounds(10,380,40,40);
t1.setBounds(80,20,40,120);
t2.setBounds(80,100,40,120);
t3.setBounds(80,170,40,120);
t4.setBounds(80,240,40,120);
t5.setBounds(80,310,40,120);
t6.setBounds(80,380,40,120);
b1.setBounds(10,420,40,40);
b2.setBounds(100,420,40,40);
}
public static void main(String args[]){
Registration ml=new Registration();
ml.setVisible(true);
ml.setSize(800,800);
ml.setTitle("my Registration window");
}
} | [
"38961078+annesha-dash@users.noreply.github.com"
] | 38961078+annesha-dash@users.noreply.github.com |
56a4daa96ab5dbbf68bc9f7bb5458690b433e598 | 63f8d4ab70752c441aaf879f2bda08284fc6a209 | /src/main/java/com/revature/assignforce/domain/dao/CurriculumRepository.java | deb866ac2d8e0168d63e285b2bd17223521a3f42 | [] | no_license | ajduet/cloneme | 642abcc1353e42ba2e0e5ef4142d28f49838a5f9 | a8f3355daff59fcfca56c182bb2d42efc631e24a | refs/heads/master | 2020-06-11T12:30:59.852804 | 2016-12-05T18:05:54 | 2016-12-05T18:05:54 | 75,666,981 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 248 | java | package com.revature.assignforce.domain.dao;
import org.springframework.stereotype.Repository;
import com.revature.assignforce.domain.Curriculum;
@Repository
public interface CurriculumRepository extends BaseRepository<Curriculum, Integer> {
}
| [
"august@revature.com"
] | august@revature.com |
9d5d06a4859a3c1fc70be1a20b7feca3637ac5f2 | d291a56c212e4bae1366fe9e57c5fee84ae10b6c | /android/MeetPlayer/src/com/pplive/common/util/PlayBackTime.java | 620f0d1fe982f6c6f55c6fb7effc8c1f852fc174 | [] | no_license | muzidudu/MeetSDK | 981c3339c149caae0091e7e8753a16409115b43e | dede3e75a26c6b3822bcabe990a12757a5755d09 | refs/heads/master | 2021-05-31T13:30:48.428902 | 2016-01-21T07:54:50 | 2016-01-21T07:54:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,719 | java | package com.pplive.common.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import com.pplive.meetplayer.R;
public class PlayBackTime {
private final static String TAG = "PlayBackTime";
private Context mContext;
private long mStartTimeSec = -1;
private int mDurationSec = 60;
private String mPlaylinkSurfix;
public PlayBackTime(Context ctx) {
mContext = ctx;
}
public long getStartTime() {
return mStartTimeSec;
}
public int getDuration() {
return mDurationSec;
}
public String getPlaylinkSurfix() {
return mPlaylinkSurfix;
}
public void setLive() {
mDurationSec = 0;
mPlaylinkSurfix = null;
}
public void setPlaybackTime() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
View view = View.inflate(mContext, R.layout.date_time_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
final Spinner spinnerDuration = (Spinner) view.findViewById(R.id.spinner_duration);
final int[] duration_min = new int[]{0, 10, 20, 30, 60, 120, 180};
ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource(
mContext, R.array.duration_array, android.R.layout.simple_spinner_item);
sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDuration.setAdapter(sourceAdapter);
spinnerDuration.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String name = parent.getItemAtPosition(pos).toString();
Log.i(TAG, "onItemSelected " + name);
}
public void onNothingSelected(AdapterView parent) {
Log.i(TAG, "onNothingSelected");
}
});
builder.setView(view);
Calendar cal = Calendar.getInstance();
timePicker.setIs24HourView(true);
if (mStartTimeSec != -1) {
cal.setTimeInMillis(mStartTimeSec * 1000);
timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
}
else {
cal.setTimeInMillis(System.currentTimeMillis());
datePicker.init(
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
null);
timePicker.setCurrentHour(18/*cal.get(Calendar.HOUR_OF_DAY)*/);
timePicker.setCurrentMinute(30/*cal.get(Calendar.MINUTE)*/);
}
// default duration
if (mDurationSec == 0)
mDurationSec = 60;
int pos = -1;
for (int i=0;i<duration_min.length;i++) {
if (mDurationSec == duration_min[i]) {
pos = i;
break;
}
}
if (pos != -1)
spinnerDuration.setSelection(pos);
builder.setTitle("select start time");
builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year, month, day, hour, min;
year = datePicker.getYear();
month = datePicker.getMonth();
day = datePicker.getDayOfMonth();
hour = timePicker.getCurrentHour();
min = timePicker.getCurrentMinute();
String strHour = String.format("%02d", hour);
String strMin = String.format("%02d", min);
StringBuffer sb = new StringBuffer();
sb.append(String.format("%d-%02d-%02d",
year, month, day));
sb.append(" ");
sb.append(strHour).append(":").append(strMin);
String strTime;
strTime = String.format("%d-%02d-%02d %02d:%02d",
datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth(),
timePicker.getCurrentHour(),
timePicker.getCurrentMinute());
// step1
GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, min, 0);
mStartTimeSec = gc.getTimeInMillis() / 1000;
// step2
int pos = spinnerDuration.getSelectedItemPosition();
mDurationSec = duration_min[pos];
Log.i(TAG, String.format("start_time %d sec, duration %d min", mStartTimeSec, mDurationSec));
if (mDurationSec == 0) {
mPlaylinkSurfix = null;
Toast.makeText(mContext, String.format("duration is 0, toggle to LIVE mode"),
Toast.LENGTH_SHORT).show();
return;
}
mPlaylinkSurfix = String.format("&begin_time=%d&end_time=%d",
mStartTimeSec, mStartTimeSec + mDurationSec * 60);
try {
mPlaylinkSurfix = URLEncoder.encode(mPlaylinkSurfix, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(TAG, "Java: mPlayerLinkSurfix final: " + mPlaylinkSurfix);
dialog.cancel();
Toast.makeText(mContext, String.format("toggle to playback mode start %s, duration %d min",
sb.toString(), mDurationSec),
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
mPlaylinkSurfix = null;
mDurationSec = 0;
Toast.makeText(mContext, String.format("toggle to LIVE mode"),
Toast.LENGTH_SHORT).show();
}
});
Dialog dialog = builder.create();
dialog.show();
}
}
| [
"guoliangma@pptv.com"
] | guoliangma@pptv.com |
28c8014f50c5a7c4565bf83fd700544095e00cd1 | 68da13c180a3918456de3a2b1d9717520e480bfe | /model/entities/TaxPayer.java | 19108018f7d06422a3c769859392e66bbb0a15af | [] | no_license | fabianofelix3/coursejava | e72133407b5cc5316f8da5d1e412670a2aebbbf2 | 725c6ebf353f4638f8d44d047eb5b1540e94497d | refs/heads/master | 2020-04-05T01:48:27.594397 | 2018-12-29T16:32:10 | 2018-12-29T16:32:10 | 156,451,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 502 | java | package entities;
public abstract class TaxPayer {
private String name;
private Double anualIncome;
public TaxPayer(String name, Double anualIncome) {
this.name = name;
this.anualIncome = anualIncome;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAnualIncome() {
return anualIncome;
}
public void setAnualIncome(double anualIncome) {
this.anualIncome = anualIncome;
}
public abstract Double tax();
}
| [
"fabianofelix3@gmail.com"
] | fabianofelix3@gmail.com |
87061b579c0464bd9be2d079b5223a258ccafcbd | 7ea4538f902aee37e1765e9c0e139fa5c32c6bff | /src/main/java/org/young/wiki/impl/AbstractService.java | 5e234a4b42ad00d71e18d7f02f6205b05391356c | [] | no_license | FlyFire-Young/young-wiki | 1773b62ce2e3db241e4837ccd038ec9281dd7a53 | 0ce149f143bb8147011d9f830e23b883bbb169e3 | refs/heads/master | 2020-03-25T00:00:59.030515 | 2018-08-02T14:50:59 | 2018-08-02T14:50:59 | 143,165,388 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 344 | java | package org.young.wiki.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.young.wiki.dao.YBookDao;
import org.young.wiki.dao.UserDao;
/**
* Created by Young on 2017/9/8.
*/
public abstract class AbstractService {
@Autowired
protected UserDao userDao;
@Autowired
protected YBookDao yBookDao;
}
| [
"mr_liuy01@163.com"
] | mr_liuy01@163.com |
066deed3d538c60773c3ae0ee031c4d8b1cb5824 | 160656914f30df7fa7ad585f4e6293c5c57fd983 | /app/src/main/java/io/github/ynagarjuna1995/levelup2/data/models/GoogleDirections.java | bb48db65db75eb103295ae346841cf13e3294fe3 | [] | no_license | carlhuth/LevelUp2 | 1d880741886c22be3b9d5f61d8601521f0aeaf2b | f7d39f77598489722af3defd571046e798dd3f03 | refs/heads/master | 2020-05-16T13:09:35.457866 | 2018-07-31T08:09:34 | 2018-07-31T08:09:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,099 | java | package io.github.ynagarjuna1995.levelup2.data.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class GoogleDirections implements Parcelable {
public String status;
@SerializedName("routes")
public ArrayList<DirectionsRoutes> Routes;
protected GoogleDirections(Parcel in) {
status = in.readString();
Routes = in.createTypedArrayList(DirectionsRoutes.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(status);
dest.writeTypedList(Routes);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<GoogleDirections> CREATOR = new Creator<GoogleDirections>() {
@Override
public GoogleDirections createFromParcel(Parcel in) {
return new GoogleDirections(in);
}
@Override
public GoogleDirections[] newArray(int size) {
return new GoogleDirections[size];
}
};
}
| [
"nagarjuna@e9ine.com"
] | nagarjuna@e9ine.com |
732ce05288b7f7883dabe875df86114cfc972195 | 8520e57a45c3b8b09a90f6677a4c9d323c628d3b | /- SpringBoot 06-gestaoFesta/src/main/java/com/algaworks/gestaoFesta/repositories/Convidados.java | d9b31b8e1fe4a8e9194fce52811b3bdfd69a8811 | [] | no_license | leonarita/Java | e58156f7ef409884a3dfe2c3d8ab84a4b57984f1 | 7dc31112de4d8006f61f2bda1ce4e2b757bbda54 | refs/heads/master | 2023-08-18T15:27:43.598098 | 2022-05-22T15:28:44 | 2022-05-22T15:28:44 | 252,060,876 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 306 | java | package com.algaworks.gestaoFesta.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.algaworks.gestaoFesta.models.ConvidadoFesta;
@Repository
public interface Convidados extends JpaRepository<ConvidadoFesta, Long> {
} | [
"leo_narita@hotmail.com"
] | leo_narita@hotmail.com |
4db280a86a805ae1b4ef8401b90648699d207a7d | c0fe21b86f141256c85ab82c6ff3acc56b73d3db | /starshield/src/main/java/com/jdcloud/sdk/service/starshield/client/DeletePageRuleExecutor.java | 7638272e363308fde85280ca5ea3786c536535ac | [
"Apache-2.0"
] | permissive | jdcloud-api/jdcloud-sdk-java | 3fec9cf552693520f07b43a1e445954de60e34a0 | bcebe28306c4ccc5b2b793e1a5848b0aac21b910 | refs/heads/master | 2023-07-25T07:03:36.682248 | 2023-07-25T06:54:39 | 2023-07-25T06:54:39 | 126,275,669 | 47 | 61 | Apache-2.0 | 2023-09-07T08:41:24 | 2018-03-22T03:41:41 | Java | UTF-8 | Java | false | false | 1,460 | java | /*
* Copyright 2018 JDCLOUD.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.
*
* Page-Rules-for-a-Zone
* A rule describing target patterns for requests and actions to perform on matching requests
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.starshield.client;
import com.jdcloud.sdk.client.JdcloudExecutor;
import com.jdcloud.sdk.service.JdcloudResponse;
import com.jdcloud.sdk.service.starshield.model.DeletePageRuleResponse;
/**
* 删除页面规则
*/
class DeletePageRuleExecutor extends JdcloudExecutor {
@Override
public String method() {
return "DELETE";
}
@Override
public String url() {
return "/zones/{zone_identifier}/pagerules/{identifier}";
}
@Override
public Class<? extends JdcloudResponse> returnType() {
return DeletePageRuleResponse.class;
}
}
| [
"jdcloud-api@jd.com"
] | jdcloud-api@jd.com |
ff0eed90c6e2e5297d26f8a60c4bd5f18430dd3a | d57f0dbf43b3acb9ff933ba990595c17d17a0bcf | /src/enstabretagne/BE/AnalyseSousMarine/SimEntity/SousMarin/EntitySousMarinFeature.java | 48b30d002685ae4a8d254a92c268b7dd3f4b2ab6 | [] | no_license | loupita/Simulation | 87326bba426b0096a089dbfc22a4e9ebd3895374 | 4e9ee80701a2d5f2532d091447583e298470ca06 | refs/heads/master | 2020-04-18T02:07:15.836376 | 2019-01-23T07:47:02 | 2019-01-23T07:47:02 | 167,148,245 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 901 | java | package enstabretagne.BE.AnalyseSousMarine.SimEntity.SousMarin;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.MouvementSequenceur.EntityMouvementSequenceurFeature;
import enstabretagne.simulation.components.data.SimFeatures;
import javafx.scene.paint.Color;
public class EntitySousMarinFeature extends SimFeatures {
private double taille;
private double rayon;
private Color couleur;
private EntityMouvementSequenceurFeature seq;
public EntitySousMarinFeature(String id,double taille,double rayon,Color couleur,EntityMouvementSequenceurFeature seq) {
super(id);
this.taille = taille;
this.couleur = couleur;
this.rayon=rayon;
this.seq=seq;
}
public Color getCouleur() {
return couleur;
}
public double getRayon() {
return rayon;
}
public double getTaille() {
return taille;
}
public EntityMouvementSequenceurFeature getSeqFeature() {
return seq;
}
}
| [
"joselinewatio@gmail.com"
] | joselinewatio@gmail.com |
3b38109b0a96f34c786e55d07a04965df25e5e9c | 98a4535c94d7092a95bf517b86496ae82d275388 | /wex-service/src/main/java/com/xuc/wex/dao/userteam/UserTeamDao.java | 5d4fc6bf6d7478330f12dc60ba932599d7a33ea9 | [] | no_license | xucg1993/wex | 03a34363316ca0fbb3587c68dad082d7aceea585 | bb0dd9a51a43ca6be65d682e6c868d49ea149286 | refs/heads/master | 2021-01-20T10:32:38.901248 | 2016-11-30T05:47:27 | 2016-11-30T05:47:27 | 75,146,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 260 | java | package com.xuc.wex.dao.userteam;
import com.xuc.wex.model.userteam.UserTeam;
import org.springframework.stereotype.Service;
/**
* Created by XCG on 2016/11/26.
*/
@Service
public interface UserTeamDao {
public int insertUserTeam(UserTeam userTeam);
}
| [
"805679287@qq.com"
] | 805679287@qq.com |
198d5b6fd4090dd04629d852b9d00c25a408f5dd | ba1bf787840630ff08b11f4fe82380a55faca5ad | /fanfan-web/src/main/java/com/fanfan/alon/map/SysUserDao.java | 35f77d2e5951c378878265ddd9fe5e6087f3f1f3 | [] | no_license | bigDragonKing/fanfan2.0.4 | d47deafd1f49d70e01da9c5d10c87f4f24c64ead | 03435c9ad02dae66ec6da66b997d72478f275463 | refs/heads/master | 2020-03-26T21:44:05.674898 | 2019-02-27T08:48:00 | 2019-02-27T08:48:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 530 | java | package com.fanfan.alon.map;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.fanfan.alon.models.SysUserEntity;
import java.util.List;
/**
* 功能描述:系统用户
* @param:
* @return:
* @auther: zoujiulong
* @date: 2018/8/28 15:36
*/
public interface SysUserDao extends BaseMapper<SysUserEntity> {
/**
* 查询用户的所有权限
* @param userId 用户ID
*/
List<String> queryAllPerms(Long userId);
/**
* 查询用户的所有菜单ID
*/
List<Long> queryAllMenuId(Long userId);
}
| [
"zjl122400"
] | zjl122400 |
8a48b6ee4a58cc6a100318643c45d6fb46adc5c2 | aa9cf28d5bbfc092f66107975cc1a2f8172d6288 | /src/main/java/com/spring/mytourbook/controller/TravelsController.java | e9e12d9a99c2a3d1b6ad385f08e5a1a4a2cbff8d | [] | no_license | Niju5/mytourbook | 40d0eee0507f29b32a57845621beb8e8440d4a91 | baf66489b2f0a9a5753a0e60f9f7baff71999fa2 | refs/heads/main | 2023-08-23T07:37:52.076167 | 2021-10-19T10:08:47 | 2021-10-19T10:08:47 | 413,761,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,552 | java | package com.spring.mytourbook.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.spring.mytourbook.entities.Travels;
import com.spring.mytourbook.service.ITravelsService;
@RestController
@RequestMapping("/api")
public class TravelsController {
@Autowired
ITravelsService tservice;
@PostMapping("/atravels")
public Travels addTravels(@RequestBody Travels travels) {
return tservice.addTravels(travels);
}
@PutMapping("/utravels")
public Travels updateTravels(@RequestBody Travels travels) {
return tservice.updateTravels(travels);
}
@DeleteMapping("/rtravels/{travelsId}")
public String removeTravels(@PathVariable("travelsId") Long travelsId) {
return tservice.removeTravels(travelsId);
}
@GetMapping("/stravels/{travelsId}")
public Optional<Travels> searchTravels(@PathVariable("travelsId") Long travelsId) {
return tservice.searchTravels(travelsId);
}
@GetMapping("/vtravels")
public List<Travels> viewTravels(){
return tservice.viewTravels();}
}
| [
"niju.new@gmail.com"
] | niju.new@gmail.com |
a98304ff368e61385b514fe411b4e75de5311bc9 | 486d524306e821a37aef0459485fd3510802b2a8 | /app/src/test/java/com/example/printdemo/ExampleUnitTest.java | 635172e6155f76ae5e7b3f0bb6f3e2114e51426e | [] | no_license | a3802/PrintDemo | e44b7d4fe83116a6dafa94d0684dc6cd635868f9 | bdadea304e77f83741a167ef0d30d361e04cd1b9 | refs/heads/master | 2023-05-07T02:40:03.181406 | 2021-05-25T07:56:22 | 2021-05-25T07:56:22 | 370,610,183 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.example.printdemo;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"253092329@qq.com"
] | 253092329@qq.com |
29d89f6a371b0f971843ffb19e08a6dd092bfa32 | 3cc05271257eb12224b84b2dfd5c003ec3cd9f34 | /MeteoCalDaverioDemaria/src/main/java/MeteoCal/gui/security/PublicScheduleBean.java | 3eb17aa68fccac2dd670a4e58dbc2f477cd02ab9 | [] | no_license | matteo-daverio/Meteocal | 8990288680c32b3f872326380ebceea787942148 | 46241abaa07327205dd2b555b892ddf4d25a47a7 | refs/heads/master | 2021-01-19T06:00:23.946642 | 2016-07-11T08:25:18 | 2016-07-11T08:25:18 | 63,005,151 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,577 | java | /*
* 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 MeteoCal.gui.security;
import MeteoCal.business.security.boundary.EventManagerInterface;
import MeteoCal.business.security.boundary.UserManagerInterface;
import MeteoCal.business.security.entity.Event;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleModel;
/**
*
* @author Matteo
*/
@ViewScoped
@Named
public class PublicScheduleBean implements Serializable {
@EJB
EventManagerInterface em;
@EJB
UserManagerInterface um;
private List<String> users = new ArrayList<>();
private Event event;
private ScheduleModel eventModel;
private String username;
/**
* initialize public calendar
*/
@PostConstruct
public void init() {
eventModel = new DefaultScheduleModel();
users = um.getListUsersPublic();
}
/**
* load event of public calendar
*/
public void loadCalendar() {
List<Event> tempCalendar = em.loadPublicCalendar(username);
for (Event tempEvent : tempCalendar) {
DefaultScheduleEvent temp = new DefaultScheduleEvent(tempEvent.getTitle(), tempEvent.getStartTime(), tempEvent.getEndTime());
temp.setDescription(tempEvent.getIdEvent().toString());
if (!eventModel.getEvents().contains(temp)) {
eventModel.addEvent(temp);
} else {
eventModel.updateEvent(temp);
}
}
}
/**
* getter e setter
* @return
*/
public ScheduleModel getEventModel() {
return eventModel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<String> getUsers() {
return users;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public void setUsers(List<String> users) {
this.users = users;
}
}
| [
"matteo.daverio@mail.polimi.it"
] | matteo.daverio@mail.polimi.it |
edd73bb6020781418fb1fc26452c3cae7556f8b0 | a7baaa4633315f766064372c00c0ca3cfa50be20 | /src/main/java/ru/kizilov/dbcourceproject/models/Sportsman.java | c5163fbdb4a686dce76f66bba5ece106095774f0 | [] | no_license | Brekhin/DBCourceProject | 97a2d5b7ca5b9fe0492ce043bca974e0a032b51e | d26b68972649456f7a05e2dd07d427cf621866bc | refs/heads/master | 2020-03-29T23:59:33.939757 | 2018-10-23T07:35:59 | 2018-10-23T07:35:59 | 150,499,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,789 | java | package ru.kizilov.dbcourceproject.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "sportsmans")
public class Sportsman {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
private String firstName;
private String lastName;
private String alias;
private int growth;
private int weight;
private int lengthOfHands;
private int countOfLose;
private int countOfWin;
private int countOfDraw;
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "fight_sport",
joinColumns = @JoinColumn(name = "id"),
inverseJoinColumns = @JoinColumn(name = "fightid")
)
private List<Fight> fights = new ArrayList<>();
private String filename;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Long getId() {
return id;
}
public List<Fight> getFights() {
return fights;
}
public void setFights(List<Fight> fights) {
this.fights = fights;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public int getGrowth() {
return growth;
}
public void setGrowth(int growth) {
this.growth = growth;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getLengthOfHands() {
return lengthOfHands;
}
public void setLengthOfHands(int lengthOfHands) {
this.lengthOfHands = lengthOfHands;
}
public int getCountOfLose() {
return countOfLose;
}
public void setCountOfLose(int countOfLose) {
this.countOfLose = countOfLose;
}
public int getCountOfWin() {
return countOfWin;
}
public void setCountOfWin(int countOfWin) {
this.countOfWin = countOfWin;
}
public int getCountOfDraw() {
return countOfDraw;
}
public void setCountOfDraw(int countOfDraw) {
this.countOfDraw = countOfDraw;
}
}
| [
"brekhin@bk.ru"
] | brekhin@bk.ru |
8731da48e3fb4dbe75b75c963f4208da40b14ea7 | 7630fb80c152050acabd25762f32c324730ea89b | /src/main/java/com/jukinmedia/service/covidapp/service/CovidCountryService.java | 0c75001712ba2a1742d3299c661c6d729812245c | [] | no_license | sattarasif/jukinMedia | fe6ff4aba4d7ef1a54ee028842d5748c67fcd10f | 71baf12a10e1326154b2c0215d8629d6900a68ff | refs/heads/master | 2023-06-02T00:25:31.982493 | 2021-06-22T07:53:22 | 2021-06-22T07:53:22 | 378,446,605 | 0 | 0 | null | 2021-06-22T08:38:57 | 2021-06-19T15:38:01 | Java | UTF-8 | Java | false | false | 5,855 | java | package com.jukinmedia.service.covidapp.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.jukinmedia.service.covidapp.entity.CovidCountry;
import com.jukinmedia.service.covidapp.entity.TotalCovidRecord;
import com.jukinmedia.service.covidapp.entity.WorldWiseCovidRecord;
import com.jukinmedia.service.covidapp.exception.CovidException;
import com.jukinmedia.service.covidapp.repository.CovidCountryRepository;
import com.jukinmedia.service.covidapp.repository.TotalCovidRecordRepository;
import com.jukinmedia.service.covidapp.repository.WorldWiseCovidRecordRepository;
@Service
public class CovidCountryService {
@Autowired
private CovidCountryRepository covidCountryRepository;
@Autowired
private TotalCovidRecordRepository totalCovidRecordRepository;
@Autowired
private WorldWiseCovidRecordRepository worldWiseCovidRecordRepository;
@Value("${get.covid.name.api.url}")
private String covidCountryUrlByName;
@Value("${get.covid.code.api.url}")
private String covidCountryUrlByCode;
@Value("${get.total.api.url}")
private String covidTotalRecordUrl;
@Value("${get.countries.api.url}")
private String covidWorldWisedUrl;
@Value("${api.key}")
private String apiKey;
private static final String CovidRapidApiKey = "X-RapidAPI-Key";
public List<CovidCountry> saveCovidCountry(String format, String countryNameOrCode, boolean isCode) {
CovidCountry[] covidCountry = getCovidDataByCountryNameOrCode(format,countryNameOrCode, isCode).getBody();
List<CovidCountry> listOfCovidCountry = new ArrayList<CovidCountry>(Arrays.asList(covidCountry));
return listOfCovidCountry.isEmpty() ? listOfCovidCountry : covidCountryRepository.saveAll(listOfCovidCountry);
}
private ResponseEntity<CovidCountry[]> getCovidDataByCountryNameOrCode(String format, String countryNameOrCode, boolean isCode) {
RestTemplate restTemplate = new RestTemplate();
xmlFormat(format, restTemplate);
HttpHeaders headers = getHeadersObj();
Map<String, String> params = new HashMap<String, String>();
params.put("format", format);
params.put("name", countryNameOrCode);
HttpEntity<String> entity = new HttpEntity<String>(headers);
if(isCode )
return restTemplate.exchange(covidCountryUrlByCode,HttpMethod.GET,entity, CovidCountry[].class, params);
else
return restTemplate.exchange(covidCountryUrlByName,HttpMethod.GET,entity, CovidCountry[].class, params);
}
private void xmlFormat(String format, RestTemplate restTemplate) {
if(format.equalsIgnoreCase("xml")) {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
}
}
public CovidCountry getCovidCountryById (int id) {
return covidCountryRepository.findById(id).orElseThrow(() ->new CovidException("Invalid id found for covid country - " + id));
}
public TotalCovidRecord getTotalRecordyById (int id) {
return totalCovidRecordRepository.findById(id).orElseThrow(() ->new CovidException("Invalid id found for total record - " + id));
}
public WorldWiseCovidRecord getWorldWiseCovidRecordyById (int id) {
return worldWiseCovidRecordRepository.findById(id).orElseThrow(() ->new CovidException("Invalid id for world wise covid record - " + id));
}
public List<TotalCovidRecord> saveTotalCovidRecords() {
TotalCovidRecord[] totalCovidRecords = getTotalNoCovidRecords().getBody();
List<TotalCovidRecord> listOfCovidCountry = new ArrayList<TotalCovidRecord>(Arrays.asList(totalCovidRecords));
return listOfCovidCountry.isEmpty() ? listOfCovidCountry : totalCovidRecordRepository.saveAll(listOfCovidCountry);
}
private ResponseEntity<TotalCovidRecord[]> getTotalNoCovidRecords() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHeadersObj();
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange(covidTotalRecordUrl, HttpMethod.GET, entity, TotalCovidRecord[].class);
}
public List<WorldWiseCovidRecord> saveListOfCovidRecords() {
WorldWiseCovidRecord[] totalCovidRecords = getWorldWiseCovidRecords().getBody();
List<WorldWiseCovidRecord> listOfCovidCountry = new ArrayList<WorldWiseCovidRecord>(Arrays.asList(totalCovidRecords));
return listOfCovidCountry.isEmpty() ? listOfCovidCountry : worldWiseCovidRecordRepository.saveAll(listOfCovidCountry);
}
private ResponseEntity<WorldWiseCovidRecord[]> getWorldWiseCovidRecords() {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHeadersObj();
HttpEntity<String> entity = new HttpEntity<String>(headers);
return restTemplate.exchange(covidWorldWisedUrl, HttpMethod.GET, entity, WorldWiseCovidRecord[].class);
}
private HttpHeaders getHeadersObj() {
HttpHeaders headers = new HttpHeaders();
headers.set(CovidRapidApiKey, apiKey);
return headers;
}
}
| [
"asifsattar@Asifs-MacBook-Air.local"
] | asifsattar@Asifs-MacBook-Air.local |
ed93c32d9f402564586d0f4c533c5ce1c83bba12 | 0dc8512bad13990b8e63b814b7240987040df934 | /app/src/androidTest/java/com/example/imeeting/ExampleInstrumentedTest.java | f16895cb591dc57584e8feb0c37a87781205a4a9 | [
"Apache-2.0"
] | permissive | wangbin1221/spaceOrder | fcfb837dabfe913aaacb95608d9a32728d97817b | 3957708843391d0211ff41bab6e7cea7253486c5 | refs/heads/master | 2020-07-21T17:13:52.820670 | 2019-09-07T08:15:52 | 2019-09-07T08:15:52 | 206,928,864 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 724 | java | package com.example.imeeting;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.imeeting", appContext.getPackageName());
}
}
| [
"865827205@qq.com"
] | 865827205@qq.com |
b68e2ab9eacc9a67ad35b364f2b197e701e4498a | 16b9a63d4e1dbbbca660be346683e6fa389e1c75 | /app/src/main/java/com/udacity/sandwichclub/MainActivity.java | 1d7d90f2b0473f3b843765a16afc246ecee48327 | [] | no_license | rray89/sandwich-club | 97ff38402d75d024ecc8d2015a3db5e07ee4fec9 | 004947126ad43d0dc04da874b4f4511022fa57a9 | refs/heads/master | 2020-03-15T22:15:45.648183 | 2018-05-18T15:18:21 | 2018-05-18T15:18:21 | 132,369,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,381 | java | package com.udacity.sandwichclub;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] sandwiches = getResources().getStringArray(R.array.sandwich_names);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, sandwiches);
// Simplification: Using a ListView instead of a RecyclerView
ListView listView = findViewById(R.id.lv_sandwiches);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
launchDetailActivity(position);
}
});
}
private void launchDetailActivity(int position) {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, position);
startActivity(intent);
}
}
| [
"rray@hotmail.ca"
] | rray@hotmail.ca |
e6c45982dd80ba7c1d3ffc522f2c64e9f0c1a16b | 897dea1f165cc7c325d5abdc190b70c0e96fe994 | /app/src/main/java/com/medvision/vrmed/utils/ToHexByteUtils.java | 25c1453802f1dba38170243f6656b992c118098a | [] | no_license | VinVon/MedVrmc | f3e0c69f3dbc5ee33a356d2466464ce89e9ced5c | 2c980f5c497dc0c453613ecf8908d143a003ed49 | refs/heads/master | 2021-04-03T09:01:57.163341 | 2018-03-29T08:59:09 | 2018-03-29T08:59:10 | 125,143,702 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,216 | java | package com.medvision.vrmed.utils;
import java.io.UnsupportedEncodingException;
/**
* Created by raytine on 2017/12/1.
*/
public class ToHexByteUtils {
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
public static String bytesToHexString(byte[] value) {
StringBuffer sb = new StringBuffer(value.length);
String sTemp;
for (int i = 0; i < value.length; i++) {
sTemp = Integer.toHexString(0xFF & value[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
//16进制转ASCII
public static String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
// 49204c6f7665204a617661 split into two characters 49, 20, 4c...
for (int i = 0; i < hex.length() - 1; i += 2) {
// grab the hex in pairs
String output = hex.substring(i, (i + 2));
// convert hex to decimal
int decimal = Integer.parseInt(output, 16);
// convert the decimal to character
sb.append((char) decimal);
temp.append(decimal);
}
return sb.toString();
}
//ASCII转16进制
public static String convertStringToHex(String str) {
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}
return hex.toString();
}
/**
* UTF-8编码 转换为对应的 汉字
*
* URLEncoder.encode("上海", "UTF-8") ---> %E4%B8%8A%E6%B5%B7
* URLDecoder.decode("%E4%B8%8A%E6%B5%B7", "UTF-8") --> 上 海
*
* convertUTF8ToString("E4B88AE6B5B7")
* E4B88AE6B5B7 --> 上海
*
* @param s
* @return
*/
public static String convertUTF8ToString(String s) {
if (s == null || s.equals("")) {
return null;
}
try {
s = s.toUpperCase();
int total = s.length() / 2;
int pos = 0;
byte[] buffer = new byte[total];
for (int i = 0; i < total; i++) {
int start = i * 2;
buffer[i] = (byte) Integer.parseInt(
s.substring(start, start + 2), 16);
pos++;
}
return new String(buffer, 0, pos, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
/**
* 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
*
* @param s 原串
* @return
*/
public static String convertStringToUTF8(String s) {
if (s == null || s.equals("")) {
return null;
}
StringBuffer sb = new StringBuffer();
try {
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
b = Character.toString(c).getBytes("utf-8");
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append(Integer.toHexString(k).toUpperCase());
// sb.append("%" +Integer.toHexString(k).toUpperCase());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}
| [
"642751580@qq.com"
] | 642751580@qq.com |
cf8beaddef7af26e48645845cb708db359e48d53 | 7696467a6a09c1076df59a8359ad20bde1c5e930 | /src/ru.lis154/test/java/CalculatorTest.java | 0dd91d9151efdb1abbe7188fe50d50ceff6b2c28 | [] | no_license | lis413/JUnitTest | 9b9a0b0a3fadcf80635656dd9144649add60ed97 | 8218a33896aa80174bd1e32de57c48fb17e577a3 | refs/heads/master | 2023-04-29T03:53:59.047382 | 2021-05-18T19:39:46 | 2021-05-18T19:39:46 | 368,523,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalculatorTest {
@Test
public void evaluatesExpression() {
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(6, sum);
}
} | [
"lis154@mail.ru"
] | lis154@mail.ru |
3d6f0272469e439e5dc9f120141b04e93f0c2b13 | 4c1935a9ddfb93497bb93bce08c645d03b15c90e | /src/SamsungGalaxy/Sample/Sample_Application/BleAnpServer/src/com/samsung/ble/anpserver/SoundManager.java | 4f3e569b568c92a8802ea27e16832a5e6f343496 | [] | no_license | kalpeshkumar412/doFirst | 30962bc35385d347e4c27415d117d65e1804f5f8 | a005aafaf506c8e523e7b74930942ba4d4208d7d | refs/heads/master | 2020-12-30T19:23:31.349880 | 2014-02-09T23:17:26 | 2014-02-09T23:23:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,958 | java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.samsung.ble.anpserver;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.util.Log;
public class SoundManager {
static private SoundManager _instance;
private static SoundPool mSoundPool;
private static AudioManager mAudioManager;
private static Context mContext;
private static int soundId;
private int sound_voulume;
private static final String SOUND_PATH = "/media/audio/ringtones/02_Fog_on_the_water.ogg";
static synchronized public SoundManager getInstance() {
if (_instance == null)
_instance = new SoundManager();
return _instance;
}
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mSoundPool.setOnLoadCompleteListener(new LoadListener());
}
private class LoadListener implements SoundPool.OnLoadCompleteListener {
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
float volFloat = ((float) mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC))
/ mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
if (sound_voulume == 0) {
volFloat = 0;
} else if (sound_voulume == 131072) {
volFloat = 1.0f;
}
Log.e("LoadListener", "Value of Volume " + volFloat);
}
}
public void addSound(int alert_level) {
String filePath = Environment.getRootDirectory() + SOUND_PATH;
sound_voulume = alert_level;
Log.e("SoundManager", "Load Sound :" + filePath);
soundId = mSoundPool.load(filePath, 1);
}
public void releaseSound() {
if (mSoundPool != null)
mSoundPool.release();
}
public void stopSound() {
mSoundPool.stop(soundId);
}
public static void cleanup() {
mSoundPool.release();
mSoundPool = null;
mAudioManager.unloadSoundEffects();
_instance = null;
}
} | [
"sh.haam@gmail.com"
] | sh.haam@gmail.com |
50f08ed4f1513e59cb365df05851dbc452c434e7 | 9e2be4968733c9ae0deb358ce70595e27bf0c554 | /app/src/main/java/com/td/test/topfacts/uicomponents/facts/FactsListAdapter.java | dd80ff7d45af9b1452cfdcb0fb61983ba1f8509c | [] | no_license | TDAndroid/Assignment | 20c59571f2bccdf2ea56e8f5a480a91c3b3a2f77 | aed9aaff4795f06aa6cae7daaeafc36426b06c6c | refs/heads/master | 2020-03-25T16:49:43.143216 | 2018-08-08T02:41:05 | 2018-08-08T02:41:05 | 143,949,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,588 | java | package com.td.test.topfacts.uicomponents.facts;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.td.test.topfacts.R;
import com.td.test.topfacts.repository.database.model.FactsModel;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FactsListAdapter extends RecyclerView.Adapter<FactsListAdapter.FactsViewHolder> {
private List<FactsModel> listFactModel;
public FactsListAdapter(List<FactsModel> listFactsModel) {
this.listFactModel = listFactsModel;
}
public void updateAdapterItems(List<FactsModel> updatedFacts) {
listFactModel = updatedFacts;
notifyDataSetChanged();
}
@NonNull
@Override
public FactsListAdapter.FactsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_facts_list,
viewGroup, false);
return new FactsViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull FactsListAdapter.FactsViewHolder factsViewHolder, int i) {
FactsModel factsModel = listFactModel.get(i);
factsViewHolder.tvHeader.setText(factsModel.getTitle());
factsViewHolder.tvDescription.setText(factsModel.getDescription());
String imageUrl = factsModel.getImageHref();
if (imageUrl == null) {
factsViewHolder.ivFactsImage.setVisibility(View.GONE);
} else {
factsViewHolder.ivFactsImage.setVisibility(View.VISIBLE);
Picasso.get().load(imageUrl)
.placeholder(R.drawable.ic_image_offline)
.error(R.drawable.ic_image_offline)
.fit()
.into(factsViewHolder.ivFactsImage);
}
}
@Override
public int getItemCount() {
return listFactModel.size();
}
public class FactsViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tvFactsHeader)
TextView tvHeader;
@BindView(R.id.tvFactDescription)
TextView tvDescription;
@BindView(R.id.ivFactsImage)
AppCompatImageView ivFactsImage;
public FactsViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
| [
"Thangadurai07@gmail.com"
] | Thangadurai07@gmail.com |
9645c56c6cb55d590e20c42ce78e48090d0d5631 | 9d3d93bb52f052fdc2b9c868b92956d7f81a0c0c | /src/main/java/com/studmat/progs/linkedlist/MergeTwoLists.java | 8d1e22a1014b9edb6e8e7acd195b4ee22ca32f41 | [] | no_license | Komal-Avkash/StudMat | 415b6744b90e6853842b1163e86d0caa997397bb | b1e74230d5356b2598b152dd415d071b7c30570f | refs/heads/master | 2023-06-14T04:58:12.235729 | 2021-06-15T05:59:20 | 2021-06-15T05:59:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,491 | java | package com.studmat.progs.linkedlist;
public class MergeTwoLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode();
ListNode dummy = new ListNode();
dummy.next = head;
if (l1 == null && l2 == null) {
return null;
}
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
head.next = l1;
l1 = l1.next;
} else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
if (l1 != null) {
head.next = l1;
}
if (l2 != null) {
head.next = l2;
}
return dummy.next.next;
}
public static void main(String[] args) {
ListNode l1 = null;//new ListNode(5);
// l1.next = new ListNode(2);
//l1.next.next = new ListNode(4);
//l1.next.next.next = new ListNode(9);
ListNode l2 = null;//new ListNode(1);
//l2.next = new ListNode(3);
// l2.next.next = new ListNode(4);
// l2.next.next.next = new ListNode(4);
// l2.next.next.next.next = new ListNode(5);
l1 = new MergeTwoLists().mergeTwoLists(l1, l2);
while (l1 != null) {
System.out.println(l1.val);
l1 = l1.next;
}
}
}
| [
"35219225+Avkashhirpara@users.noreply.github.com"
] | 35219225+Avkashhirpara@users.noreply.github.com |
e86228e2667a0c66ae3b3e4756a5348eb759d73f | 4e1101cb1c4e71cdc12c74a6480af0d053ec0578 | /backend/src/main/java/edu/hanu/qldt/repository/user/TeacherRepository.java | 3b839498115fd84a84a98d9fac17c40d04d2edad | [] | no_license | Hanu-Homework/qldt | f549ebc1a9e1d91cc4a524689b1990ac11010e8b | b40e82c1e8fc9529a4eee5dc16871e09d5806912 | refs/heads/main | 2023-02-15T12:46:53.356431 | 2021-01-06T16:17:30 | 2021-01-06T16:17:30 | 312,002,627 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 657 | java | package edu.hanu.qldt.repository.user;
import edu.hanu.qldt.model.user.group.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public interface TeacherRepository extends JpaRepository<Teacher, Long> {
@Query(value = "SELECT teacher_id FROM teachers WHERE :teacher_id = id LIMIT 1", nativeQuery = true)
@Transactional
Long GetUserIdByTeacherId(@Param("teacher_id") Long teacher_id);
}
| [
"tangbamiinh@gmail.com"
] | tangbamiinh@gmail.com |
8518db12b0142ac82c7b061982c9cef6ccff1298 | ce3482253d46bfcc0769ea946282aacc21880c76 | /src/test/java/com/lqs/study/growup/spring/aop/SpringAopTest.java | b51c374005ee583aac1fd00f7d8b571c9f6d45b9 | [] | no_license | luqinshun/grow-up | 65d5157763a2e4584681afc03e0f5e21c87f5461 | 9303f02fb99ae1e771bfcd3f83a1bdc7319829da | refs/heads/master | 2020-11-27T04:10:04.140424 | 2020-06-11T04:31:50 | 2020-06-11T04:31:50 | 229,299,125 | 2 | 0 | null | 2019-12-20T16:29:34 | 2019-12-20T16:27:23 | Java | UTF-8 | Java | false | false | 547 | java | package com.lqs.study.growup.spring.aop;
import com.lqs.study.growup.spring.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @program: grow-up
* @description: spring aop 测试类
* @author:luqinshun
* @create: 2019-11-28 11:25
**/
@SpringBootTest
public class SpringAopTest {
@Autowired
private MyService myService;
@Test
public void testAop(){
myService.testService();
}
}
| [
"luqinshun-ds@gome.com.cn"
] | luqinshun-ds@gome.com.cn |
7fd465a1ad92783e03baee1512113923f54c56dd | 804749cc328ac1aede46ba2e0e02f809c17ca6a9 | /xc-edu-service/xc-service-manage-course/src/main/java/com/xuecheng/manage/course/dao/CoursePubRepository.java | d8df37ea4a2f0915fc0b13cf43f6ce7cc8b11c8f | [] | no_license | NeverMoreAndNeverEnd/xuecheng | c77bf1137100a58fd7e3048da7b94f06698bbe30 | f2bcee166e2e33ba21dedbb5f3090d64937a5136 | refs/heads/master | 2022-12-04T10:13:28.389492 | 2020-01-20T11:59:25 | 2020-01-20T11:59:25 | 229,530,809 | 1 | 0 | null | 2022-11-24T06:27:17 | 2019-12-22T07:01:17 | JavaScript | UTF-8 | Java | false | false | 241 | java | package com.xuecheng.manage.course.dao;
import com.xuecheng.framework.domain.course.CoursePub;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CoursePubRepository extends JpaRepository<CoursePub, String> {
}
| [
"15995283349@163.com"
] | 15995283349@163.com |
d67049a856099b1b9771f822b0c0049b63c49e5e | eb301dda211613d4fbe3ab1e5e6f3e8d049c42a2 | /src/main/java/info/navnoire/recipeappserver_springboot/scraper/Scraper.java | 2aa3adb5759ef1e08ce218d5a8eeda71dc2498a1 | [] | no_license | navnoire/RecipeApp_backend | 277df7ba66de139d4402f4bcb8f39113393faf21 | f9c607202e789c1208d584bb00ad519c8c444f30 | refs/heads/master | 2023-06-09T20:09:40.413596 | 2021-06-23T17:09:34 | 2021-06-23T17:09:34 | 368,867,272 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 916 | java | package info.navnoire.recipeappserver_springboot.scraper;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public interface Scraper {
Logger LOG = LoggerFactory.getLogger(Scraper.class);
default Document getDocument(String url) throws IOException {
Connection connection = Jsoup.connect(url);
Document document;
document = connection.get();
return document;
}
default Integer extractId(String string) {
string = string.replace("https://gotovim-doma.ru/", "");
int index = string.indexOf('-');
if (index != -1) string = string.substring(0, index);
try {
return Integer.parseInt(string.replaceAll("[^0-9]", ""));
} catch (NumberFormatException nfe) {
return 0;
}
}
}
| [
"navna3@gmail.com"
] | navna3@gmail.com |
5a98d0118a62da4be7cde12749d44eccb827eb71 | ea08c396406002ee1317a07f9cedacb1d0d56604 | /src/main/java/com/warlodya/telegavladimirbot/services/AuthorNameService.java | 41a88077c840cc9e18d64524c9e61ebd36fecfac | [
"MIT"
] | permissive | oskov/TelegramVladimirLv_bot | 0e61871ee171855b19f8685b01b080927a4793b4 | 62bf021fe7c85e9f9a36b1ca0593af1652eebc32 | refs/heads/master | 2021-04-08T16:54:13.104600 | 2020-09-13T14:35:01 | 2020-09-13T14:35:01 | 248,791,997 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 942 | java | package com.warlodya.telegavladimirbot.services;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.telegram.abilitybots.api.objects.MessageContext;
import org.telegram.telegrambots.meta.api.objects.User;
@Component
@Scope
public class AuthorNameService {
public String getAuthorName(MessageContext context) {
return getAuthorName(context.user());
}
public String getAuthorName(User user) {
String fName = user.getFirstName();
String lName = user.getLastName();
String userName = user.getUserName();
String authorName;
if (userName != null) {
authorName = '@' + userName;
} else {
String firstName = fName != null ? fName : "";
String lastName = lName != null ? lName : "";
authorName = firstName + " " + lastName;
}
return authorName;
}
}
| [
"faklosg@gmail.com"
] | faklosg@gmail.com |
4d61d0e1ee2ab03f6eac5b8b46e88ce88a5983f1 | 2accecaaae3324dd0e99b4bde8d3b765fee99ccc | /ejbModule/com/shorturl/ejb/interfaces/ShortUrlBeanLocal.java | 7fbc218914ea57221efd41bdb632bbbfcf8e7ea2 | [] | no_license | pradeepsixer/ShortUrlEjb | b7208ff52e27baf83ae294a9884acbc0651194ae | 3637e4d5e57c2a11e0b1c8f0c7bc373038c3160f | refs/heads/master | 2020-07-14T01:30:21.511712 | 2016-04-30T15:06:02 | 2016-04-30T15:06:02 | 66,121,211 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,332 | java | /**
*
*/
package com.shorturl.ejb.interfaces;
import com.shorturl.datamodel.ShortUrlDetails;
/**
* Local Interface for Short URL Bean
* @author Pradeep Kumar
*/
public interface ShortUrlBeanLocal {
public static final String JNDI_NAME = "java:global/ShortUrlEar/ShortUrlEjb/ShortUrlBean!com.shorturl.ejb.interfaces.ShortUrlBeanLocal";
/**
* Create or Update the link details
* @param linkDetails {@link ShortUrlDetails Short URL Details}
*/
public ShortUrlDetails addOrUpdateShortUrlDetails(final ShortUrlDetails linkDetails);
/**
* Get the {@link ShortUrlDetails Short URL Details} for the given Short URL
* @param shortUrl Short URL
* @return {@link ShortUrlDetails Short URL Details}
*/
public ShortUrlDetails getShortUrlDetails(final String shortUrl);
/**
* Increment the View Count for Short Url
* <b>Note:</b> The caller of this method is responsible for synchronization.
* @param shortUrl The Short Url for which the view count should be incremented.
*/
public void incrementViewCount(final String shortUrl);
/**
* Increment the Click Count for Short Url
* <b>Note:</b> The caller of this method is responsible for synchronization.
* @param shortUrl The Short Url for which the click count should be incremented.
*/
public void incrementClickCount(final String shortUrl);
}
| [
"pradeepsixer@gmail.com"
] | pradeepsixer@gmail.com |
a0a678035438d7c5262d7d294b655d033dc8c259 | 9bed5688c7132eeea77bfe2064d9402774795605 | /src/main/java/com/loginRegister/loginRegister/registration/RegistrationService.java | 5daf7043b07dba9056a8b30ec056ec0f86f67730 | [] | no_license | JustCreature/loginRegister | 261e44d105d736b46824308268a8a9cada0860a0 | e15e6243c80a69420a2c6ce4c55c8563a144973d | refs/heads/master | 2023-04-19T05:36:14.210180 | 2021-05-07T09:38:12 | 2021-05-07T09:39:36 | 365,184,928 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,444 | java | package com.loginRegister.loginRegister.registration;
import com.loginRegister.loginRegister.appuser.AppUser;
import com.loginRegister.loginRegister.appuser.AppUserRole;
import com.loginRegister.loginRegister.appuser.AppUserService;
import com.loginRegister.loginRegister.email.EmailSender;
import com.loginRegister.loginRegister.registration.token.ConfirmationToken;
import com.loginRegister.loginRegister.registration.token.ConfirmationTokenService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
@Service
@AllArgsConstructor
public class RegistrationService {
private final AppUserService appUserService;
private EmailValidator emailValidator;
private ConfirmationTokenService confirmationTokenService;
private final EmailSender emailSender;
public String register(RegistrationRequest request) {
boolean isValidEmail = emailValidator.test(request.getEmail());
if (!isValidEmail) {
throw new IllegalStateException("email not valid");
}
String token = appUserService.signUpUser(
new AppUser(
request.getFirstName(),
request.getLastName(),
request.getEmail(),
request.getPassword(),
AppUserRole.USER
)
);
String link = "http://localhost:8080/api/v1/registration/confirm?token=" + token;
emailSender.send(request.getEmail(),
buildEmail(request.getFirstName(), link));
return token;
}
@Transactional
public String confirmToken(String token) {
ConfirmationToken confirmationToken = confirmationTokenService
.getToken(token)
.orElseThrow(() -> new IllegalStateException("token not found"));
if (confirmationToken.getConfirmedAt() != null) {
throw new IllegalStateException("email already confirmed");
}
LocalDateTime expiderAt = confirmationToken.getExpiresAt();
if (expiderAt.isBefore(LocalDateTime.now())) {
throw new IllegalStateException("token expired");
}
confirmationTokenService.setConfirmedAt(token);
appUserService.enableAppUser(confirmationToken.getAppUser().getEmail());
return "confirmed";
}
private String buildEmail(String name, String link) {
return "<div style=\"font-family:Helvetica,Arial,sans-serif;font-size:16px;margin:0;color:#0b0c0c\">\n" +
"\n" +
"<span style=\"display:none;font-size:1px;color:#fff;max-height:0\"></span>\n" +
"\n" +
" <table role=\"presentation\" width=\"100%\" style=\"border-collapse:collapse;min-width:100%;width:100%!important\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n" +
" <tbody><tr>\n" +
" <td width=\"100%\" height=\"53\" bgcolor=\"#0b0c0c\">\n" +
" \n" +
" <table role=\"presentation\" width=\"100%\" style=\"border-collapse:collapse;max-width:580px\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" align=\"center\">\n" +
" <tbody><tr>\n" +
" <td width=\"70\" bgcolor=\"#0b0c0c\" valign=\"middle\">\n" +
" <table role=\"presentation\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"border-collapse:collapse\">\n" +
" <tbody><tr>\n" +
" <td style=\"padding-left:10px\">\n" +
" \n" +
" </td>\n" +
" <td style=\"font-size:28px;line-height:1.315789474;Margin-top:4px;padding-left:10px\">\n" +
" <span style=\"font-family:Helvetica,Arial,sans-serif;font-weight:700;color:#ffffff;text-decoration:none;vertical-align:top;display:inline-block\">Confirm your email</span>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody></table>\n" +
" </a>\n" +
" </td>\n" +
" </tr>\n" +
" </tbody></table>\n" +
" \n" +
" </td>\n" +
" </tr>\n" +
" </tbody></table>\n" +
" <table role=\"presentation\" class=\"m_-6186904992287805515content\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"border-collapse:collapse;max-width:580px;width:100%!important\" width=\"100%\">\n" +
" <tbody><tr>\n" +
" <td width=\"10\" height=\"10\" valign=\"middle\"></td>\n" +
" <td>\n" +
" \n" +
" <table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"border-collapse:collapse\">\n" +
" <tbody><tr>\n" +
" <td bgcolor=\"#1D70B8\" width=\"100%\" height=\"10\"></td>\n" +
" </tr>\n" +
" </tbody></table>\n" +
" \n" +
" </td>\n" +
" <td width=\"10\" valign=\"middle\" height=\"10\"></td>\n" +
" </tr>\n" +
" </tbody></table>\n" +
"\n" +
"\n" +
"\n" +
" <table role=\"presentation\" class=\"m_-6186904992287805515content\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"border-collapse:collapse;max-width:580px;width:100%!important\" width=\"100%\">\n" +
" <tbody><tr>\n" +
" <td height=\"30\"><br></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td width=\"10\" valign=\"middle\"><br></td>\n" +
" <td style=\"font-family:Helvetica,Arial,sans-serif;font-size:19px;line-height:1.315789474;max-width:560px\">\n" +
" \n" +
" <p style=\"Margin:0 0 20px 0;font-size:19px;line-height:25px;color:#0b0c0c\">Hi " + name + ",</p><p style=\"Margin:0 0 20px 0;font-size:19px;line-height:25px;color:#0b0c0c\"> Thank you for registering. Please click on the below link to activate your account: </p><blockquote style=\"Margin:0 0 20px 0;border-left:10px solid #b1b4b6;padding:15px 0 0.1px 15px;font-size:19px;line-height:25px\"><p style=\"Margin:0 0 20px 0;font-size:19px;line-height:25px;color:#0b0c0c\"> <a href=\"" + link + "\">Activate Now</a> </p></blockquote>\n Link will expire in 15 minutes. <p>See you soon</p>" +
" \n" +
" </td>\n" +
" <td width=\"10\" valign=\"middle\"><br></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td height=\"30\"><br></td>\n" +
" </tr>\n" +
" </tbody></table><div class=\"yj6qo\"></div><div class=\"adL\">\n" +
"\n" +
"</div></div>";
}
}
| [
"shaxx96@mail.ru"
] | shaxx96@mail.ru |
a3b21b6bb9d01c2766e35704c608e5811710d484 | 94a01b8d04be38e10bbcf04a3eb5e7affb1577a7 | /app/src/main/java/com/example/sonata/recipecollection/stepsItems.java | f9b4a161120a3f87f31c55035feb4063a1714d39 | [] | no_license | UFaded/RecipeCollection | ae81bc1866287c33539ac73382013b2a8c3e127b | 8332ce1974e4a16d2405046674bbd710265cea14 | refs/heads/master | 2020-04-03T19:29:08.731074 | 2018-10-31T08:41:45 | 2018-10-31T08:41:45 | 155,524,701 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package com.example.sonata.recipecollection;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class stepsItems extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_steps_items);
}
}
| [
"627608654@qq.com"
] | 627608654@qq.com |
c2fc8d6811ab8892673ec7379df957dbc0552b30 | 1bbf972a15b382bb81a619c70188dca18b827292 | /src/main/java/com/manzhizhen/activemq/broker/TopicTest.java | c3055fa2ba4e5a5f18cb63c961f704d8a716d17e | [] | no_license | justfordream/mzz-activemq-study | 8f8e9372c943176c0b007b9fad9db0b0a720f3b5 | dad5c615a4bc59379f35735b2fef01bd8404745a | refs/heads/master | 2016-09-06T19:30:16.281878 | 2015-09-14T07:07:37 | 2015-09-14T07:07:37 | 42,431,865 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,046 | java | /**
*
*/
package com.manzhizhen.activemq.broker;
import java.util.concurrent.CountDownLatch;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
* @author Manzhizhen
*
*/
public class TopicTest {
public static void main(String[] args) {
createTopic();
}
private static void createTopic() {
try {
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61617");
ConnectionFactory factory1 = new ActiveMQConnectionFactory("tcp://localhost:61618");
Connection connection1 = factory1.createConnection();
Connection connection = factory.createConnection();
connection.setClientID("我爱你");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue topic = session.createQueue("TopicTestQueue1");
Queue topic1 = session1.createQueue("TopicTestQueue1");
final MessageConsumer consumer = session.createConsumer(topic);
// final MessageConsumer durableConsumer = session.createDurableSubscriber(topic, "我是持久化订阅者");
// final MessageConsumer durableConsumer1 = session.createDurableSubscriber(topic, "我是持久化订阅者2");
// final MessageConsumer durableConsumer = session.createConsumer(topic);
// final MessageConsumer durableConsumer1 = session.createConsumer(topic);
final MessageConsumer durableConsumer2 = session1.createConsumer(topic1);
final MessageConsumer durableConsumer3 = session1.createConsumer(topic1);
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
System.out.println("consumer 接收到:" + ((TextMessage)consumer.receive()).getText());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
System.out.println("durableConsumer2 接收到:" + ((TextMessage)durableConsumer2.receive()).getText());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
System.out.println("durableConsumer3 接收到:" + ((TextMessage)durableConsumer3.receive()).getText());
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}).start();
connection.start();
connection1.start();
System.out.println("消费者创建完毕!");
CountDownLatch latch = new CountDownLatch(1);
latch.await();
} catch (JMSException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者程序结束!");
}
}
| [
"2323173088@qq.com"
] | 2323173088@qq.com |
af81695fee8e3f1ac15e7e967baf32c643029488 | 1b15fe5acedc014df2e0ae108a4c929dccf0911d | /src/main/java/com/turk/util/opencsv/CSVWriter.java | a9e46e6f650f6e832e0f922348790eb28d6a15af | [] | no_license | feinzaghi/Capricorn | 9fb9593828e4447a9735079bad6b440014f322b3 | e1fca2926b1842577941b070a826a2448739a2e8 | refs/heads/master | 2020-06-14T11:43:29.627233 | 2017-01-24T03:19:28 | 2017-01-24T03:19:28 | 75,029,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,973 | java | package com.turk.util.opencsv;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class CSVWriter
implements Closeable
{
public static final int INITIAL_STRING_SIZE = 128;
private Writer rawWriter;
private PrintWriter pw;
private char separator;
private char quotechar;
private char escapechar;
private String lineEnd;
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char NO_QUOTE_CHARACTER = '\000';
public static final char NO_ESCAPE_CHARACTER = '\000';
public static final String DEFAULT_LINE_END = "\n";
private ResultSetHelper resultService = new ResultSetHelperService();
public CSVWriter(Writer writer)
{
this(writer, ',');
}
public CSVWriter(Writer writer, char separator)
{
this(writer, separator, '"');
}
public CSVWriter(Writer writer, char separator, char quotechar)
{
this(writer, separator, quotechar, '"');
}
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar)
{
this(writer, separator, quotechar, escapechar, "\n");
}
public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd)
{
this(writer, separator, quotechar, '"', lineEnd);
}
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd)
{
this.rawWriter = writer;
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
public void writeAll(List<String[]> allLines)
{
for (String[] line : allLines)
writeNext(line);
}
protected void writeColumnNames(ResultSet rs)
throws SQLException
{
writeNext(this.resultService.getColumnNames(rs));
}
public void writeAll(ResultSet rs, boolean includeColumnNames)
throws SQLException, IOException
{
if (includeColumnNames) {
writeColumnNames(rs);
}
while (rs.next())
{
writeNext(this.resultService.getColumnValues(rs));
}
}
public void writeNext(String[] nextLine)
{
if (nextLine == null) {
return;
}
StringBuilder sb = new StringBuilder(128);
for (int i = 0; i < nextLine.length; i++)
{
if (i != 0) {
sb.append(this.separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (this.quotechar != 0) {
sb.append(this.quotechar);
}
sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement);
if (this.quotechar != 0) {
sb.append(this.quotechar);
}
}
sb.append(this.lineEnd);
this.pw.write(sb.toString());
}
private boolean stringContainsSpecialCharacters(String line)
{
return (line.indexOf(this.quotechar) != -1) || (line.indexOf(this.escapechar) != -1);
}
protected StringBuilder processLine(String nextElement)
{
StringBuilder sb = new StringBuilder(128);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if ((this.escapechar != 0) && (nextChar == this.quotechar))
sb.append(this.escapechar).append(nextChar);
else if ((this.escapechar != 0) && (nextChar == this.escapechar))
sb.append(this.escapechar).append(nextChar);
else {
sb.append(nextChar);
}
}
return sb;
}
public void flush()
throws IOException
{
this.pw.flush();
}
public void close()
throws IOException
{
flush();
this.pw.close();
this.rawWriter.close();
}
public boolean checkError()
{
return this.pw.checkError();
}
public void setResultService(ResultSetHelper resultService) {
this.resultService = resultService;
}
} | [
"huangxiao227@gmail.com"
] | huangxiao227@gmail.com |
7580087d7d5f274278c6ec4f4745a0b659c988f4 | 7ab0da8a85679309be0f17ed0204a0af552b82b3 | /com/states/PlayState.java | 74db38134e5e5a8eccf6e7bef4cceb884542b630 | [] | no_license | lucasmoura/cs4303---game | de62f292801b054f6b9abd6e0e120a8c4ddc2d29 | b62ef71577d6d7b6312042dfa3f997296e1b0d28 | refs/heads/master | 2020-12-25T23:37:39.223720 | 2014-11-16T06:00:05 | 2014-11-16T06:00:05 | 26,605,692 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,780 | java | package com.states;
import java.util.ArrayList;
import java.util.Iterator;
import com.engine.Button;
import com.engine.GameObject;
import com.engine.Processing;
import com.engine.QuadTree;
import com.game.AdmiralShip;
import com.game.DestructableObject;
import com.game.EnemyBulletPool;
import com.game.EnemySpawn;
import com.game.Starfield;
import com.game.Enemy;
import com.game.PlayHUD;
import processing.core.PApplet;
public class PlayState implements GameState
{
private Starfield starfield;
private ArrayList<GameObject> playObjects;
private ArrayList<DestructableObject> enemies;
private EnemySpawn spawn;
private final String playID = "PLAY";
private Button leftButton;
private Button rightButton;
private AdmiralShip admiralShip;
private QuadTree quadTree;
private PlayHUD playHUD;
@Override
public void update()
{
handleQuadTree();
int score = 0;
for (Iterator<DestructableObject> iterator = enemies.iterator(); iterator.hasNext();)
{
DestructableObject object = iterator.next();
if (!((Enemy) object).isAlive())
{
score += object.getPoints();
iterator.remove();
}
else
object.update();
}
starfield.update();
enemies.addAll(spawn.spawn(enemies.size()));
if(rightButton.isPressed())
admiralShip.moveRight();
else if(leftButton.isPressed())
admiralShip.moveLeft();
EnemyBulletPool.getInstance().update();
admiralShip.update();
playHUD.update(admiralShip.getHealth(), score);
}
@Override
public void render()
{
starfield.drawObject();
admiralShip.drawObject();
for(DestructableObject enemy: enemies)
enemy.drawObject();
for(GameObject object: playObjects)
object.drawObject();
for(DestructableObject bullet: EnemyBulletPool.getInstance().getPool())
bullet.drawObject();
playHUD.drawObject();
}
@Override
public boolean onEnter()
{
PApplet applet = Processing.getInstance().getParent();
playObjects = new ArrayList<GameObject>();
enemies = new ArrayList<DestructableObject>();
spawn = new EnemySpawn();
//GameObject kodan = EnemyFactory.getInstance().createEnemy(Enemy.KODANCWCH);
starfield = new Starfield(20);
//System.out.println("Starfield ready");
rightButton = new Button(0, 0, "rightMove.png", "rightMove", 1, false);
int rightx = applet.width - rightButton.getWidth();
int righty = applet.height - rightButton.getHeight();
rightButton.setX(rightx);
rightButton.setY(righty);
leftButton = new Button(0, 0, "leftMove.png", "leftMove", 1, false);
int leftx = 0;
int lefty = applet.height - leftButton.getHeight();
leftButton.setX(leftx);
leftButton.setY(lefty);
admiralShip = new AdmiralShip(0, 0, 0, 0, "admiralship.png",
"admiralship", 1);
int shipx = applet.width/2 - admiralShip.getWidth()/2;
int shipy = applet.height - admiralShip.getHeight();
admiralShip.setX(shipx);
admiralShip.setY(shipy);
admiralShip.setDamageDealt(1000);
admiralShip.setHealth(100);
playHUD = new PlayHUD();
playHUD.init();
quadTree = new QuadTree(0, 0, 0, applet.width, applet.height);
playObjects.add(leftButton);
playObjects.add(rightButton);
//enemies.add(kodan);
return true;
}
@Override
public boolean onExit()
{
leftButton.clean();
rightButton.clean();
starfield = null;
return true;
}
private void detectCollision()
{
ArrayList<DestructableObject> objects = new ArrayList<DestructableObject>();
ArrayList<DestructableObject> collision = new ArrayList<DestructableObject>();
quadTree.getAllObjects(objects);
for (int x = 0, len = objects.size(); x < len; x++)
{
collision.clear();
quadTree.retrieve(collision, objects.get(x));
for (int y = 0, length = collision.size(); y < length; y++)
{
if ( objects.get(x).isCollidableWith(collision.get(y)) &&
objects.get(x).getX() < collision.get(y).getX() + collision.get(y).getWidth() &&
objects.get(x).getX() + objects.get(x).getWidth() > collision.get(y).getX() &&
objects.get(x).getY() < collision.get(y).getY() + collision.get(y).getHeight() &&
objects.get(x).getY() + objects.get(x).getHeight() > collision.get(y).getY())
{
objects.get(x).setColliding(true, collision.get(y).getDamageDealt());
collision.get(y).setColliding(true, objects.get(x).getDamageDealt());
}
}
}
}
private void handleQuadTree()
{
quadTree.clear();
for(int i =0; i<enemies.size(); i++)
quadTree.insert(enemies.get(i));
quadTree.insert(admiralShip);
ArrayList<DestructableObject> bullets = admiralShip.getBulletPool().getPool();
bullets.addAll(EnemyBulletPool.getInstance().getPool());
for(int i =0; i<bullets.size(); i++)
quadTree.insert(bullets.get(i));
detectCollision();
}
@Override
public void enable() {
// TODO Auto-generated method stub
}
@Override
public void disable() {
// TODO Auto-generated method stub
}
public void mouseReleased(int x, int y)
{
leftButton.setPressed(false);
rightButton.setPressed(false);
}
public void mousePressed(int x, int y)
{
if(leftButton.touchOnMe(x, y))
{
//System.out.println("Left pressed");
if (leftButton.isPressed()==false)
{
leftButton.setPressed(true);
rightButton.setPressed(false);
}
}
else
{
leftButton.setPressed(false);
}
if(rightButton.touchOnMe(x, y))
{
//System.out.println("Right pressed");
if (rightButton.isPressed()==false)
{
rightButton.setPressed(true);
leftButton.setPressed(false);
}
}
else
{
rightButton.setPressed(false);
}
}
@Override
public String getStateId()
{
return playID;
}
}
| [
"lucas.moura128@gmail.com"
] | lucas.moura128@gmail.com |
7bb173127e928f114bf215055eadedb9d2c9d23d | 4a68a3afeb5b56cdfb5d84974347f51f5eca5d09 | /src/main/java/study/designpattern/composite/iterator/MenuComponent.java | 8925329b10bf02964b4001190cb65576cdb4317a | [] | no_license | luvram/design-pattern-study | 9bbddb2a2ed84806ac2852086657458b8a8245c9 | f50932876be877c8d57306c50a63fc57d3a6b019 | refs/heads/master | 2023-04-15T10:47:28.106438 | 2021-04-20T13:31:35 | 2021-04-20T13:31:35 | 352,915,657 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 877 | java | package study.designpattern.composite.iterator;
import java.util.Iterator;
public abstract class MenuComponent {
public void add(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public void remove(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public MenuComponent getChild(int i) {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public String getDescription() {
throw new UnsupportedOperationException();
}
public double getPrice() {
throw new UnsupportedOperationException();
}
public boolean isVegetarian() {
throw new UnsupportedOperationException();
}
public void print() {
throw new UnsupportedOperationException();
}
public Iterator createIterator() {
throw new UnsupportedOperationException();
}
}
| [
"sahul0804@gmail.com"
] | sahul0804@gmail.com |
9f40f6e3b74ca9e098437c1c3a90c75cec55c620 | e495b45be7390e714fff0514f31083c6482c6220 | /src/main/java/com/oracle/java/App.java | 8e45ebf3713a033e4d45108514cf8967d81fcb49 | [] | no_license | tgvdinesh/java | a853b135e0c633adb13f7b846b1b91de2c01f6f4 | 5e596a3cb6674a42e2d5adb3deeeeccec60fe04c | refs/heads/master | 2021-06-08T09:17:24.227617 | 2016-11-11T05:26:40 | 2016-11-11T05:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,431 | java | package com.oracle.java;
import java.util.*;
/**
* Data Structures
*/
public class App {
public static void main(String[] args) {
System.out.println("List of Data Structures");
/* 1. Primitive Data Type */
int i = 10;
long l = 50;
short sh = 4;
byte by = 'x';
float f = 20.0f;
boolean b = false;
String s = "Character sequence";
char c = 'a';
Integer integer = new Integer(4);
/* 2. Composite Data Structure / Non primitive Data Type */
int[] array = new int[5];
int[] intArray = new int[]{4, 5, 6, 3};
Arrays.stream(intArray).forEach(System.out::println);
/* 3. Abstract Data Type */
/* 3.1 List */
List arrayList = new ArrayList();
arrayList.add(new Integer(1));
arrayList.add(new Float(5.5));
arrayList.add(new String("Dinesh"));
arrayList.add(new Character('a'));
System.out.println(arrayList.size());
arrayList.forEach(player -> System.out.println(player));
List genericArrayList = new ArrayList<String>();
genericArrayList.add("Test");
genericArrayList.add("What?");
genericArrayList.forEach(System.out::println);
List<String> linkedList = new LinkedList<String>();
/* 3.2 Stack */
Stack<String> stack = new Stack<String>();
/* 3.3 Queue */
}
}
| [
"dinesh-v@users.noreply.github.com"
] | dinesh-v@users.noreply.github.com |
f19ad7539929a95b823455028754944f7ff11fa5 | c843a2cfea19ebf831d40e6c6df01b6f9e5b9539 | /app/src/main/java/com/i550/photogallery/StartupReceiver.java | 2f3dd91c7eeba69177dcdd6548066b615ae34fb7 | [] | no_license | AndSky90/PhotoGallery | 181b21fb8cd70119f8e049f6a08c0b4ad0c361ef | bc1a9f68cc49aeb79cb282fe3ffc46fc305142c3 | refs/heads/master | 2021-04-15T04:47:21.152829 | 2018-04-04T16:04:58 | 2018-04-04T16:04:58 | 126,783,751 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 639 | java | package com.i550.photogallery;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class StartupReceiver extends BroadcastReceiver {
private static final String TAG = "StartupReceiver";
@Override
public void onReceive(Context context, Intent intent) { //выполняется при получении бродбанда, и процесс умирает
Log.i(TAG, "Received broadcast intent: " + intent.getAction());
boolean isOn = QueryPreferences.isAlarmOn(context);
PollService.setServiceAlarm(context,isOn);
}
}
| [
"andsky90@gmail.com"
] | andsky90@gmail.com |
6ff13b6a5cd1c77d6caaffae7211d6b4b67aa712 | cbf3a435f2c806f91202d254bf478dcf6ebdef3d | /src/main/java/com/kodilla/kalkulator/Calculator.java | aac9aab7e06ff45fab1032774ceb41dfd311f05a | [] | no_license | lukgrz/kalkulator | f022493a0a00378503f8b4525d07bfc208f50897 | 4db99bf76fc6e161082f8d7cbd735560db7267f4 | refs/heads/main | 2023-04-04T19:35:52.065715 | 2021-03-29T21:49:01 | 2021-03-29T21:49:01 | 352,784,476 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package com.kodilla.kalkulator;
public class Calculator {
int a;
int b;
public Calculator (int a, int b) {
this.a = a;
this.b = b;
}
public void addAToB () {
System.out.println("Wynik dodawania to "+(a+b));
}
public void multiplyAAndB (){
System.out.println("Wynik mnożenia to "+(a*b));
}
}
| [
"lukaszgrzegorzak@gmail.com"
] | lukaszgrzegorzak@gmail.com |
48128c8efefb8fbcb08263748e932b9a40baa2e5 | b52aa1187d06216e5cae0fa314c7d87c5f06c9e2 | /src/main/java/me/slaps/DMWrapper/DMWrapperPluginListener.java | fe81daef4d204e66812027dd51c6d94153b334d7 | [] | no_license | GoalieGuy6/DMWrapper | d3dbbbb7a0173f6e09604ad03b33f2509056c0b6 | 2274758d53df7c4abd078838deaaaad16edba014 | refs/heads/master | 2021-01-20T20:18:29.670396 | 2011-07-07T09:43:52 | 2011-07-07T09:43:52 | 1,998,931 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,721 | java | package me.slaps.DMWrapper;
import com.gmail.haloinverse.DynamicMarket.DynamicMarket;
import com.gmail.haloinverse.DynamicMarket.DynamicMarketAPI;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerListener;
import org.bukkit.plugin.PluginManager;
public class DMWrapperPluginListener extends ServerListener {
private DMWrapper plugin;
private String dmName = "DynamicMarket";
private String wgName = "WorldGuard";
public DMWrapperPluginListener(DMWrapper instance) {
this.plugin = instance;
}
@Override
public void onPluginDisable(PluginDisableEvent event) {
if (event.getPlugin().getDescription().getName().equals(dmName)) {
plugin.setAPI(null);
}
plugin.disable();
}
@Override
public void onPluginEnable(PluginEnableEvent event) {
if (event.getPlugin().getDescription().getName().equals(dmName)) {
hookDM((DynamicMarket) event.getPlugin());
}
if (event.getPlugin().getDescription().getName().equals(wgName)) {
setWG((WorldGuardPlugin) event.getPlugin());
}
}
private void setWG(WorldGuardPlugin wg) {
plugin.setWG(wg);
}
public void checkPlugins(PluginManager pm) {
if (pm.getPlugin(dmName).isEnabled() && plugin.getAPI() == null) {
hookDM((DynamicMarket) pm.getPlugin("DynamicMarket"));
}
if (pm.getPlugin(wgName) != null && plugin.getWG() == null) {
if (pm.getPlugin(wgName).isEnabled()) {
setWG((WorldGuardPlugin) pm.getPlugin("WorldGuard"));
}
}
}
private void hookDM(DynamicMarket dm) {
DynamicMarketAPI api = dm.getAPI();
plugin.setAPI((DynamicMarketAPI) api);
plugin.hookAPI();
}
} | [
"l.mikelonis@yahoo.com"
] | l.mikelonis@yahoo.com |
b6c39518884d27cc4d26061437bc617516f21012 | e28f34ccf434650e80d7a22eec051f64f354f83a | /src/main/java/com/examples/one/petstore/puppy.java | 41ae93179b17c8fd45983eb867351e33fa8247e6 | [] | no_license | angieann/Tutorial3 | a16f57f328acaf0d567a96c199619d585b699699 | 45b2c8d838245e07296dd6c2fbfb6564f7020f16 | refs/heads/master | 2021-01-10T13:50:07.925528 | 2016-03-14T23:39:57 | 2016-03-14T23:39:57 | 53,835,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,670 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.examples.one.petstore;
import java.util.Arrays;
/**
*
* @author userElise
*/
public class puppy {
int id;
String name;
String breed ;
boolean loudBark;
int exerciseRequiredPerDay;
boolean friendlyWithChildren;
public puppy(int id, String name, String breed) throws IncorrectBreedException{
try{
if(!(breed.equals("Labrador")) & !(breed.equals("Doberman")) & !(breed.equals("Pitbull")))
throw new IncorrectBreedException();
}catch(IncorrectBreedException ex){
throw ex;
}
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setBreed(String breed){
this.breed = breed;
}
public String getBreed(){
return breed;
}
public void setExercise(int exerciseRequiredPerDay) throws notEnoughExerciseExcepetion{
this.exerciseRequiredPerDay = exerciseRequiredPerDay;
try{
if (exerciseRequiredPerDay<0 | exerciseRequiredPerDay>4)
throw new notEnoughExerciseExcepetion();
}catch(notEnoughExerciseExcepetion ex){
throw ex;
}
}
public int getExercise(){
return exerciseRequiredPerDay;
}
}
| [
"elise.gabrielle@hotmail.com"
] | elise.gabrielle@hotmail.com |
a8515b84b38fb0ebff3963d138cb3c7b548cbfd0 | fe935324a99a68eb1594a38108030e8abc45247b | /src/main/java/bank/Main.java | e785b78d414c8491f02a94e90e17431b8759d3a8 | [] | no_license | elyasaad/Bank_Demo | fbf94b56305b68466d472227a4f51bc013e8cd32 | 05b40b5ae9030f8d1fe3c495523e1cca15a3df44 | refs/heads/master | 2022-12-30T08:23:44.551695 | 2020-04-11T10:05:02 | 2020-04-11T10:05:02 | 254,840,010 | 0 | 0 | null | 2020-10-13T21:06:04 | 2020-04-11T10:05:43 | Java | UTF-8 | Java | false | false | 556 | java | package bank;
import bank.customer.PhysicalPerson;
import bank.exception.BankAccountException;
public class Main {
public static void main(String[] args) throws BankAccountException {
PhysicalPerson ph_p = new PhysicalPerson("0001", "adress 1", "saad", "saad2");
BankAccount ba = new BankAccount(ph_p);
System.out.println("Initial balance: " + ba.getBalance());
ba.makeDeposit(10.55);
ba.makeDeposit(10);
ba.makeWithdrawal(5);
System.out.println("balance: " + ba.getBalance());
System.out.println(ba.printTransactions());
}
}
| [
"elyasaad@gmail.com"
] | elyasaad@gmail.com |
f7f8e67f3e8a9e0b0dc7a8110c6fa27e24fce95e | 2f4a058ab684068be5af77fea0bf07665b675ac0 | /app/com/facebook/feed/data/ProfileMutator.java | 74b2f56f193d07645a8071043f7444f96c4a0593 | [] | no_license | cengizgoren/facebook_apk_crack | ee812a57c746df3c28fb1f9263ae77190f08d8d2 | a112d30542b9f0bfcf17de0b3a09c6e6cfe1273b | refs/heads/master | 2021-05-26T14:44:04.092474 | 2013-01-16T08:39:00 | 2013-01-16T08:39:00 | 8,321,708 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,009 | java | package com.facebook.feed.data;
import com.facebook.graphql.model.GraphQLObjectType;
import com.facebook.graphql.model.GraphQLObjectType.ObjectType;
import com.facebook.graphql.model.GraphQLProfile;
import com.facebook.graphql.model.GraphQLProfile.Builder;
import com.google.common.base.Preconditions;
public class ProfileMutator
{
public GraphQLProfile a(GraphQLProfile paramGraphQLProfile)
{
Preconditions.checkArgument(GraphQLObjectType.ObjectType.Page.equals(paramGraphQLProfile.objectType.a()), "Cannot like a profile that is not a page.");
if (!paramGraphQLProfile.doesViewerLike);
for (boolean bool = true; ; bool = false)
{
GraphQLProfile.Builder localBuilder = new GraphQLProfile.Builder().a(paramGraphQLProfile);
localBuilder.a(bool);
return localBuilder.b();
}
}
}
/* Location: /data1/software/jd-gui/com.facebook.katana_2.0_liqucn.com-dex2jar.jar
* Qualified Name: com.facebook.feed.data.ProfileMutator
* JD-Core Version: 0.6.0
*/ | [
"macluz@msn.com"
] | macluz@msn.com |
27a280cf99faab6cfb21768d1ccd31735e9fa3ba | e5c9bf1c789e7f20130410ab01b3e42d9a3c95ab | /app/build/generated/ap_generated_sources/debug/out/com/komiut/conductor/db/AppDatabase_Impl.java | 5f8872dbf1556ec12c9beec27be125f530ecd272 | [] | no_license | KomiutSystems/conductor-application | 389bfcf6008f410294a9b52a31f9011dea8efb39 | 554a5206455785b93e086adce914f50135ee3866 | refs/heads/main | 2023-03-08T09:06:18.271203 | 2021-02-26T13:27:16 | 2021-02-26T13:27:16 | 342,521,289 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,896 | java | package com.komiut.conductor.db;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.RoomOpenHelper;
import androidx.room.RoomOpenHelper.Delegate;
import androidx.room.RoomOpenHelper.ValidationResult;
import androidx.room.util.DBUtil;
import androidx.room.util.TableInfo;
import androidx.room.util.TableInfo.Column;
import androidx.room.util.TableInfo.ForeignKey;
import androidx.room.util.TableInfo.Index;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
import androidx.sqlite.db.SupportSQLiteOpenHelper.Callback;
import androidx.sqlite.db.SupportSQLiteOpenHelper.Configuration;
import com.komiut.conductor.dao.CashTransactionDao;
import com.komiut.conductor.dao.CashTransactionDao_Impl;
import com.komiut.conductor.dao.MpesaMessageDao;
import com.komiut.conductor.dao.MpesaMessageDao_Impl;
import com.komiut.conductor.dao.OfflineUserDataDao;
import com.komiut.conductor.dao.OfflineUserDataDao_Impl;
import com.komiut.conductor.dao.SubRoutesDao;
import com.komiut.conductor.dao.SubRoutesDao_Impl;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings({"unchecked", "deprecation"})
public final class AppDatabase_Impl extends AppDatabase {
private volatile MpesaMessageDao _mpesaMessageDao;
private volatile CashTransactionDao _cashTransactionDao;
private volatile OfflineUserDataDao _offlineUserDataDao;
private volatile SubRoutesDao _subRoutesDao;
@Override
protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {
final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(configuration, new RoomOpenHelper.Delegate(7) {
@Override
public void createAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("CREATE TABLE IF NOT EXISTS `MpesaMessage` (`transactionId` TEXT NOT NULL, `date` TEXT, `time` TEXT, `amount` TEXT, `phonenumber` TEXT, `firstname` TEXT, `secondname` TEXT, `printStatus` INTEGER NOT NULL, PRIMARY KEY(`transactionId`))");
_db.execSQL("CREATE TABLE IF NOT EXISTS `CashTransaction` (`user_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `selectedDepart` TEXT, `selectedDest` TEXT, `regno` TEXT, `passname` TEXT, `passphone` TEXT, `nopass` TEXT, `amount` TEXT, `luggage` TEXT, `amtGiven` TEXT, `stringTotal` TEXT, `stringChange` TEXT, `date` TEXT, `offlineDataAccessDate` TEXT, `uniqueID` TEXT, `cashId` TEXT, `status` INTEGER NOT NULL)");
_db.execSQL("CREATE TABLE IF NOT EXISTS `OfflineUser` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `user_email` TEXT, `user_name` TEXT, `user_phone` TEXT, `user_plate` TEXT, `fingerprint` BLOB)");
_db.execSQL("CREATE TABLE IF NOT EXISTS `SubRoutesResponse` (`id` INTEGER NOT NULL, `substage` TEXT, `departure` TEXT, `destination` TEXT, PRIMARY KEY(`id`))");
_db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
_db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'c06d0978a3ebff35ab60faadfb361704')");
}
@Override
public void dropAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("DROP TABLE IF EXISTS `MpesaMessage`");
_db.execSQL("DROP TABLE IF EXISTS `CashTransaction`");
_db.execSQL("DROP TABLE IF EXISTS `OfflineUser`");
_db.execSQL("DROP TABLE IF EXISTS `SubRoutesResponse`");
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onDestructiveMigration(_db);
}
}
}
@Override
protected void onCreate(SupportSQLiteDatabase _db) {
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onCreate(_db);
}
}
}
@Override
public void onOpen(SupportSQLiteDatabase _db) {
mDatabase = _db;
internalInitInvalidationTracker(_db);
if (mCallbacks != null) {
for (int _i = 0, _size = mCallbacks.size(); _i < _size; _i++) {
mCallbacks.get(_i).onOpen(_db);
}
}
}
@Override
public void onPreMigrate(SupportSQLiteDatabase _db) {
DBUtil.dropFtsSyncTriggers(_db);
}
@Override
public void onPostMigrate(SupportSQLiteDatabase _db) {
}
@Override
protected RoomOpenHelper.ValidationResult onValidateSchema(SupportSQLiteDatabase _db) {
final HashMap<String, TableInfo.Column> _columnsMpesaMessage = new HashMap<String, TableInfo.Column>(8);
_columnsMpesaMessage.put("transactionId", new TableInfo.Column("transactionId", "TEXT", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("date", new TableInfo.Column("date", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("time", new TableInfo.Column("time", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("amount", new TableInfo.Column("amount", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("phonenumber", new TableInfo.Column("phonenumber", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("firstname", new TableInfo.Column("firstname", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("secondname", new TableInfo.Column("secondname", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMpesaMessage.put("printStatus", new TableInfo.Column("printStatus", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysMpesaMessage = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesMpesaMessage = new HashSet<TableInfo.Index>(0);
final TableInfo _infoMpesaMessage = new TableInfo("MpesaMessage", _columnsMpesaMessage, _foreignKeysMpesaMessage, _indicesMpesaMessage);
final TableInfo _existingMpesaMessage = TableInfo.read(_db, "MpesaMessage");
if (! _infoMpesaMessage.equals(_existingMpesaMessage)) {
return new RoomOpenHelper.ValidationResult(false, "MpesaMessage(com.komiut.conductor.model.MpesaMessage).\n"
+ " Expected:\n" + _infoMpesaMessage + "\n"
+ " Found:\n" + _existingMpesaMessage);
}
final HashMap<String, TableInfo.Column> _columnsCashTransaction = new HashMap<String, TableInfo.Column>(17);
_columnsCashTransaction.put("user_id", new TableInfo.Column("user_id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("selectedDepart", new TableInfo.Column("selectedDepart", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("selectedDest", new TableInfo.Column("selectedDest", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("regno", new TableInfo.Column("regno", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("passname", new TableInfo.Column("passname", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("passphone", new TableInfo.Column("passphone", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("nopass", new TableInfo.Column("nopass", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("amount", new TableInfo.Column("amount", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("luggage", new TableInfo.Column("luggage", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("amtGiven", new TableInfo.Column("amtGiven", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("stringTotal", new TableInfo.Column("stringTotal", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("stringChange", new TableInfo.Column("stringChange", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("date", new TableInfo.Column("date", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("offlineDataAccessDate", new TableInfo.Column("offlineDataAccessDate", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("uniqueID", new TableInfo.Column("uniqueID", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("cashId", new TableInfo.Column("cashId", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsCashTransaction.put("status", new TableInfo.Column("status", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysCashTransaction = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesCashTransaction = new HashSet<TableInfo.Index>(0);
final TableInfo _infoCashTransaction = new TableInfo("CashTransaction", _columnsCashTransaction, _foreignKeysCashTransaction, _indicesCashTransaction);
final TableInfo _existingCashTransaction = TableInfo.read(_db, "CashTransaction");
if (! _infoCashTransaction.equals(_existingCashTransaction)) {
return new RoomOpenHelper.ValidationResult(false, "CashTransaction(com.komiut.conductor.model.CashTransaction).\n"
+ " Expected:\n" + _infoCashTransaction + "\n"
+ " Found:\n" + _existingCashTransaction);
}
final HashMap<String, TableInfo.Column> _columnsOfflineUser = new HashMap<String, TableInfo.Column>(6);
_columnsOfflineUser.put("id", new TableInfo.Column("id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsOfflineUser.put("user_email", new TableInfo.Column("user_email", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsOfflineUser.put("user_name", new TableInfo.Column("user_name", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsOfflineUser.put("user_phone", new TableInfo.Column("user_phone", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsOfflineUser.put("user_plate", new TableInfo.Column("user_plate", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsOfflineUser.put("fingerprint", new TableInfo.Column("fingerprint", "BLOB", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysOfflineUser = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesOfflineUser = new HashSet<TableInfo.Index>(0);
final TableInfo _infoOfflineUser = new TableInfo("OfflineUser", _columnsOfflineUser, _foreignKeysOfflineUser, _indicesOfflineUser);
final TableInfo _existingOfflineUser = TableInfo.read(_db, "OfflineUser");
if (! _infoOfflineUser.equals(_existingOfflineUser)) {
return new RoomOpenHelper.ValidationResult(false, "OfflineUser(com.komiut.conductor.model.OfflineUser).\n"
+ " Expected:\n" + _infoOfflineUser + "\n"
+ " Found:\n" + _existingOfflineUser);
}
final HashMap<String, TableInfo.Column> _columnsSubRoutesResponse = new HashMap<String, TableInfo.Column>(4);
_columnsSubRoutesResponse.put("id", new TableInfo.Column("id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsSubRoutesResponse.put("substage", new TableInfo.Column("substage", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsSubRoutesResponse.put("departure", new TableInfo.Column("departure", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsSubRoutesResponse.put("destination", new TableInfo.Column("destination", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysSubRoutesResponse = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesSubRoutesResponse = new HashSet<TableInfo.Index>(0);
final TableInfo _infoSubRoutesResponse = new TableInfo("SubRoutesResponse", _columnsSubRoutesResponse, _foreignKeysSubRoutesResponse, _indicesSubRoutesResponse);
final TableInfo _existingSubRoutesResponse = TableInfo.read(_db, "SubRoutesResponse");
if (! _infoSubRoutesResponse.equals(_existingSubRoutesResponse)) {
return new RoomOpenHelper.ValidationResult(false, "SubRoutesResponse(com.komiut.conductor.retrofit.SubRoutesResponse).\n"
+ " Expected:\n" + _infoSubRoutesResponse + "\n"
+ " Found:\n" + _existingSubRoutesResponse);
}
return new RoomOpenHelper.ValidationResult(true, null);
}
}, "c06d0978a3ebff35ab60faadfb361704", "981d0c34648ab3332be2d292463a200c");
final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context)
.name(configuration.name)
.callback(_openCallback)
.build();
final SupportSQLiteOpenHelper _helper = configuration.sqliteOpenHelperFactory.create(_sqliteConfig);
return _helper;
}
@Override
protected InvalidationTracker createInvalidationTracker() {
final HashMap<String, String> _shadowTablesMap = new HashMap<String, String>(0);
HashMap<String, Set<String>> _viewTables = new HashMap<String, Set<String>>(0);
return new InvalidationTracker(this, _shadowTablesMap, _viewTables, "MpesaMessage","CashTransaction","OfflineUser","SubRoutesResponse");
}
@Override
public void clearAllTables() {
super.assertNotMainThread();
final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase();
try {
super.beginTransaction();
_db.execSQL("DELETE FROM `MpesaMessage`");
_db.execSQL("DELETE FROM `CashTransaction`");
_db.execSQL("DELETE FROM `OfflineUser`");
_db.execSQL("DELETE FROM `SubRoutesResponse`");
super.setTransactionSuccessful();
} finally {
super.endTransaction();
_db.query("PRAGMA wal_checkpoint(FULL)").close();
if (!_db.inTransaction()) {
_db.execSQL("VACUUM");
}
}
}
@Override
public MpesaMessageDao mpesaMessageDao() {
if (_mpesaMessageDao != null) {
return _mpesaMessageDao;
} else {
synchronized(this) {
if(_mpesaMessageDao == null) {
_mpesaMessageDao = new MpesaMessageDao_Impl(this);
}
return _mpesaMessageDao;
}
}
}
@Override
public CashTransactionDao cashTransactionDao() {
if (_cashTransactionDao != null) {
return _cashTransactionDao;
} else {
synchronized(this) {
if(_cashTransactionDao == null) {
_cashTransactionDao = new CashTransactionDao_Impl(this);
}
return _cashTransactionDao;
}
}
}
@Override
public OfflineUserDataDao offlineUserDataDao() {
if (_offlineUserDataDao != null) {
return _offlineUserDataDao;
} else {
synchronized(this) {
if(_offlineUserDataDao == null) {
_offlineUserDataDao = new OfflineUserDataDao_Impl(this);
}
return _offlineUserDataDao;
}
}
}
@Override
public SubRoutesDao subRoutesDao() {
if (_subRoutesDao != null) {
return _subRoutesDao;
} else {
synchronized(this) {
if(_subRoutesDao == null) {
_subRoutesDao = new SubRoutesDao_Impl(this);
}
return _subRoutesDao;
}
}
}
}
| [
"davidinnocent@live.com"
] | davidinnocent@live.com |
a202ebb17de8d01c6303a60f434b676658b41844 | 25ebc2419a924ff7ab811cd43db33ba2a5d458d6 | /src/main/java/com/api/gateway/api/gateway/filter/ZuulRouteFilter.java | f25e0f5807dd9bd5122dd7190610b1850b45381d | [] | no_license | vetrivetri/Api-Gateway | d5f776a444279d80b888fe6df622d94ea8de58dd | edb1d78eaee76f1b3f287599400e4145b709ad9d | refs/heads/master | 2023-06-18T08:31:55.634966 | 2021-07-22T17:01:39 | 2021-07-22T17:01:39 | 387,687,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 479 | java | package com.api.gateway.api.gateway.filter;
import com.netflix.zuul.ZuulFilter;
public class ZuulRouteFilter extends ZuulFilter {
@Override
public String filterType() {
return "route";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
System.out.println("Inside Route Filter");
return null;
}
}
| [
"51082669+vetrivetri@users.noreply.github.com"
] | 51082669+vetrivetri@users.noreply.github.com |
c0428902226c904257e6bd7a0cd756229a622422 | 0e3faff63ed4970bcabe02bb20807026cffa320b | /src/main/java/com/top/yirenbaotop/controller/UserController.java | db13c29a7e6c8b63346bf24b15e0e05b16b14f49 | [] | no_license | orgin0909/yirenbao | ab5626940392eb8abc9022ae885c08ec464c4f13 | 24c3cdc55dc7df69ce9652f5d84041ee697ea3e3 | refs/heads/master | 2022-08-10T03:44:47.385606 | 2019-09-19T07:50:13 | 2019-09-19T07:50:13 | 209,231,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,456 | java | package com.top.yirenbaotop.controller;
import com.top.yirenbaotop.domain.User;
import com.top.yirenbaotop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
public class UserController {
@Autowired
private UserService userService;
//注册
@RequestMapping("/register")
public boolean register(User user, @RequestParam("phoneCode") String phoneCode, HttpSession session){
String code = (String) session.getAttribute("code");
if (!code.equals(phoneCode)){
return false;
}
int fluRows = userService.register(user);
if (fluRows!=1){
return false;
}
return true;
}
//判断用户名是否存在
@RequestMapping("/loadByAccount")
public boolean loadByAccount(@RequestParam("account") String account){
User user = userService.loadByAccount(account);
if(user==null){
return false;
}
return true;
}
//登录
@RequestMapping("/login")
public boolean login(User user){
User user1 = userService.login(user);
if(user1==null){
return false;
}
return true;
}
}
| [
"1429827953@qq.com"
] | 1429827953@qq.com |
638ab95fb0d199a539ce8b1a9eb70925578bf3a6 | 6dcc5b8ea27bc7adea8636e66bc7c9fa81c8b5d3 | /src/com/rdml/pentaho/util/ILogDevice.java | 58da705281ecc0b8fa6631031e3e997360834092 | [] | no_license | xiatiansong/PentahoJobExecutor | cf1dcc371117c10027454c82850c573b50496169 | bfa306263e01373edce46c3036241b6fd691b427 | refs/heads/master | 2021-01-15T18:50:26.300056 | 2012-06-12T14:12:44 | 2012-06-12T14:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 93 | java | package com.rdml.pentaho.util;
public interface ILogDevice
{
public void log(String str);
} | [
"kai.cao@aspiro.com"
] | kai.cao@aspiro.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.