blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
37dd51e7dc62b008bf2808a66ea8d681fac2ab8d
|
Java
|
pooja-repo/TollRoad
|
/src/com/poja/example/Test1.java
|
UTF-8
| 606
| 3.09375
| 3
|
[] |
no_license
|
package com.poja.example;
import java.util.HashMap;
import java.util.Map;
public class Test1 {
///this is my second commit
///this will be shown only when i commits
public static void main(String[] args) {
Map map = new HashMap();
String s1 = "pooja";
map.put(s1, 123);
map.put("poonam", 456);
map.put("sushil", 789);
s1 = s1.toUpperCase();// POOJA
map.put(s1, 456);
System.out.println("value of s1 " + s1);
System.out.println("I am getting value");
System.out.println(map.get("pooja"));// 123
System.out.println(map.get("POOJA"));// 456\
//my third comment
}
}
| true
|
5babe52924920f78b37a352fce0879db9191d10d
|
Java
|
qingweiyang/nianhong
|
/src/main/java/com/nianhong/vo/TaskGetVO.java
|
UTF-8
| 1,086
| 1.898438
| 2
|
[] |
no_license
|
package com.nianhong.vo;
import java.util.Map;
import com.nianhong.model.SubTask;
import com.nianhong.model.Task;
import com.nianhong.model.TaskGet;
public class TaskGetVO {
private TaskGet taskGetModel;
private Task taskModel;
private SubTask subTaskModel;
private String picPaths[];
private Map<String, Object> personInf;
public TaskGet getTaskGetModel() {
return taskGetModel;
}
public void setTaskGetModel(TaskGet taskGetModel) {
this.taskGetModel = taskGetModel;
}
public String[] getPicPaths() {
return picPaths;
}
public void setPicPaths(String[] picPaths) {
this.picPaths = picPaths;
}
public Map<String, Object> getPersonInf() {
return personInf;
}
public void setPersonInf(Map<String, Object> personInf) {
this.personInf = personInf;
}
public Task getTaskModel() {
return taskModel;
}
public void setTaskModel(Task taskModel) {
this.taskModel = taskModel;
}
public SubTask getSubTaskModel() {
return subTaskModel;
}
public void setSubTaskModel(SubTask subTaskModel) {
this.subTaskModel = subTaskModel;
}
}
| true
|
aa237af7a5013c795728dfd3b70afaf43692bd65
|
Java
|
PatrickEuclides/biolab
|
/BioLab/src/br/edu/ifpi/biolab/dao/IDao.java
|
UTF-8
| 193
| 1.570313
| 2
|
[] |
no_license
|
package br.edu.ifpi.biolab.dao;
import br.edu.ifpi.biolab.entidade.Entidade;
import br.edu.ifpi.biolab.entidade.Especie;
public interface IDao {
void salvar(Entidade entidade);
}
| true
|
42c1e3fcb1fa29f79a50b13278bbc5df8aa98927
|
Java
|
cwlowder/AsteroidProject
|
/src/body.java
|
UTF-8
| 2,877
| 2.625
| 3
|
[] |
no_license
|
import java.awt.Color;
import java.awt.Graphics;
import orbitalCalc.orbitCalc;
import vectorsMatrices.*;
public class body {//distances in AU
public String name="N/A";
public int ID=-9999;
public double apoapsis;//highest point of orbit
public double periapsis;//lowest point of orbit
public double eccentricity;
public double theta;//angle from orient(true anomaly) in radians
//public double phi;//angle from orient at start of simulation
public double meanAnomaly0;//mean anomaly at epoch
public double eccentricAnomaly;//the eccentric anomaly
public double period;//period of the orbit
public double semimajor;//semi major axis
public double semiminor;//semi major axis
public double radius;
public double LongAscenNode=0;//longitude of Ascending Node
public double ArgPeriapsis=0;//Argument of Periapsis
public double Inclination=0;//Inclination
public vector pos=new vector(0,0,0);//position vector
public double x=10;
public double y;
public double z;
public double mass;//mass of this body
public body(double semi,double e){
semimajor=semi;
eccentricity=e;
semiminor=semimajor*Math.sqrt(1-e*e);
period=Math.sqrt(Math.pow(semimajor,3));
radius=semimajor*(1-eccentricity*eccentricity)/(1+eccentricity*Math.cos(theta));
apoapsis=(1+e)*semimajor;
periapsis=(1-e)*semimajor;
}
public void calc(){//https://en.wikipedia.org/wiki/Kepler's_laws_of_planetary_motion
//double n=2*Math.PI/period;//mean motion
theta=orbitCalc.calc(period,eccentricity,runnerMain.time,meanAnomaly0);//TODO factor in mean anomally since epoch
radius=semimajor*(1-eccentricity*eccentricity)/(1+eccentricity*Math.cos(theta));
//TODO this code is all shit
matrix posPerhel=rotationalMatrix.rotateComplete(ArgPeriapsis, Inclination, LongAscenNode,radius);//positional vector for the periapsis TODO make sure to check if longAsceNde should be shifted like in Prof Larson's paper
matrix posPerpPerhel=rotationalMatrix.rotatePerp(Inclination, LongAscenNode);
posPerhel=rotationalMatrix.rotate(posPerhel, posPerpPerhel, theta);
//x=posPerhel.getValPos(0, 0);
//y=posPerhel.getValPos(0, 1);
//z=posPerhel.getValPos(0, 2);
pos.i=posPerhel.getValPos(0, 0);
pos.j=posPerhel.getValPos(0, 1);
pos.k=posPerhel.getValPos(0, 2);
if(pos.i==0&&pos.j==0&&pos.k==0){
System.out.println("zeroer- "+ID);
}
//runnerMain.testPrint.print(100*x,100*y,100*z,runnerMain.time,theta,radius,temp);//TODO remove
}
public void draw(Graphics g){
int xFake=(int)(pos.i*runnerMain.zoom);//TODO what scale should I draw at
int yFake=(int)(pos.j*runnerMain.zoom);
g.setColor(Color.red);
if(ID==0)
{}
else
g.drawOval(runnerMain.con.xSun+xFake,runnerMain.con.ySun+yFake, 10, 10);
}
public void print(){
System.out.println("name: "+name);
System.out.println("radius: "+radius);
System.out.println("angle: "+theta);
}
}
| true
|
7ee168e65d45910011d4c0e360dddb698788a8e1
|
Java
|
abstract-base-method/ratpack-background
|
/src/main/java/com/lemonoflime/rpbackground/handlers/CreateObjectHandler.java
|
UTF-8
| 828
| 2.46875
| 2
|
[] |
no_license
|
package com.lemonoflime.rpbackground.handlers;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.lemonoflime.rpbackground.persistence.SimpleObject;
import com.lemonoflime.rpbackground.services.StorageService;
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.http.Status;
@Singleton
public class CreateObjectHandler implements Handler {
private final StorageService storageService;
@Inject
public CreateObjectHandler(StorageService storageService) {
this.storageService = storageService;
}
@Override
public void handle(Context ctx) throws Exception {
ctx
.parse(SimpleObject.class)
.nextOp(storageService::persist)
.then(obj -> ctx.getResponse().status(Status.ACCEPTED).send());
}
}
| true
|
1721b02a7693bf0fab63fed14b025d0c8d13739d
|
Java
|
Isakots/mealride-api
|
/src/main/java/hu/student/projlab/mealride_api/service/UserService.java
|
UTF-8
| 2,581
| 2.34375
| 2
|
[] |
no_license
|
package hu.student.projlab.mealride_api.service;
import hu.student.projlab.mealride_api.config.security.SecurityUtils;
import hu.student.projlab.mealride_api.domain.user.CustomerUser;
import hu.student.projlab.mealride_api.domain.user.SpringUser;
import hu.student.projlab.mealride_api.exception.UserIsNotAuthenticatedException;
import hu.student.projlab.mealride_api.repository.CustomerUserRepository;
import hu.student.projlab.mealride_api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
private UserRepository userRepository;
private CustomerUserRepository customerUserRepository;
@Autowired
public UserService(UserRepository userRepository, CustomerUserRepository customerUserRepository) {
this.userRepository = userRepository;
this.customerUserRepository = customerUserRepository;
}
public List<SpringUser> findAllWorkers(Long restaurantId) {
return userRepository.findAllByRestaurantUserRestaurantId(restaurantId)
.orElse(Collections.emptyList());
}
public Optional<SpringUser> findByEmail(String email) {
return userRepository.findByUsername(email);
}
/**
* Note: This is a bad solution. I cant store yet the authorities of a CustomerUser in SecurityContext so
* I implement this function as a temporary solution to let me move on.
*
* @return the database CustomerUser of the current login
*/
public SpringUser getCurrentUser(Optional<String> email) throws UserIsNotAuthenticatedException {
return userRepository.findByUsername(email.get()).orElseThrow(UserIsNotAuthenticatedException::new);
}
public void save(SpringUser springUser) {
userRepository.save(springUser);
}
public CustomerUser getUserData() {
return this.getCurrentUser(SecurityUtils.getCurrentUserLogin()).getCustomerUser();
}
public CustomerUser modifyUserData(CustomerUser customerUser) {
validateID(customerUser);
return customerUserRepository.save(customerUser);
}
private void validateID(CustomerUser customerUser) {
if (this.getCurrentUser(SecurityUtils.getCurrentUserLogin()).getCustomerUser().getId() !=
customerUser.getId())
throw new AccessDeniedException("Invalid operation");
}
}
| true
|
c1ba20cf5a8328121c87929c64c26984af489306
|
Java
|
liordon/encryptor1
|
/src/main/java/mil/idf/af/ofek/crypto/EncryptionAlgorithmComparator.java
|
UTF-8
| 297
| 2.3125
| 2
|
[] |
no_license
|
package mil.idf.af.ofek.crypto;
import java.util.Comparator;
public class EncryptionAlgorithmComparator implements Comparator<EncryptionAlgorithm> {
@Override
public int compare(EncryptionAlgorithm o1, EncryptionAlgorithm o2) {
return o1.getKeyStrength() - o2.getKeyStrength();
}
}
| true
|
21987f65f5612eed71a668e6a378d7e0ef78835d
|
Java
|
theoriginalshaheedra/artifactory-oss
|
/web/rest-ui/src/main/java/org/artifactory/ui/rest/service/admin/security/auth/forgotpassword/ForgotPasswordService.java
|
UTF-8
| 4,838
| 1.867188
| 2
|
[] |
no_license
|
/*
*
* Artifactory is a binaries repository manager.
* Copyright (C) 2018 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.artifactory.ui.rest.service.admin.security.auth.forgotpassword;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.artifactory.addon.AddonsManager;
import org.artifactory.addon.CoreAddons;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.api.security.ResetPasswordException;
import org.artifactory.api.security.UserGroupService;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.artifactory.rest.common.service.RestResponse;
import org.artifactory.rest.common.service.RestService;
import org.artifactory.ui.rest.model.admin.security.login.UserLogin;
import org.artifactory.util.HttpUtils;
import org.jfrog.client.util.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @author Chen Keinan
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ForgotPasswordService implements RestService {
private static final Logger log = LoggerFactory.getLogger(ForgotPasswordService.class);
@Autowired
UserGroupService userGroupService;
@Override
public void execute(ArtifactoryRestRequest request, RestResponse response) {
UserLogin userLogin = (UserLogin) request.getImodel();
String resetPasswordUrl = getResetPasswordPageUrl();
String username = userLogin.getUser();
//Check if username is valid
if (StringUtils.isEmpty(username)) {
response.error("User is required");
response.responseCode(400);
return;
}
// rest user password
resetPassword(request, response, username, resetPasswordUrl);
}
/**
* reset user password
*
* @param artifactoryRequest - encapsulate data require for request
* @param artifactoryResponse - encapsulate data related to response
* @param username - username
*/
private void resetPassword(ArtifactoryRestRequest artifactoryRequest, RestResponse artifactoryResponse,
String username, String resetPasswordUrl) {
// if in aol mode then have to go to the dashboard to reset password
String remoteAddress = HttpUtils.getRemoteClientAddress(artifactoryRequest.getServletRequest());
try {
String status = userGroupService.resetPassword(username, remoteAddress, resetPasswordUrl);
artifactoryResponse.info(status);
} catch (ResetPasswordException e) {
log.warn("Error while resetting password for user: '{}', requested from address '{}'. {}", username,
remoteAddress, e.getMessage());
log.debug("Error while resetting password for user: '{}', requested from address '{}'. {}", username,
remoteAddress, e);
artifactoryResponse.error(e.getMessage());
artifactoryResponse.responseCode(HttpStatus.SC_FORBIDDEN);
} catch (Exception e) {
log.error("Error while resetting password for user: '{}', requested from address '{}'. {}", username,
remoteAddress, e);
artifactoryResponse.error(e.getMessage());
}
}
/**
* Get the bookmarkable URL of the reset password page
*
* @return String - URL to reset password page
*/
private String getResetPasswordPageUrl() {
CoreAddons addon = ContextHelper.get().beanForType(AddonsManager.class).addonByType(CoreAddons.class);
String resetPasswordUrl = addon.getMailConfigArtifactoryUrl();
// In case we have no url at all, just return relative url, better than nothing.
if (resetPasswordUrl == null) {
log.warn("No URL found for password expiration notification");
resetPasswordUrl = "";
}
return PathUtils.addTrailingSlash(resetPasswordUrl) + "#/resetpassword";
}
}
| true
|
6340296a93af3743179924f5b226ba119f044ef4
|
Java
|
AlGreed/fahrschein
|
/fahrschein/src/main/java/org/zalando/fahrschein/ZignAccessTokenProvider.java
|
UTF-8
| 2,728
| 2.625
| 3
|
[
"LicenseRef-scancode-free-unknown",
"CC-BY-SA-3.0",
"CC-BY-3.0",
"Apache-2.0"
] |
permissive
|
package org.zalando.fahrschein;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class ZignAccessTokenProvider implements AccessTokenProvider {
private static final Logger LOG = LoggerFactory.getLogger(ZignAccessTokenProvider.class);
private static final long CACHE_DURATION = 5 * 60 * 1000L;
static class Entry {
final long timestamp;
final String value;
Entry(long timestamp, String value) {
this.timestamp = timestamp;
this.value = value;
}
}
private final AtomicReference<Entry> token = new AtomicReference<>();
private static String readAll(InputStream inputStream) throws IOException {
try (final Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final StringBuilder sb = new StringBuilder();
final char[] buf = new char[1024];
int len;
while ((len = reader.read(buf)) != -1) {
sb.append(buf, 0, len);
}
return sb.toString();
}
}
private static String zign() throws IOException {
LOG.info("Refreshing token from zign...");
final Process zign = new ProcessBuilder("zign", "token").start();
try (final InputStream inputStream = zign.getInputStream()) {
final String output = readAll(inputStream).trim();
zign.waitFor(5, TimeUnit.SECONDS);
if (zign.exitValue() != 0) {
throw new IOException(String.format("zign failed with the exit code: %d", zign.exitValue()));
}
LOG.debug("Refreshed token from zign");
return output;
} catch (InterruptedException e) {
throw new IOException("zign process took longer than 5 seconds to exit");
}
}
private static Entry update(@Nullable Entry entry) {
final long now = System.currentTimeMillis();
try {
return entry == null || entry.timestamp < now - CACHE_DURATION ? new Entry(now, zign()) : entry;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public String getAccessToken() throws IOException {
try {
return token.updateAndGet(ZignAccessTokenProvider::update).value;
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
}
| true
|
16e888cdf6cd97ec32b30a5cf5f9da06d3d5bb59
|
Java
|
QiquWong/jpad
|
/JPADSandBox/src/sandbox/vc/agile/Test_AGILE_DC1_01.java
|
UTF-8
| 3,356
| 2.25
| 2
|
[] |
no_license
|
package sandbox.vc.agile;
import java.io.File;
import javax.measure.quantity.Mass;
import javax.measure.unit.SI;
import org.jscience.physics.amount.Amount;
import aircraft.OperatingConditions;
import aircraft.calculators.ACAnalysisManager;
import aircraft.components.Aircraft;
import aircraft.components.liftingSurface.LSAerodynamicsManager;
import aircraft.components.liftingSurface.LiftingSurface2Panels;
import configuration.MyConfiguration;
import configuration.enumerations.AircraftEnum;
import configuration.enumerations.AnalysisTypeEnum;
import configuration.enumerations.DatabaseReaderEnum;
import javafx.util.Pair;
import writers.JPADChartWriter;
import writers.JPADDataWriter;
import writers.JPADWriteUtils;
public class Test_AGILE_DC1_01 {
public static void main(String[] args) {
// Initialize working directories
MyConfiguration.initWorkingDirectoryTree(MyConfiguration.currentDirectoryString,
MyConfiguration.inputDirectory,
MyConfiguration.outputDirectory,
MyConfiguration.databaseDirectory);
String folderName = "Test_AGILE_DC1_01";
// Define the aircraft
Aircraft aircraft = Aircraft.createDefaultAircraft(AircraftEnum.AGILE_DC1);
aircraft.setName("AGILE_DC1");
LiftingSurface2Panels theWing = aircraft.get_wing();
String exportFile = MyConfiguration.outputDirectory + File.separator +
folderName + File.separator + aircraft.getName();
// Set the operating conditions
OperatingConditions operatingConditions = new OperatingConditions();
operatingConditions.set_altitude(Amount.valueOf(11000., SI.METER));
operatingConditions.set_machCurrent(0.78);
// Define the Analysis Manager
ACAnalysisManager theAnalysis = new ACAnalysisManager(operatingConditions);
theAnalysis.updateGeometry(aircraft);
// --------------------------------------------------------------
// Define an LSAerodynamicsManager Object
// --------------------------------------------------------------
LSAerodynamicsManager theLSAnalysis = new LSAerodynamicsManager (
operatingConditions,
theWing,
aircraft
);
// --------------------------------------------------------------
// Setup database(s)
// --------------------------------------------------------------
theLSAnalysis.setDatabaseReaders(
new Pair<DatabaseReaderEnum, String>(DatabaseReaderEnum.AERODYNAMIC,
"Aerodynamic_Database_Ultimate.h5"),
new Pair<DatabaseReaderEnum, String>(DatabaseReaderEnum.HIGHLIFT,
"HighLiftDatabase.h5")
);
// Define the analysis
theAnalysis.doAnalysis(aircraft,
AnalysisTypeEnum.AERODYNAMIC_AND_STABILITY,
AnalysisTypeEnum.BALANCE,
AnalysisTypeEnum.WEIGHTS,
AnalysisTypeEnum.PERFORMANCE,
AnalysisTypeEnum.COSTS
);
JPADDataWriter _theWriteUtilities = new JPADDataWriter(
operatingConditions,
aircraft,
theAnalysis);
JPADChartWriter _theWriteCharts = new JPADChartWriter(aircraft);
_theWriteCharts.createCharts();
// +++++++++++++++++++++++++++++++++++++++++++++++
// STATIC FUNCTIONS - TO BE CALLED BEFORE WRITING CUSTOM XML FILES
JPADWriteUtils.buildXmlTree(aircraft,operatingConditions);
// Export everything to file
_theWriteUtilities.exportToXMLfile(exportFile + ".xml");
_theWriteUtilities.exportToXLSfile(exportFile + ".xls");
}
}
| true
|
66255050c9564d4388103fbdcb57fa2d61abd1ec
|
Java
|
Vivek1517/For-Viveks-New-Laptop
|
/FirstExercise/src/Conditional/Practice3.java
|
UTF-8
| 1,727
| 4.21875
| 4
|
[] |
no_license
|
package Conditional;
//1. Write a program to compare 2 number and print maximum value
//2. Write a program to compare 2 numbers and print minimum value
//3. write a program to find out whether number is positive or negative number
import java.util.Scanner;
public class Practice3 {
public void max(int a, int b){
if(a>b){
System.out.println(a+" Is the greatest number");
}
else{
System.out.println(b+" Is the greatest number");
}
}
public void mini(int a, int b){
System.out.println(a+" & "+b);
if(a<b){
System.out.println(a+" Is the lowest number");
}
else{
System.out.println(b+" Is the lowest number");
}
}
public void pOrN(int a){
System.out.println(a);
if(a>=0){
System.out.println(a+" Is a positive number");
}
else{
System.out.println(a+" Is a negative number");
}
if(a==0){
System.out.println(a+" It is neutral number");
}
}
public static void main(String[] args) {
Practice3 obj = new Practice3();
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 numbers to find out which is a higher number");
int maxN1= input.nextInt();
int maxN2= input.nextInt();
obj.max(maxN1, maxN2);
System.out.println("Enter a numbers to find out which is lower number");
int min1= input.nextInt();
int min2= input.nextInt();
obj.mini(min1, min2);
System.out.println("Enter a number to find out if it is positive or negative");
int pN= input.nextInt();
obj.pOrN(pN);
}
}
| true
|
e28e97a8417205018435e1e0ee51cd93a3671539
|
Java
|
GlebSviripa/NDKWrapperExample
|
/src/com/simplexsolutionsinc/coresignkernelwrapper/listeners/CSSessionEvent.java
|
UTF-8
| 341
| 1.804688
| 2
|
[] |
no_license
|
package com.simplexsolutionsinc.coresignkernelwrapper.listeners;
public class CSSessionEvent extends CSEvent
{
public static final int SessionStateChanged = 1;
public static final int SessionUserPasswordChanged = 2;
public static final int SessionCriticalTasksCompleted = 3;
public CSSessionEvent(long _ptr)
{
super(_ptr);
}
}
| true
|
2017635fedbac4066ff58d44082b77b2f4d9115c
|
Java
|
sumit-sardar/GitMigrationRepo01
|
/application-tmsproxy/remoteservlet/src/com/ctb/tms/bean/login/AccommodationsData.java
|
UTF-8
| 6,698
| 2.046875
| 2
|
[] |
no_license
|
package com.ctb.tms.bean.login;
public class AccommodationsData
{
private int studentId;
private String screenMagnifier;
private String screenReader;
private String speechSpeedControl;
private String calculator;
private String testPause;
private String untimedTest;
private String questionBackgroundColor;
private String questionFontColor;
private float questionFontSize;
private String answerBackgroundColor;
private String answerFontColor;
private float answerFontSize;
private String highlighter;
private String maskingRuler;
private String auditoryCalming;
private byte[] musicFileData;
private Integer musicFileId;
private String magnifyingGlass;//Added for magnifier
private String extendedTime;
private String maskingTool;//Added for masking Answers
public String getSpeechSpeedControl() {
return speechSpeedControl;
}
public void setSpeechSpeedControl(String speechSpeedControl) {
this.speechSpeedControl = speechSpeedControl;
}
/**
* @return the musicFileId
*/
public Integer getMusicFileId() {
return musicFileId;
}
/**
* @param musicFileId the musicFileId to set
*/
public void setMusicFileId(Integer musicFileId) {
this.musicFileId = musicFileId;
}
/**
* @return Returns the highlighter.
*/
public String getHighlighter() {
return highlighter;
}
/**
* @param highlighter The highlighter to set.
*/
public void setHighlighter(String highlighter) {
this.highlighter = highlighter;
}
/**
* @return Returns the answerBackgroundColor.
*/
public String getAnswerBackgroundColor() {
return answerBackgroundColor;
}
/**
* @param answerBackgroundColor The answerBackgroundColor to set.
*/
public void setAnswerBackgroundColor(String answerBackgroundColor) {
this.answerBackgroundColor = answerBackgroundColor;
}
/**
* @return Returns the answerFontColor.
*/
public String getAnswerFontColor() {
return answerFontColor;
}
/**
* @param answerFontColor The answerFontColor to set.
*/
public void setAnswerFontColor(String answerFontColor) {
this.answerFontColor = answerFontColor;
}
/**
* @return Returns the answerFontSize.
*/
public float getAnswerFontSize() {
return answerFontSize;
}
/**
* @param answerFontSize The answerFontSize to set.
*/
public void setAnswerFontSize(float answerFontSize) {
this.answerFontSize = answerFontSize;
}
/**
* @return Returns the calculator.
*/
public String getCalculator() {
return calculator;
}
/**
* @param calculator The calculator to set.
*/
public void setCalculator(String calculator) {
this.calculator = calculator;
}
/**
* @return Returns the questionBackgroundColor.
*/
public String getQuestionBackgroundColor() {
return questionBackgroundColor;
}
/**
* @param questionBackgroundColor The questionBackgroundColor to set.
*/
public void setQuestionBackgroundColor(String questionBackgroundColor) {
this.questionBackgroundColor = questionBackgroundColor;
}
/**
* @return Returns the questionFontColor.
*/
public String getQuestionFontColor() {
return questionFontColor;
}
/**
* @param questionFontColor The questionFontColor to set.
*/
public void setQuestionFontColor(String questionFontColor) {
this.questionFontColor = questionFontColor;
}
/**
* @return Returns the questionFontSize.
*/
public float getQuestionFontSize() {
return questionFontSize;
}
/**
* @param questionFontSize The questionFontSize to set.
*/
public void setQuestionFontSize(float questionFontSize) {
this.questionFontSize = questionFontSize;
}
/**
* @return Returns the screenMagnifier.
*/
public String getScreenMagnifier() {
return screenMagnifier;
}
/**
* @param screenMagnifier The screenMagnifier to set.
*/
public void setScreenMagnifier(String screenMagnifier) {
this.screenMagnifier = screenMagnifier;
}
/**
* @return Returns the screenReader.
*/
public String getScreenReader() {
return screenReader;
}
/**
* @param screenReader The screenReader to set.
*/
public void setScreenReader(String screenReader) {
this.screenReader = screenReader;
}
/**
* @return Returns the studentId.
*/
public int getStudentId() {
return studentId;
}
/**
* @param studentId The studentId to set.
*/
public void setStudentId(int studentId) {
this.studentId = studentId;
}
/**
* @return Returns the testPause.
*/
public String getTestPause() {
return testPause;
}
/**
* @param testPause The testPause to set.
*/
public void setTestPause(String testPause) {
this.testPause = testPause;
}
/**
* @return Returns the untimedTest.
*/
public String getUntimedTest() {
return untimedTest;
}
/**
* @param untimedTest The untimedTest to set.
*/
public void setUntimedTest(String untimedTest) {
this.untimedTest = untimedTest;
}
/**
* @return the maskingRuler
*/
public String getMaskingRuler() {
return maskingRuler;
}
/**
* @param maskingRuler the maskingRuler to set
*/
public void setMaskingRuler(String maskingRuler) {
this.maskingRuler = maskingRuler;
}
/**
* @return the auditoryCalming
*/
public String getAuditoryCalming() {
return auditoryCalming;
}
/**
* @param auditoryCalming the auditoryCalming to set
*/
public void setAuditoryCalming(String auditoryCalming) {
this.auditoryCalming = auditoryCalming;
}
/**
* @return the musicFileData
*/
public byte[] getMusicFileData() {
return musicFileData;
}
/**
* @param musicFileData the musicFileData to set
*/
public void setMusicFileData(byte[] musicFileData) {
this.musicFileData = musicFileData;
}
/**
* @return the magnifyingGlass
*/
public String getMagnifyingGlass() {
return magnifyingGlass;
}
/**
* @param magnifyingGlass the magnifyingGlass to set
*/
public void setMagnifyingGlass(String magnifyingGlass) {
this.magnifyingGlass = magnifyingGlass;
}
/**
* @return the extendedTime
*/
public String getExtendedTime() {
return extendedTime;
}
/**
* @param extendedTime the extendedTime to set
*/
public void setExtendedTime(String extendedTime) {
this.extendedTime = extendedTime;
}
/**
* @return the maskingTool
*/
public String getMaskingTool() {
return maskingTool;
}
/**
* @param maskingTool the maskingTool to set
*/
public void setMaskingTool(String maskingTool) {
this.maskingTool = maskingTool;
}
}
| true
|
f1999aa7fcd6f8f30061eb82e8792082eb4701e6
|
Java
|
tangheng666/test_hello-wrold
|
/Server_Manager_Code/src/com/ssd/controller/exception/UserExceptionResolver.java
|
UTF-8
| 1,221
| 2.421875
| 2
|
[] |
no_license
|
package com.ssd.controller.exception;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class UserExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// TODO Auto-generated method stub
//输出异常
ex.printStackTrace();
//统一异常处理代码
//针对系统自定义的CustomException异常,就可以直接从异常类中获取异常信息,将异常处理在错误页面展示
//异常信息
request.setAttribute("message",ex.getMessage());
try {
//转向到错误 页面
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ModelAndView();
}
}
| true
|
a2b4c0f2653463aef59b3fa574abe5bc8af3e3a9
|
Java
|
Stevelet/Starcraft
|
/eisbw/src/main/java/eisbw/WindowsTools.java
|
UTF-8
| 3,843
| 2.515625
| 3
|
[] |
no_license
|
package eisbw;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Danny & Harm - The windowstool for starting the chaoslauncher and
* writing the menu script.
*
*/
public class WindowsTools {
private WindowsTools() {
// Private constructor to hide the public one.
}
/**
* Check if a process is running on the system.
*
* @param process
* the name of the process.
* @return true iff a process is running.
*/
public static boolean isProcessRunning(String process) {
try {
Process proc = Runtime.getRuntime().exec("tasklist.exe");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = stdInput.readLine()) != null) {
if (line.contains(process)) {
stdInput.close();
return true;
}
}
stdInput.close();
} catch (IOException exception) {
Logger.getLogger("StarCraft Logger").log(Level.SEVERE, "Could not read processes.", exception);
}
return false;
}
/**
* Starts the Chaoslauncher with launch rules.
*
* @param race
* the race specified in the mas2g
* @param map
* the map specified in the mas2g
* @param scDir
* the starcraft installation directory in the mas2g.
* @param autoMenu
* the automenu (single- or multi-player) specified in the mas2g
* @param enemyRace
* the enemy race
* @throws IOException
* throws exception when BWAPI.ini cannot be written.
*/
public static void startChaoslauncher(String race, String map, String scDir, String autoMenu, String enemyRace)
throws IOException {
populateInitFile(race, map, scDir, autoMenu, enemyRace);
if (autoMenu.toLowerCase().equals("lan")) {
Runtime.getRuntime().exec(new String[] { scDir + "\\Chaoslauncher\\Chaoslauncher - MultiInstance.exe" },
null, new File(scDir + "\\Chaoslauncher\\"));
} else {
Runtime.getRuntime().exec(scDir + "\\Chaoslauncher\\Chaoslauncher.exe", null,
new File(scDir + "\\Chaoslauncher\\"));
}
}
private static void populateInitFile(String race, String map, String scDir, String autoMenu, String enemyRace) {
String bwapiDest = scDir + "\\bwapi-data\\bwapi.ini";
String iniFile = getIniFile(race, map, autoMenu, enemyRace);
try {
BufferedWriter out = new BufferedWriter(new FileWriter(new File(bwapiDest)));
out.write(iniFile);
out.close();
} catch (Exception exception) {
Logger.getLogger("StarCraft Logger").log(Level.SEVERE, "Could not write config file.", exception);
}
}
protected static String getIniFile(String race, String map, String autoMenu, String enemyRace) {
String newLine = System.getProperty("line.separator");
String iniFile = "";
iniFile += ";Generated by GOAL launcher" + newLine;
iniFile += "[ai]" + newLine;
iniFile += "ai = NULL" + newLine + newLine;
iniFile += "[auto_menu]" + newLine;
iniFile += "auto_menu = " + autoMenu + newLine + newLine;
if (autoMenu.toLowerCase().equals("lan")) {
iniFile += "lan_mode = local pc" + newLine + newLine;
}
iniFile += "pause_dbg = OFF" + newLine + newLine;
iniFile += "auto_restart = OFF" + newLine + newLine;
iniFile += "map = maps\\sscai\\" + map + newLine + newLine;
iniFile += "race = " + race + newLine + newLine;
iniFile += "enemy_count = 1" + newLine + newLine;
iniFile += "enemy_race = " + enemyRace + newLine + newLine;
iniFile += "[config]" + newLine;
iniFile += "[window]" + newLine;
iniFile += "windowed = ON" + newLine;
iniFile += "width = 1024" + newLine;
iniFile += "height = 768" + newLine + newLine;
return iniFile;
}
}
| true
|
054cc8fe461c06788a2d560a15d52f37b23f2f44
|
Java
|
lu92/TradeEngineUJ
|
/src/main/java/com/tradeengineproject/profilereader/repositories/CreditCardRepository.java
|
UTF-8
| 277
| 1.617188
| 2
|
[] |
no_license
|
package com.tradeengineproject.profilereader.repositories;
import com.tradeengineproject.profilereader.domain.entities.CreditCard;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CreditCardRepository extends JpaRepository<CreditCard, Long>
{
}
| true
|
f17a4a3b68002c3d4f5c8327b9cf4ba17175daa3
|
Java
|
CKB0001/javaEE
|
/程序/c06_sh_card/src/com/edu/dao/user/UserDao.java
|
UTF-8
| 890
| 2.671875
| 3
|
[] |
no_license
|
package com.edu.dao.user;
import com.edu.dao.DaoHibernate;
import com.edu.model.user.User;
public class UserDao extends DaoHibernate<User> {
// 通过姓名、密码查询用户
public User findBynameAndPassword(User user) {
String hql = "from User u where u.userName=? and u.userPassword=?";
String param[] = { user.getUserName(), user.getUserPassword() };
User user1 = this.findOne(hql, param);
return user1;
}
// 通过姓名查询用户
public User findByname(User user) {
String hql = "from User u where u.userName=?";
String param[] = { user.getUserName() };
User user1 = this.findOne(hql, param);
return user1;
}
// 修改用户密码: 修改 对象use的密码为newPasswoed
public int updatePassword(User user, String newPassword) {
User user1 = this.findBynameAndPassword(user);
user1.setUserPassword(newPassword);
return this.update(user1);
}
}
| true
|
86e4cb09f7ba666a19b3bb19cdf8230b05566bd0
|
Java
|
gkdevps/JavaMasterClass
|
/src/Encapsulation/Printer.java
|
UTF-8
| 1,223
| 3.453125
| 3
|
[] |
no_license
|
package Encapsulation;
/**
* Created by GAGAN on 10/01/2018.
*/
public class Printer {
private int tonerLevel;
private int pagesPrinted;
private boolean isDuplex;
public Printer(int tonerLevel, boolean isDuplex) {
if (tonerLevel>-1&&tonerLevel<=100) {
this.tonerLevel = tonerLevel;
}
else
{
this.tonerLevel=-1;
}
this.isDuplex = isDuplex;
this.pagesPrinted=0;
}
public int addToner(int tonerAmount)
{
if (tonerAmount>0&&tonerAmount<=100)
{
if (this.tonerLevel+tonerAmount>100)
{
return -1;
}
this.tonerLevel+=tonerAmount;
return this.tonerLevel;
}else {
return -1;
}
}
public int getTonerLevel() {
return tonerLevel;
}
public int printPages(int pages)
{
int pagesToPrint=pages;
if (this.isDuplex){
pagesToPrint/=2;
System.out.println("printing in duplex mode");
}
this.pagesPrinted+=pagesToPrint;
return pagesToPrint;
}
public int getPagesPrinted() {
return pagesPrinted;
}
}
| true
|
2fa49fb8a4338f931eeb41f8a9d706291ba06ddb
|
Java
|
ReshiIRE/ProgrammingIIIAssignment4
|
/src/programmingiiiassignment4/Ball.java
|
UTF-8
| 983
| 3.296875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package programmingiiiassignment4;
/**
*
* @author Eamonn Hannon
*/
public enum Ball {
BASEBALL(149, 73),
BASKETBALL(624, 239),
FOOTBALL(450, 216),
GOLF(46, 43),
POOL(156, 60),
SOFTBALL(180, 97),
TENNIS(59, 64),
VOLLEYBALL(260, 218);
private float weight;
private float diameter;
Ball(float weight, float diameter)
{
this.weight = weight;
this.diameter = diameter;
}
public float getWeight()
{
return weight;
}
public float getDiameter()
{
return diameter;
}
public double getCircumference()
{
return Math.PI * diameter;
}
public double getVolume()
{
float radius = diameter / 2;
return (4/3) * Math.PI * radius * radius * radius;
}
}
| true
|
4745c3a92e763c92899d0b62f41ee4dc9694a601
|
Java
|
cctytw2000/Team6FinalProjectBackup
|
/Team6FinalProject/src/main/java/com/eeit109team6/finalproject/service/impl/SubjectTypeServiceImpl.java
|
UTF-8
| 1,209
| 2.1875
| 2
|
[] |
no_license
|
package com.eeit109team6.finalproject.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eeit109team6.finalproject.dao.ISubjectTypeDao;
import com.eeit109team6.finalproject.model.SubjectType;
import com.eeit109team6.finalproject.service.ISubjectTypeService;
@Service
public class SubjectTypeServiceImpl implements ISubjectTypeService {
ISubjectTypeDao dao;
@Autowired
public void setDao(ISubjectTypeDao dao) {
this.dao = dao;
}
public SubjectTypeServiceImpl() {
}
@Transactional
@Override
public List<SubjectType> getAllSubjectType() {
System.out.println("進入SubjectTypeServiceImpl");
return dao.getAllSubjectType();
}
@Transactional
@Override
public SubjectType getSubjectTypeById(int subjectTypeId) {
return dao.getSubjectTypeById(subjectTypeId);
}
@Transactional
@Override
public void addSubjectType(SubjectType subjectType) {
dao.addSubjectType(subjectType);
}
@Transactional
@Override
public void updateSubjectType(SubjectType subjectType) {
dao.updateSubjectType(subjectType);
}
}
| true
|
9ebc04a5db6ef989c35e29616f5760cba20490a5
|
Java
|
chokrihamza/abstractclass
|
/src/domain/GeometricFigure.java
|
UTF-8
| 464
| 2.84375
| 3
|
[] |
no_license
|
package domain;
public abstract class GeometricFigure {
protected String figureType;
public GeometricFigure(String figureType) {
this.figureType = figureType;
}
public abstract void draw();
public String getFigureType() {
return figureType;
}
public void setFigureType(String figureType) {
this.figureType = figureType;
}
@Override
public String toString() {
return "GeometricFigure [figureType=" + figureType + "]";
}
}
| true
|
101808260e8144b0fc0ccb5c6d68543b56cf5554
|
Java
|
KarolNurzynski/Workshop-Amelco
|
/src/main/java/pl/coderslab/controller/BetController.java
|
UTF-8
| 2,477
| 2.28125
| 2
|
[] |
no_license
|
package pl.coderslab.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import pl.coderslab.entity.Bet;
import pl.coderslab.service.BetService;
import pl.coderslab.service.UserService;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
@Controller
@RequestMapping("/bet")
public class BetController {
@Autowired
BetService betService;
@Autowired
UserService userService;
@GetMapping("/add")
public String addBet(Model model){
model.addAttribute("bet", new Bet());
return "betForm";
}
@PostMapping("/add")
public String addBet(@Valid @ModelAttribute Bet bet,
BindingResult result){
if (result.hasErrors()) {
return "betForm";
}
bet.setCreated(LocalDateTime.now());
betService.saveBet(bet);
return "redirect:/";
}
// @GetMapping("/show/all")
// public String showAllBets(Model model) {
// return "betListAll";
// }
//
// @GetMapping("/show/{bet_id")
// public String showBet(@PathVariable Long bet_id, Model model) {
// model.addAttribute(betService.findBetById(bet_id));
// return "betShow";
// }
//
// @GetMapping("/edit/{bet_id}")
// public String editBet(@PathVariable Long bet_id, Model model) {
// Bet bet = betService.findBetById(bet_id);
// model.addAttribute("bet",bet);
// return "betEditForm";
// }
//
// @PostMapping("/edit/{bet_id}")
// public String editBet(@ModelAttribute Bet bet,
// @PathVariable Long bet_id,
// Model model) {
// bet.setId(bet_id);
// betService.editBet(bet);
// return "redirect:/";
// }
//
// @GetMapping("/delete/{bet_id}")
// public String deleteBet(@PathVariable Long bet_id, Model model) {
// betService.deleteBet(bet_id);
// return "redirect:/";
// }
///////////////////////// MODEL ATTRIBUTES /////////////////////////////////
// @ModelAttribute("users")
// public List<User> users() {
// return userService.findAllUsers();
// }
//
@ModelAttribute("bets")
public List<Bet> bets() {
return betService.findAllBets();
}
}
| true
|
6f85dbe5077a83bce29b681074605082da0c640f
|
Java
|
OleksandrGrument/HealthCareSocialWebApp
|
/src/main/java/com/HealthCareSocialAppServer/util/ServerResponseAnswersConstant.java
|
UTF-8
| 4,354
| 1.867188
| 2
|
[] |
no_license
|
package com.HealthCareSocialAppServer.util;
public class ServerResponseAnswersConstant {
//Errors
public final static String ERR_SERVER_ERROR = "Server error! ";
public final static String ERR_NO_OPERATION = "Error! No \"operation\" argument";
public final static String ERR_NO_USER = "Error! No \"user\" argument";
public final static String ERR_ILLEGAL_ARGUMENT = "Error! Illegal argument for this operation";
public final static String ERR_UNKNOWN_OPERATION = "Error! Unknown operation";
public final static String ERR_PROFILE_NOT_FOUND = "Error! Profile not found";
public final static String ERR_USER_NOT_FOUND = "Error! User not found";
public final static String ERR_SAVE_NOTE = "Error! Note not saved";
public final static String ERR_GET_NOTES = "Error! Get notes for user fail";
public final static String ERR_SAVE_IMAGES = "Error! Save images fail";
//Messages
public final static String MSG_EMAIL_UPDATE_FAIL = "Email allready in use";
public final static String MSG_EMAIL_UPDATE_SUCCESS = "User email updated";
public final static String MSG_PASSWORD_UPDATE_SUCCESS = "User password updated";
public final static String MSG_PASSWORD_UPDATE_FAIL = "Password update fail. Old password incorrect";
public final static String MSG_REGISTER_USER_FAIL = "Registration fail. Email allready in use";
public final static String MSG_REGISTER_USER_SUCCESS = "New user registration success";
public final static String MSG_LOGIN_EMAIL_FAIL = "No such user or password incorrect";
public final static String MSG_LOGIN_EMAIL_SUCCESS = "Success login";
public final static String MSG_REGISTER_SOCIAL_SUCCESS = "New user registration success";
public final static String MSG_LOGIN_SOCIAL_SUCCESS = "Success login";
public final static String MSG_LOGIN_SOCIAL_FAIL = "Registration fail";
public final static String MSG_LIST_CITY_FAIL = "Get list cities fail";
public final static String MSG_LIST_CITY_SUCCESS = "Get list cities success";
public final static String MSG_PROFILE_UPDATE_SUCCESS = "Profile update success";
public final static String MSG_B_Q_UPLOAD_SUCCESS = "B_Q upload success";
public final static String MSG_NOTE_SAVE_SUCCESS = "Note save success";
public final static String MSG_GUIDE_DOWNLOAD_SUCCESS = "Guides download success";
public final static String MSG_RECIPE_DOWNLOAD_SUCCESS = "Recipes download success";
public final static String MSG_GET_NOTES_SUCCESS = "Get user notes success";
public final static String MSG_SAVE_IMAGES_SUCCESS = "Save images success";
public final static String MSG_UPDATE_AVATAR_FAIL = "Update avatar fail";
public final static String MSG_UPDATE_AVATAR_SUCCESS = "Update avatar success";
public final static String MSG_SAVE_COMUNITY_RECORD_SUCCESS = "Save community record success";
public final static String MSG_SAVE_COMUNITY_RECORD_FAIL = "Save community record fail";
public final static String MSG_GET_COMMUNITY_RECORDS_SUCCESS = "Get community records success";
public final static String MSG_GET_COMMUNITY_RECORDS_FAIL = "Get community records fail";
public final static String MSG_EDIT_COMUNITY_ITEM_SUCCESS = "Edit community item success";
public final static String MSG_EDIT_COMUNITY_ITEM_FAIL = "Edit community item fail";
public final static String MSG_SAVE_COMMENT_SUCCESS = "Save comment success";
public final static String MSG_SAVE_COMMENT_FAIL = "Save comment fail";
public final static String MSG_GET_COMMENTS_SUCCESS = "Get comments success";
public final static String MSG_GET_COMMENTS_FAIL = "Get comments fail";
public final static String MSG_Q_A_DOWNLOAD_SUCCESS = "QuestionAnswer download success";
public final static String MSG_GET_NOTICES_SUCCESS = "Get notices success";
public final static String MSG_GET_NOTICES_FAIL = "Get notices fail";
public final static String MSG_DELETE_COMMUNITY_FAIL = "Delete community record fail";
public final static String MSG_DELETE_COMMUNITY_SUCCESS = "Delete community record success";
public final static String MSG_DELETE_USER_FAIL = "Delete user record fail";
public final static String MSG_DELETE_USER_SUCCESS = "Delete user record success";
public final static String MSG_IS_USER_LIKE_SUCCESS = "Is user like success";
}
| true
|
77c3ce33adcad7ab11219e6ec83a4b09b1e2748a
|
Java
|
opengeospatial/teamengine-offline
|
/src/test-suite-dependencies/geoapi-pending-3.1-M04-sources/org/opengis/webservice/capability/ServiceProvider.java
|
UTF-8
| 2,829
| 1.65625
| 2
|
[] |
no_license
|
// $Header$
/*---------------- FILE HEADER ------------------------------------------
This file is part of deegree.
Copyright (C) 2001 by:
EXSE, Department of Geography, University of Bonn
http://www.giub.uni-bonn.de/exse/
lat/lon Fitzke/Fretter/Poth GbR
http://www.lat-lon.de
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact:
Andreas Poth
lat/lon Fitzke/Fretter/Poth GbR
Meckenheimer Allee 176
53115 Bonn
Germany
E-Mail: poth@lat-lon.de
Jens Fitzke
Department of Geography
University of Bonn
Meckenheimer Allee 166
53115 Bonn
Germany
E-Mail: jens.fitzke@uni-bonn.de
---------------------------------------------------------------------------*/
package org.opengis.webservice.capability;
// OpenGIS direct dependencies
import org.opengis.webservice.SimpleLink;
import org.opengis.metadata.citation.Contact;
import org.opengis.metadata.identification.KeywordType;
// Annotations
import org.opengis.annotation.UML;
import static org.opengis.annotation.Obligation.*;
import static org.opengis.annotation.Specification.*;
/**
* Represents the ServiceProvider section of the capabilities of an OGC
* compliant web service according to the OGC Common Implementation
* Specification 0.3.
*
* This section corresponds to and expands the SV_ServiceProvider class in ISO
* 19119.
*
* @author <a href="mailto:mschneider@lat-lon.de">Markus Schneider </a>
*/
public interface ServiceProvider {
/**
* Returns the contactInfo.
*/
@UML(identifier="contactInfo", specification=UNSPECIFIED)
Contact getContactInfo();
/**
* Returns the individualName.
*/
@UML(identifier="individualName", specification=UNSPECIFIED)
String getIndividualName();
/**
* Returns the positionName.
*/
@UML(identifier="positionName", specification=UNSPECIFIED)
String getPositionName();
/**
* Returns the providerName.
*/
@UML(identifier="providerName", specification=UNSPECIFIED)
String getProviderName();
/**
* Returns the providerSite.
*/
@UML(identifier="providerSite", specification=UNSPECIFIED)
SimpleLink getProviderSite();
/**
* Returns the role.
*/
KeywordType getRole();
}
| true
|
2e2a4ba221f92e0dec3a6466e709e9f9f931b958
|
Java
|
Taskyers/tasky-base
|
/src/main/java/pl/taskyers/taskybase/project/slo/ProjectSettingsSLOImpl.java
|
UTF-8
| 5,499
| 2.015625
| 2
|
[] |
no_license
|
package pl.taskyers.taskybase.project.slo;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import pl.taskyers.taskybase.core.messages.MessageCode;
import pl.taskyers.taskybase.core.messages.MessageType;
import pl.taskyers.taskybase.core.messages.ResponseMessage;
import pl.taskyers.taskybase.core.messages.container.ValidationMessageContainer;
import pl.taskyers.taskybase.core.roles.constants.Roles;
import pl.taskyers.taskybase.core.roles.dao.RoleDAO;
import pl.taskyers.taskybase.core.slo.AuthProvider;
import pl.taskyers.taskybase.core.users.entity.UserEntity;
import pl.taskyers.taskybase.core.validator.Validator;
import pl.taskyers.taskybase.project.converter.ProjectConverter;
import pl.taskyers.taskybase.project.dao.ProjectDAO;
import pl.taskyers.taskybase.project.dto.ProjectDTO;
import pl.taskyers.taskybase.project.dto.SettingsEntryResponseData;
import pl.taskyers.taskybase.project.entity.ProjectEntity;
import java.util.Optional;
@Service
@AllArgsConstructor
public class ProjectSettingsSLOImpl implements ProjectSettingsSLO {
private final AuthProvider authProvider;
private final RoleDAO roleDAO;
private final ProjectDAO projectDAO;
private final Validator<ProjectEntity> projectValidator;
@Override
public ResponseEntity updateBasicData(Long id, ProjectDTO projectDTO) {
Optional<ProjectEntity> projectEntityOptional = projectDAO.getProjectEntityById(id);
if ( projectEntityOptional.isPresent() ) {
ProjectEntity projectEntity = projectEntityOptional.get();
if ( roleDAO.hasPermission(authProvider.getUserEntity(), projectEntity, Roles.SETTINGS_EDIT_PROJECT) ) {
ProjectEntity projectEntityFromDTO = ProjectConverter.convertFromDTO(projectDTO);
ValidationMessageContainer validationMessageContainer = new ValidationMessageContainer();
if ( !projectEntity.getName().equals(projectDTO.getName()) ) {
projectValidator.validate(projectEntityFromDTO, validationMessageContainer, true);
} else {
projectValidator.validate(projectEntityFromDTO, validationMessageContainer, false);
}
if ( validationMessageContainer.hasErrors() ) {
return ResponseEntity.badRequest().body(validationMessageContainer.getErrors());
}
ProjectEntity updatedProject = projectDAO.updateProject(projectEntity, projectDTO.getName(), projectDTO.getDescription());
return ResponseEntity.ok(new ResponseMessage<>(MessageCode.project_updated.getMessage(), MessageType.SUCCESS, updatedProject));
}
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new ResponseMessage<>(MessageCode.project_permission_not_granted.getMessage(), MessageType.ERROR));
}
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ResponseMessage<>(MessageCode.project_not_found.getMessage("id", id), MessageType.ERROR));
}
@Override
public ResponseEntity deleteProject(Long id) {
Optional<ProjectEntity> projectEntityOptional = projectDAO.getProjectEntityById(id);
if ( projectEntityOptional.isPresent() ) {
if ( roleDAO.hasPermission(authProvider.getUserEntity(), projectEntityOptional.get(), Roles.SETTINGS_DELETE_PROJECT) ) {
projectDAO.deleteProjectById(id);
return ResponseEntity.ok(new ResponseMessage<>(MessageCode.project_deleted.getMessage(), MessageType.SUCCESS));
}
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new ResponseMessage<>(MessageCode.project_permission_not_granted.getMessage(), MessageType.ERROR));
}
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ResponseMessage<>(MessageCode.project_not_found.getMessage("id", id), MessageType.ERROR));
}
@Override
public ResponseEntity hasProperRoleOnEntry(String projectName) {
if ( projectDAO.getProjectEntityByName(projectName).isPresent() ) {
final ProjectEntity projectEntity = projectDAO.getProjectEntityByName(projectName).get();
final UserEntity userEntity = authProvider.getUserEntity();
final boolean canEdit = roleDAO.hasPermission(userEntity, projectEntity, Roles.SETTINGS_EDIT_PROJECT);
final boolean canDelete = roleDAO.hasPermission(userEntity, projectEntity, Roles.SETTINGS_DELETE_PROJECT);
return (canEdit || canDelete) ? ResponseEntity.ok(createEntryData(projectEntity, canEdit, canDelete)) :
ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new ResponseMessage<>(MessageCode.project_permission_not_granted.getMessage(), MessageType.ERROR));
}
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ResponseMessage<>(MessageCode.project_not_found.getMessage("name", projectName), MessageType.WARN));
}
private SettingsEntryResponseData createEntryData(ProjectEntity projectEntity, boolean canEdit, boolean canDelete) {
return new SettingsEntryResponseData(projectEntity.getId(), projectEntity.getName(), projectEntity.getDescription(), canEdit, canDelete);
}
}
| true
|
00aca122e665c8a2062e042fdf75b8a4ce141755
|
Java
|
JoshuaKincannon/Project-350
|
/Launch/gameLauncher.java
|
UTF-8
| 5,803
| 2.96875
| 3
|
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class gameLauncher implements ActionListener {
private static JTextField userText;
private static JPasswordField passwordText;
private static JTextField createUserText;
private static JTextField createUserPassword;
private static JTextField verify;
private static JLabel results;
public static void launchGames() {
JFrame frame = new JFrame("350Games");
frame.setSize(500, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
tp.addTab("Games", new GamePlatform.GridPanel());
frame.getContentPane().add(tp);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
/*Text Fields that we will be checking are userText &&
* passwordText, createUserText && createUserPassword && verify*/
String users = userText.getText();
String usersPassword = passwordText.getText();
String createUsers = createUserText.getText();
String createPass = createUserPassword.getText();
String verifyPass = verify.getText();
boolean hasUserName=false;
results.setText("Searching Credentials...");
String path = "/Users/megtreiber/Documents/usernames.txt";
String line = "";
System.out.println(users);
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//Create a map hashmap() to hold people in memory so I don't write over them.
if(users.equals(values[0]) && usersPassword.equals(values[1])){
launchGames();
results.setText("Login Successful");
}else if(createUsers.equals(values[0])){
hasUserName = true;
results.setText("User Already Exists");
}else{
results.setText("TRY AGAIN");
}
}
br.close();
} catch (IOException g) {
g.printStackTrace();
}
if(!hasUserName && createPass.equals(verifyPass) && !createUsers.isEmpty() && !verifyPass.isEmpty()){
try (FileWriter writer = new FileWriter("/Users/megtreiber/Documents/usernames.txt", true);
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write("\n" + createUsers + "," + createPass);
results.setText("UserName Created");
launchGames();
} catch (IOException l) {
System.err.format("IOException: %s%n", l);
}
}else{
results.setText("Invalid Entry!");
}
}
//System.out.println("Button Clicked!");
public static void main (String[]args){
JPanel logPanel = new JPanel();
JFrame logFrame = new JFrame();
logFrame.setSize(400, 350);
logFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
logFrame.add(logPanel);
logPanel.setLayout(null);
//The label for the username text field
JLabel logUser = new JLabel("Username:");
logUser.setBounds(10, 20, 80, 25);
logPanel.add(logUser);
//The label for the password text field
JLabel passwordLabel1 = new JLabel("Password:");
passwordLabel1.setBounds(10, 50, 80, 25);
logPanel.add(passwordLabel1);
//The button that logs you in
JButton login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(new gameLauncher());
logPanel.add(login);
//The label for the username text field in create user
JLabel createUser = new JLabel("Username:");
createUser.setBounds(10, 110, 100, 25);
logPanel.add(createUser);
//The label for the username password to create a login
JLabel createPassword = new JLabel("Enter Password:");
createPassword.setBounds(10, 140, 120, 25);
logPanel.add(createPassword);
//The label to verify the passwor dof an account being created
JLabel verifyLabel = new JLabel("Re-Enter Password:");
verifyLabel.setBounds(10, 170, 140, 25);
logPanel.add(verifyLabel);
//The label for the game log in or create account buttons also where we launch gridbag layout
results = new JLabel("");
results.setBounds(10, 230, 250, 25);
logPanel.add(results);
//Where the existing user enters their information.
userText = new JTextField();
userText.setBounds(160, 20, 200, 25);
logPanel.add(userText);
//Where the existing user enters their password
passwordText = new JPasswordField();
passwordText.setBounds(160, 50, 200, 25);
logPanel.add(passwordText);
//Where the new user creates their account name
createUserText = new JTextField();
createUserText.setBounds(160, 110, 200, 25);
logPanel.add(createUserText);
//Where the new user enters their password
createUserPassword = new JTextField();
createUserPassword.setBounds(160, 140, 200, 25);
logPanel.add(createUserPassword);
verify = new JTextField();
verify.setBounds(160, 170, 200, 25);
logPanel.add(verify);
JButton creates = new JButton("Create Account!");
creates.setBounds(10, 200, 150, 25);
creates.addActionListener(new gameLauncher());
logPanel.add(creates);
logFrame.setVisible(true);
}
}
| true
|
f15dd1638e328cde9cd87d5c29ae4b4b52d086bb
|
Java
|
siguangli/Hippy
|
/examples/android-demo/src/main/java/com/tencent/mtt/hippy/example/MyActivityTiny.java
|
UTF-8
| 3,978
| 2.15625
| 2
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
package com.tencent.mtt.hippy.example;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Window;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tencent.mtt.hippy.HippyEngine;
import com.tencent.mtt.hippy.HippyEngine.EngineInitStatus;
import com.tencent.mtt.hippy.HippyRootView;
import com.tencent.mtt.hippy.adapter.image.HippyDrawable;
import com.tencent.mtt.hippy.adapter.image.HippyImageLoader;
import com.tencent.mtt.hippy.utils.LogUtils;
@SuppressWarnings({"unused"})
public class MyActivityTiny extends Activity
{
private HippyEngine mHippyEngine;
private HippyRootView mHippyView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// 1/3. 初始化hippy引擎
{
HippyEngine.EngineInitParams initParams = new HippyEngine.EngineInitParams();
// 必须:hippy运行环境的context。
// 若存在多个Activity加载多个业务jsbundle的情况,则这里初始化引擎时建议使用Application的Context
initParams.context = this;
// 必须:图片加载器
initParams.imageLoader = new HippyImageLoader()
{
// 网络图片加载,异步加载
@Override
public void fetchImage(final String url, final Callback requestCallback, Object param)
{
//noinspection unchecked,rawtypes
Glide.with(MyActivityTiny.this).load(url).asBitmap().into(new SimpleTarget() {
@Override
public void onResourceReady(Object object, GlideAnimation glideAnimation) {
HippyDrawable hippyTarget = new HippyDrawable();
if (object instanceof Bitmap)
hippyTarget.setData((Bitmap) object);
requestCallback.onRequestSuccess(hippyTarget);
}
});
}
};
// 可选:debugMode = false 时必须设置(debugMode = true时,所有jsbundle都是从debug server上下载)
initParams.coreJSAssetsPath = "vendor.android.js";
// 根据EngineInitParams创建引擎实例
mHippyEngine = HippyEngine.create(initParams);
// 异步初始化Hippy引擎
mHippyEngine.initEngine(new HippyEngine.EngineListener() {
// Hippy引擎初始化完成
/**
* @param statusCode status code from initializing procedure
* @param msg Message from initializing procedure
*/
@Override
public void onInitialized(EngineInitStatus statusCode, String msg) {
if (statusCode != EngineInitStatus.STATUS_OK)
LogUtils.e("MyActivity", "hippy engine init failed code:" + statusCode + ", msg=" + msg);
// else
{
// 2/3. 加载hippy前端模块
HippyEngine.ModuleLoadParams loadParams = new HippyEngine.ModuleLoadParams();
// 必须:该Hippy模块将要挂在的Activity or Dialog的context
loadParams.context = MyActivityTiny.this;
/*
必须:指定要加载的Hippy模块里的组件(component)。componentName对应的是js文件中的"appName",比如:
var hippy = new Hippy({
appName: "Demo",
entryPage: App
});
*/
loadParams.componentName = "Demo";
/*
可选:二选一设置。自己开发的业务模块的jsbundle的assets路径(assets路径和文件路径二选一,优先使用assets路径)
debugMode = false 时必须设置jsAssetsPath或jsFilePath(debugMode = true时,所有jsbundle都是从debug server上下载)
*/
loadParams.jsAssetsPath = "index.android.js";
// 加载Hippy前端模块
mHippyView = mHippyEngine.loadModule(loadParams);
setContentView(mHippyView);
}
}
});
}
}
@Override
protected void onDestroy()
{
// 3/3. 摧毁hippy前端模块,摧毁hippy引擎
mHippyEngine.destroyModule(mHippyView);
mHippyEngine.destroyEngine();
super.onDestroy();
}
}
| true
|
75cfb3fc019853aac9cdad9c767e1d1592fd6789
|
Java
|
SunrhLeo/lucker-stocks
|
/luckers-stocks/src/main/java/cn/edu/nju/luckers/luckers_stocks/data/network/service/StockDataGetter.java
|
UTF-8
| 4,308
| 2.84375
| 3
|
[] |
no_license
|
package cn.edu.nju.luckers.luckers_stocks.data.network.service;
import java.io.IOException;
import java.util.ArrayList;
import cn.edu.nju.luckers.luckers_stocks.data.network.exception.ConnectionFailure;
import cn.edu.nju.luckers.luckers_stocks.data.network.po.stock.StockPO;
public interface StockDataGetter {
public static final String SZ = "sz";
public static final String SH = "sh";
public static final String BENCHMARK_HS300 = "hs300";
/**
* @param year 年份,可以为null,将返回默认结果(我也不知道默认结果是啥,下同)
* @param exchange 交易所,只有三个可选值:StockDataGetter.SZ(代表深圳交易所)
* ,StockDataGetter.SH(代表上海交易所) 和 null,如果输入其他值
* ,将返回未知结果或抛出未知异常,输入null将返回默认结果
* @return 返回在指定条件下的股票代码名单
* @throws IOException 代表从服务器上读取此列表失败
* @throws ConnectionFailure
*/
public ArrayList<String> getStockIDList(String year, String exchange) throws IOException, ConnectionFailure;
/**
* @param id 比如:sh600000 不能为null
* @param startDay 起始时间,格式'YYYY-mm-dd',可以为null(起始时间和结束时间不同时为null时,我也不知道会返回什么)
* @param endDay 结束时间,格式'YYYY-mm-dd',可以为null(起始时间和结束时间不同时为null时,我也不知道会返回什么)
* @param fields 指定数据字段(可以为null,为null时返回全部交易数据)
* 格式: name1+name2+name3(可以有多个),具体字段请参考为StockDataPO.STOCK_FIELDS_TYPE
* :open: 开盘价,high: 最高价
* ,low: 最低价,close: 收盘价,adj_price: 后复权价,volume: 成交量,turnover: 换手率
* ,pe: 市盈率,pb: 市净率
* @return 返回指定股票代码的股票交易数据,默认返回过去一个月的全部交易数据
* @throws IOException 代表从服务器上读取此股票失败
* PS by MZC:该方法最快只能获得昨天的数据,且返回时不包括结束日期的数据,想要某一天的数据
* 起始日期选择当天,结束日期选择后一天
* 获得不了当天的数据真实脑残....
* @throws ConnectionFailure */
public StockPO getStockByID(String id,String startDay, String endDay,String fields) throws IOException, ConnectionFailure;
/**
* @param id 比如:hs300,也可以调用此接口的静态常量 不能为null
* @param startDay 起始时间,格式'YYYY-mm-dd',可以为null(起始时间和结束时间不同时为null时,我也不知道会返回什么)
* @param endDay 结束时间,格式'YYYY-mm-dd',可以为null(起始时间和结束时间不同时为null时,我也不知道会返回什么)
* @param fields 指定数据字段(可以为null,为null时返回全部交易数据)
* 格式: name1+name2+name3(可以有多个),具体字段请参考StockDataPO.BENCHMARK_FIELDS_TYPE
* @return 返回指定大盘指数代码的交易数据,默认返回一年内的所有数据(经过测试得出的结论)
* @throws IOException 代表从服务器上读取此股票失败
* @throws ConnectionFailure
*/
public StockPO getBenchmarkByID(String id,String startDay, String endDay,String fields) throws IOException, ConnectionFailure;
/**
* 根据输入的股票去读取其对应的名字
* Copyright@ 新浪财经,如侵必删,详请联系@author zzzzzyx@outlook.com
* @param stockCodeList
* @return 返回的结果列表与输入的列表按顺序一一对应,如果列表某项股票无法读取,对应的一项值为null
* @throws IOException
* @throws ConnectionFailure
*/
public ArrayList<String> getStockName(ArrayList<String> stockCodeList) throws IOException, ConnectionFailure;
/**
* 根据股票代码从外网读取其行业名,如输入为'sh600485'(即信威集团), 将返回'通信设备'
* Copyright@ 网易财经,如侵必删,详请联系@author zzzzzyx@outlook.com
* @param stockCode 股票代码
* @return 行业名称
* @throws IOException
* @throws ConnectionFailure
*/
public String getIndustryName(String stockCode) throws IOException, ConnectionFailure;
}
| true
|
ab99d2a4b794f0bf3184001c8ca760d8167c13c6
|
Java
|
ht5678/TestProject
|
/src/license/rsa/RSACoderTest.java
|
UTF-8
| 2,331
| 3.0625
| 3
|
[] |
no_license
|
package license.rsa;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RSACoderTest {
private String publicKey;
private String privateKey;
@Before
public void setUp()throws Exception{
Map<String, Object> keyMap = RSACoder.initKey();
publicKey = RSACoder.getPublicKey(keyMap);
privateKey = RSACoder.getPrivateKey(keyMap);
System.err.println("公钥: \n\r" + publicKey);
System.err.println("私钥: \n\r" + privateKey);
}
/**
* 公钥加密----私钥解密
* @throws Exception
*/
@Test
public void testPub2Pri()throws Exception{
System.err.println("公钥加密----私钥解密");
String inputStr = "abc";
byte[] data = inputStr.getBytes();
byte[] encodedData = RSACoder.encryptByPublicKey(data, publicKey);
byte[] decodedData = RSACoder.decryptByPrivateKey(encodedData, privateKey);
String outputStr = new String(decodedData);
System.err.println("加密前:"+inputStr +"\n\r"+"解密后"+outputStr);
Assert.assertEquals(inputStr, outputStr);
}
/**
* 私钥加密----公钥解密
* @throws Exception
*/
@Test
public void testPri2Pub()throws Exception{
System.err.println("私钥加密----公钥解密");
String inputStr = "sign";
byte[] data = inputStr.getBytes();
byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey);
byte[] decodedData = RSACoder.decryptByPublicKey(encodedData, publicKey);
String outputStr = new String(decodedData);
Assert.assertEquals(inputStr, outputStr);//使用Junit断言,加密前的原文与解密后的明文是否一致
System.err.println("私钥签名---公钥验证签名");
//产生签名,这里的encodedData可以和下面的encodedData同时换成new int[]{2,45}
String sign = RSACoder.sign(encodedData, privateKey);//数字签名只要公钥人拿到签名的sign对比
//自己公钥通过同样的byte[]运算得到签名是否一致。是一致代表这个公钥是对的,就是为现在发私钥人服务的
System.err.println("签名:\r"+sign);
//验证签名
boolean status = RSACoder.verify(encodedData, publicKey, sign);
System.err.println("状态:\r"+status);
Assert.assertTrue(status);
}
}
| true
|
5c159f64ecd2559fde87ff9c753a624adef12d88
|
Java
|
liangperfect/Fussion
|
/WestAlgoFussion/src/com/westalgo/factorycamera/app/AppController.java
|
UTF-8
| 2,158
| 1.898438
| 2
|
[] |
no_license
|
/*
* 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.westalgo.factorycamera.app;
import com.westalgo.factorycamera.ButtonManager;
import com.westalgo.factorycamera.MediaSaveService;
import com.westalgo.factorycamera.module.ModuleController;
import com.westalgo.factorycamera.settings.SettingsManager;
import android.content.Context;
import android.view.View;
/**
* The controller at app level.
*/
public interface AppController {
/**
* @return the {@link android.content.Context} being used.
*/
public Context getAndroidContext();
public CameraAppUI getCameraAppUI();
/**
* This gets called when mode is changed.
*
* @param moduleIndex index of the new module to switch to
*/
public void onModeSelected(int moduleIndex);
/**
* This gets called when settings is selected and settings dialog needs to open.
*/
public void onSettingsSelected();
public int getCurrentModuleIndex();
public ModuleController getCurrentModuleController();
public SettingsManager getSettingsManager();
/**
* @return a String scope uniquely identifing the current module.
*/
public String getModuleScope();
/**
* @return a String scope uniquely identifing the current camera id.
*/
public String getCameraScope();
/**
* Returns the {@link com.westalgo.factorycamera.ButtonManager}.
*/
public ButtonManager getButtonManager();
public MediaSaveService getMediaSaveService();
public void gotoGallery();
public void onViewClicked(View v);
}
| true
|
dc6fc64b21b446beba27d665564240c3458f3310
|
Java
|
z-salang/init
|
/src/main/java/com/zdd/project/collection/list/BatchInsert.java
|
UTF-8
| 721
| 3.109375
| 3
|
[] |
no_license
|
package com.zdd.project.collection.list;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
*
* @author <a href="zdd109067@alibaba-inc.com">zhoudongdong</a>
* @version create on 2017/10/23 上午11:32
*/
public class BatchInsert {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 103; ++i) {
list.add(i);
}
System.out.println("Size of list = " + list.size());
int from = 0;
while (from < list.size()) {
int end = Math.min(list.size(), from + 30);
List<Integer> sublist = list.subList(from, end);
System.out.printf("Size of sublist = %d, sublist = %s\n", sublist.size(), sublist);
from = end;
}
}
}
| true
|
759a26f5ac55a4a354604dd5583d78a21e5012cd
|
Java
|
junaidp/gwtapplication
|
/target/.generated/com/smartgwt/client/types/DSOperationType_FieldSerializer.java
|
UTF-8
| 2,349
| 2.15625
| 2
|
[] |
no_license
|
package com.smartgwt.client.types;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.impl.ReflectionHelper;
@SuppressWarnings("deprecation")
public class DSOperationType_FieldSerializer implements com.google.gwt.user.client.rpc.impl.TypeHandler {
private static native java.lang.String getValue(com.smartgwt.client.types.DSOperationType instance) /*-{
return instance.@com.smartgwt.client.types.DSOperationType::value;
}-*/;
private static native void setValue(com.smartgwt.client.types.DSOperationType instance, java.lang.String value)
/*-{
instance.@com.smartgwt.client.types.DSOperationType::value = value;
}-*/;
public static void deserialize(SerializationStreamReader streamReader, com.smartgwt.client.types.DSOperationType instance) throws SerializationException {
// Enum deserialization is handled via the instantiate method
}
public static com.smartgwt.client.types.DSOperationType instantiate(SerializationStreamReader streamReader) throws SerializationException {
int ordinal = streamReader.readInt();
com.smartgwt.client.types.DSOperationType[] values = com.smartgwt.client.types.DSOperationType.values();
assert (ordinal >= 0 && ordinal < values.length);
return values[ordinal];
}
public static void serialize(SerializationStreamWriter streamWriter, com.smartgwt.client.types.DSOperationType instance) throws SerializationException {
assert (instance != null);
streamWriter.writeInt(instance.ordinal());
}
public Object create(SerializationStreamReader reader) throws SerializationException {
return com.smartgwt.client.types.DSOperationType_FieldSerializer.instantiate(reader);
}
public void deserial(SerializationStreamReader reader, Object object) throws SerializationException {
com.smartgwt.client.types.DSOperationType_FieldSerializer.deserialize(reader, (com.smartgwt.client.types.DSOperationType)object);
}
public void serial(SerializationStreamWriter writer, Object object) throws SerializationException {
com.smartgwt.client.types.DSOperationType_FieldSerializer.serialize(writer, (com.smartgwt.client.types.DSOperationType)object);
}
}
| true
|
651532aafd94022e131268f6dd708d4af4d0f769
|
Java
|
Yeo-injun/-staysinchon-backend
|
/src/main/java/com/project/sinchon/entity/RoomEntity.java
|
UTF-8
| 390
| 1.953125
| 2
|
[] |
no_license
|
package com.project.sinchon.entity;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RoomEntity {
private int roomId;
private String roomName;
private String roomType;
private String roomImg;
private String bed;
private String bathroom;
private int capacity;
private int priceDay;
private int priceMonth;
}
| true
|
ef8451e0dacd3c7502194f8ef4a80d9c8806c1c1
|
Java
|
sterlp/training
|
/spring-redis/src/main/java/org/sterl/training/redis/complex/dao/RoomDao.java
|
UTF-8
| 303
| 1.875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.sterl.training.redis.complex.dao;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.sterl.training.redis.complex.model.RoomBE;
public interface RoomDao extends CrudRepository<RoomBE, String> {
List<RoomBE> findByPersonsName(String name);
}
| true
|
9c2cb78001b586753abc55d62a0b08df5c29111d
|
Java
|
mr-bhuvaneswaran/FAB
|
/app/src/main/java/chatapp/com/chatapp/Friends.java
|
UTF-8
| 349
| 2
| 2
|
[] |
no_license
|
package chatapp.com.chatapp;
/**
* Created by bhuvanes on 2/9/17.
*/
public class Friends {
public Friends() {
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String date;
public Friends(String date) {
this.date = date;
}
}
| true
|
b20907d05924d274c629432abcabeb6a5f25455f
|
Java
|
shizidong/jzalgorithm
|
/Stack/chap30/major.java
|
UTF-8
| 327
| 2.6875
| 3
|
[] |
no_license
|
package code.Stack.chap30;
public class major {
public static void main(String[] args) {
solution s = new solution();
s.push(3);
s.push(4);
s.push(2);
s.push(5);
System.out.println(s.min());
s.pop();
System.out.println(s.top());
s.pop();
System.out.println(s.min());
System.out.println(s.top());
}
}
| true
|
1c7d9590b27e3c2d67503e542996ca0ee2511d14
|
Java
|
DmitryKropotov/metaprime
|
/src/main/java/com/project/controller/EmployerController.java
|
UTF-8
| 248
| 2.015625
| 2
|
[] |
no_license
|
package com.project.controller;
import com.project.model.Employer;
import java.util.Optional;
public interface EmployerController {
Employer save(Employer employer);
Optional<Employer> findById(int id);
void deleteById(int id);
}
| true
|
162494f74f6b44eb1df906d57755acfbb12a6f01
|
Java
|
cha63506/CompSecurity
|
/collage-source/src/com/google/android/gms/internal/ga.java
|
UTF-8
| 4,503
| 1.5
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
import android.content.Context;
import android.os.Handler;
import android.os.RemoteException;
import com.google.android.gms.ads.internal.request.AdRequestInfoParcel;
import com.google.android.gms.ads.internal.util.client.zza;
import com.google.android.gms.ads.internal.util.client.zzb;
import com.google.android.gms.ads.internal.zzp;
// Referenced classes of package com.google.android.gms.internal:
// gs, gc, gf, fz,
// dj, ix, ge
public class ga extends gs
implements gc, gf
{
private final gl.a a;
private final Context b;
private final fz c;
private final gf d;
private final Object e = new Object();
private final String f;
private final String g;
private final String h;
private int i;
private int j;
public ga(Context context, String s, String s1, String s2, gl.a a1, fz fz1, gf gf1)
{
i = 0;
j = 3;
b = context;
f = s;
h = s1;
g = s2;
a = a1;
c = fz1;
d = gf1;
}
static String a(ga ga1)
{
return ga1.g;
}
static String b(ga ga1)
{
return ga1.f;
}
private void b(long l)
{
_L1:
label0:
{
synchronized (e)
{
if (i == 0)
{
break label0;
}
}
return;
}
if (a(l))
{
break MISSING_BLOCK_LABEL_35;
}
obj;
JVM INSTR monitorexit ;
return;
exception;
obj;
JVM INSTR monitorexit ;
throw exception;
obj;
JVM INSTR monitorexit ;
goto _L1
}
static Context c(ga ga1)
{
return ga1.b;
}
static String d(ga ga1)
{
return ga1.h;
}
public void a()
{
c.b();
com.google.android.gms.ads.internal.client.AdRequestParcel adrequestparcel = a.a.zzDy;
dj dj1 = c.a();
try
{
dj1.a(adrequestparcel, g);
return;
}
catch (RemoteException remoteexception)
{
zzb.zzd("Fail to load ad from adapter.", remoteexception);
}
a(f, 0);
}
public void a(int k)
{
a(f, 0);
}
public void a(String s)
{
synchronized (e)
{
i = 1;
e.notify();
}
return;
exception;
s;
JVM INSTR monitorexit ;
throw exception;
}
public void a(String s, int k)
{
synchronized (e)
{
i = 2;
j = k;
e.notify();
}
return;
exception;
s;
JVM INSTR monitorexit ;
throw exception;
}
protected boolean a(long l)
{
l = 20000L - (zzp.zzbB().b() - l);
if (l <= 0L)
{
return false;
}
try
{
e.wait(l);
}
catch (InterruptedException interruptedexception)
{
return false;
}
return true;
}
public void onStop()
{
}
public void zzdG()
{
ge ge1;
com.google.android.gms.ads.internal.client.AdRequestParcel adrequestparcel;
dj dj1;
if (c == null || c.b() == null || c.a() == null)
{
return;
}
ge1 = c.b();
ge1.a(this);
ge1.a(this);
adrequestparcel = a.a.zzDy;
dj1 = c.a();
if (!dj1.g())
{
break MISSING_BLOCK_LABEL_135;
}
zza.zzIy.post(new zzgz._cls1(this, dj1, adrequestparcel));
_L1:
b(zzp.zzbB().b());
ge1.a(null);
ge1.a(null);
RemoteException remoteexception;
if (i == 1)
{
d.a(f);
return;
} else
{
d.a(f, j);
return;
}
try
{
zza.zzIy.post(new zzgz._cls2(this, dj1, adrequestparcel, ge1));
}
// Misplaced declaration of an exception variable
catch (RemoteException remoteexception)
{
zzb.zzd("Fail to check if adapter is initialized.", remoteexception);
a(f, 0);
}
goto _L1
}
}
| true
|
9d391cdf9111e258dd25e04a27cea2583729657c
|
Java
|
AbelKinkela/Netbeans_Projects
|
/PayrollSystem/src/Learning/Algorithms/MergeSortTest.java
|
UTF-8
| 705
| 3.265625
| 3
|
[] |
no_license
|
package Learning.Algorithms;
/*
* 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.
*/
/**
*
* @author Marcelo
*/
public class MergeSortTest {
public static void main(String[] args) {
// create object to perform merge sort
MergeSort sortArray = new MergeSort(10);
// print unsorted array
System.out.println("Unsorted:" + sortArray + "\n");
sortArray.sort(); // sort array
// print sorted array
System.out.println("Sorted: " + sortArray);
} // end main
} // end class MergeSortTest
| true
|
a90e3328665450de74dd8941aadba8f0cf324e74
|
Java
|
suzeyinhappyboy/Android-Opencv-AR-tutorial
|
/AndroidOpencvARTutorial/src/zh/wang/android/opencv/ar/OpenCVARView.java
|
UTF-8
| 5,732
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package zh.wang.android.opencv.ar;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.os.Build;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class OpenCVARView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private static final String TAG = "OpenCVARView";
private static int MAGIC_TEXTURE_ID = 10;
private Camera mCamera;
private SurfaceHolder mHolder;
private SurfaceTexture mSurfaceTexture;
private int mFrameWidth;
private int mFrameHeight;
private byte[] mFrame;
private boolean mThreadRun;
public OpenCVARView(Context context) {
super(context);
getHolder().addCallback(this);
Log.i(TAG, "Instantiated new " + this.getClass());
mSurfaceTexture = new SurfaceTexture(10);
}
public int getFrameWidth() {
return mFrameWidth;
}
public int getFrameHeight() {
return mFrameHeight;
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
Log.d(TAG, "surfaceChanged");
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
mFrameWidth = width / 2;
mFrameHeight = height / 2;
// selecting optimal camera preview size
{
double minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
Log.d(TAG, "size : " + size.width + ", " + size.height);
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = size.width;
mFrameHeight = size.height;
minDiff = Math.abs(size.height - height);
}
}
}
Log.d(TAG, "change preview size to : " + mFrameWidth + ", " + mFrameHeight);
mHolder = _holder;
params.setPreviewSize(getFrameWidth(), getFrameHeight());
mCamera.setParameters(params);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
mCamera.setPreviewTexture(mSurfaceTexture);
// TODO Auto-generated catch block
} else {
mCamera.setPreviewDisplay(null);
}
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}
public void surfaceCreated(final SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
mCamera = Camera.open();
mCamera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
synchronized (OpenCVARView.this) {
mFrame = data;
OpenCVARView.this.notify();
}
}
});
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "surfaceDestroyed");
mThreadRun = false;
if (mCamera != null) {
synchronized (this) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
}
public void run() {
mThreadRun = true;
Log.d(TAG, "Starting processing thread");
while (mThreadRun) {
Bitmap bmp = null;
synchronized (this) {
try {
this.wait();
bmp = processFrame(mFrame);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (bmp != null) {
Log.d(TAG, "bitmap: " + bmp.getWidth() + ", " + bmp.getHeight());
if (mHolder == null) {
Log.d(TAG, "mHolder is null");
}
if (!mHolder.getSurface().isValid()) {
Log.d(TAG, "surface is not valid");
}
Canvas canvas = mHolder.lockCanvas();
if (canvas == null) {
Log.d(TAG, "canvas is null");
}
Paint paint = new Paint();
paint.setColor(0xFFFF0000);
if (canvas != null) {
canvas.drawBitmap(bmp, (canvas.getWidth() - getFrameWidth()) / 2, (canvas.getHeight() - getFrameHeight()) / 2, null);
mHolder.unlockCanvasAndPost(canvas);
}
bmp.recycle();
}
}
}
protected Bitmap processFrame(byte[] data) {
int frameSize = getFrameWidth() * getFrameHeight();
int[] rgba = new int[frameSize];
FindFeatures(getFrameWidth(), getFrameHeight(), data, rgba);
Bitmap bmp = Bitmap.createBitmap(getFrameWidth(), getFrameHeight(), Bitmap.Config.ARGB_8888);
bmp.setPixels(rgba, 0/* offset */, getFrameWidth() /* stride */, 0, 0, getFrameWidth(), getFrameHeight());
return bmp;
}
public native void FindFeatures(int width, int height, byte yuv[], int[] rgba);
}
| true
|
e8c1955b86197fd15e27aaeb2fa63bb6f9b07ffe
|
Java
|
Dev-fil/JavaPrograms
|
/positive_priting.java
|
UTF-8
| 671
| 3.46875
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class positive_priting{
public static void main(String[] args) {
System.out.println("Enter lower limit of range");
Scanner l=new Scanner(System.in);
int r1=l.nextInt();
System.out.println("Enter upper limit of range");
Scanner u=new Scanner(System.in);
int r2=u.nextInt();
System.out.println("THE RANGE ENTERED BY USER IS "+r1+" - "+r2);
System.out.println("Positive integers between them are :");
int i=r1;
while(i<=r2){
if(i%2==0){
System.out.println(i);
}
i++;
}
}
}
| true
|
fd6fc6f20345e0cab85db8e94c865b3c524dfa36
|
Java
|
tonussi/inseguro
|
/ciphers/Vigenere.java
|
UTF-8
| 1,472
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
public class Vigenere {
// http://www.asciitable.com/
public static void main(String[] args) {
String key = "gandalf";
String plainText = "whatanunpredictableworldweliveright";
String encryptedText = vigenereCipher(plainText, key);
String decriptedText = vigenereDecipher(encryptedText, key);
System.out.println(encryptedText);
System.out.println(decriptedText);
System.out.println((-2) % 26);
}
public static String vigenereCipher(String plainText, String key) {
String cipherText = "";
plainText.toLowerCase();
plainText.trim();
key.toLowerCase();
for (int i = 0; i < plainText.length(); i++) {
char letter = (char) (((int) plainText.charAt(i) - (int) 'a'
+ (int) key.charAt(i % key.length()) - (int) 'a') % 26 + (int) 'A');
cipherText = cipherText + letter;
}
return cipherText;
}
public static String vigenereDecipher(String cipherText, String key) {
String plainText = "";
String plaint = "";
cipherText.toUpperCase();
key.toLowerCase();
for (int i = 0; i < cipherText.length(); i++) {
int cipherAt = (int) cipherText.charAt(i) - (int) 'A';
int keyAt = (int) key.charAt(i % key.length()) - (int) 'a';
int resultKey = (cipherAt - keyAt);
System.out.println(resultKey);
if (resultKey < 0) {
resultKey = resultKey + 26;
System.out.println(resultKey);
}
resultKey = (int)resultKey % 26 + (int) 'a';
plainText = plainText + (char) resultKey;
}
return plainText;
}
}
| true
|
9881d22a693c9d85932f2ad7971ca67da4efbad6
|
Java
|
DataBiosphere/jade-data-repo
|
/src/test/java/bio/terra/integration/DataRepoResponse.java
|
UTF-8
| 941
| 2.078125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package bio.terra.integration;
import bio.terra.model.ErrorModel;
import java.util.Optional;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.http.HttpStatus;
/** Specialization of ObjectOrErrorResponse for ErrorModel */
public class DataRepoResponse<T> {
private ObjectOrErrorResponse<ErrorModel, T> response;
public DataRepoResponse(ObjectOrErrorResponse<ErrorModel, T> response) {
this.response = response;
}
public HttpStatus getStatusCode() {
return response.getStatusCode();
}
public Optional<ErrorModel> getErrorObject() {
return response.getErrorObject();
}
public Optional<T> getResponseObject() {
return response.getResponseObject();
}
public Optional<String> getLocationHeader() {
return response.getLocationHeader();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("response", response).toString();
}
}
| true
|
a068fd79a21ae1ba0fc85e34d4b99f8c15f87f8f
|
Java
|
yutao-arch/2021-HIT-compile-lab
|
/实验二/1180300829_余涛_lab2/1180300829_余涛_lab2_源程序/compile_system_lab2/src/grammer_analyze/grammer_init.java
|
UTF-8
| 4,896
| 3.078125
| 3
|
[] |
no_license
|
package grammer_analyze;
import java.io.*;
import java.util.*;
public class grammer_init {
public static List<String> non_terminal = new ArrayList<>(); // 非终结符集合
public static List<String> terminal = new ArrayList<>(); // 终结符集合
public static List<String> all_symbol = new ArrayList<>(); // 所有符号
public static Map<String, HashSet<String>> first = new HashMap<>(); // first集
public static List<production> allproduction = new ArrayList<>(); // 文件中所有的产生式
// 初始化所有符号
public static void init_all_symbol(){
for (production temp : allproduction){
if (!all_symbol.contains(temp.getProduction_left())){
all_symbol.add(temp.getProduction_left());
}
}
for (production temp : allproduction){
for (String a : temp.getProduction_right_list()){
if (!all_symbol.contains(a)){
all_symbol.add(a);
}
}
}
}
// 初始化非终结符
public static void init_non_terminal(){
for (production temp : allproduction){
if (!non_terminal.contains(temp.getProduction_left())){
non_terminal.add(temp.getProduction_left());
}
}
}
// 初始化终结符
public static void init_terminal(){
all_symbol.removeIf(temp -> non_terminal.contains(temp)); // 从所有符号中去除掉非终结符
terminal.addAll(all_symbol);
}
// 读取文件中的所有产生式到allproduction中
public static void readfromfile(String filename) {
File myfile = new File(filename);
if (myfile.isFile() && myfile.exists()) {
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(myfile), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
String[] temp = lineTxt.split("->");
if (temp[1].contains("丨")){
String[] right = temp[1].split("丨");
for (String s : right) {
allproduction.add(new production(temp[0] + "->" + s.trim()));
}
}else{
allproduction.add(new production(temp[0] + "->" + temp[1].trim()));
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 计算first集
public static void buildfirst(){
for (String temp : terminal){ // 终结符的first为本身
first.put(temp, new HashSet<>());
first.get(temp).add(temp);
}
for (String temp : non_terminal){ // 终结符的first
first.put(temp, new HashSet<>());
first.get(temp).addAll(findfirst(temp));
}
}
// 计算某个非终结符的first集
public static Set<String> findfirst(String temp) {
Set<String> set = new HashSet<>();
int size1;
int size2;
do{
size1 = set.size();
for (production d : allproduction){
if (d.getProduction_left().equals(temp)){
if (terminal.contains(d.getProduction_right_list().get(0))){ // 产生式右部第一个符号为终结符直接加入
set.add(d.getProduction_right_list().get(0));
}else if (d.getProduction_right_list().get(0).equals("ε")){ // 产生式右部第一个符号为ε直接加入
set.add("ε");
}else if (non_terminal.contains(d.getProduction_right_list().get(0))){ // 产生式右部第一个符号为非终结符,递归
if (!temp.equals(d.getProduction_right_list().get(0))){ // 去除左递归
Set<String> set1 = findfirst(d.getProduction_right_list().get(0));
set.addAll(set1);
if (set1.contains("ε")){ // 如果含有ε,继续往后递归
for (int j = 1; j < d.getProduction_right_list().size(); j++){
Set<String> set2 = findfirst(d.getProduction_right_list().get(j));
set.addAll(set2);
if (!set2.contains("ε")){
break;
}
}
}
}
}
}
}
size2 = set.size();
} while (size1 != size2);
return set;
}
}
| true
|
b18ebf68dce90534c65e103d587c8447a518bd0c
|
Java
|
dwyanewang/springboot-thymeleaf
|
/demo8-logger-intercepter/src/main/java/com/dwyanewang/interceptor/LoggerInterceptor.java
|
UTF-8
| 3,485
| 2.125
| 2
|
[] |
no_license
|
package com.dwyanewang.interceptor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dwyanewang.dao.LoggerDao;
import com.dwyanewang.entity.TLoggerInfos;
import com.dwyanewang.util.LoggerUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoggerInterceptor implements HandlerInterceptor {
@Autowired
private LoggerDao loggerDao;
//请求开始时间标识
private static final String LOGGER_SENT_TIME = "_sent_time";
//请求日志实体标识
private static final String LOGGER_ENTITY = "_entity";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
TLoggerInfos loggerInfos = new TLoggerInfos();
String sessionId = request.getRequestedSessionId();
String url = request.getRequestURI();
String paramData = JSON.toJSONString(request.getParameterMap(),
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue);
loggerInfos.setAliClientIp(LoggerUtils.getCliectIp(request));
loggerInfos.setAliMethod(request.getMethod());
loggerInfos.setAliType(LoggerUtils.getRequestType(request));
loggerInfos.setAliParamData(paramData);
loggerInfos.setAliUri(url);
loggerInfos.setAliSessionId(sessionId);
request.setAttribute(LOGGER_SENT_TIME, System.currentTimeMillis());
request.setAttribute(LOGGER_ENTITY, loggerInfos);
System.out.println("处理前" + loggerInfos);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
int status = response.getStatus();
long currenTime = System.currentTimeMillis();
long time = Long.valueOf(request.getAttribute(LOGGER_SENT_TIME).toString());
TLoggerInfos loggerInfos = (TLoggerInfos) request.getAttribute(LOGGER_ENTITY);
loggerInfos.setAliTimeConsuming(Integer.valueOf((currenTime - time) + ""));
loggerInfos.setAliReturmTime(currenTime + "");
loggerInfos.setAliHttpStatusCode(status + "");
loggerInfos.setAliReturnData(JSON.toJSONString(request.getAttribute(LoggerUtils.LOGGER_RETURN),
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue
));
System.out.println("处理完成" + loggerInfos);
// LoggerDao loggerDao = getDAO(request);
loggerDao.insert(loggerInfos);
}
/**
* 根据传入的类型获取spring管理的对应dao
* @param request 请求对象
* @return LoggerDao
*/
private LoggerDao getDAO(HttpServletRequest request)
{
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return factory.getBean(LoggerDao.class);
}
}
| true
|
9ed73ba4590e4cdfddc1eee22e4060f49d1132f2
|
Java
|
jwcifuentes/TyS-sources
|
/tys-application/tys-adapters/src/main/java/co/com/mintrabajo/tys/adapters/integration/client/bpm/ActualizarDocumentoWebType.java
|
UTF-8
| 2,359
| 1.984375
| 2
|
[] |
no_license
|
package co.com.mintrabajo.tys.adapters.integration.client.bpm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for actualizarDocumentoWeb_Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="actualizarDocumentoWeb_Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://soaint.com/Servicios/Base/EncabezadosSOA}EncabezadoEntrada"/>
* <element name="strId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "actualizarDocumentoWeb_Type", propOrder = {
"encabezadoEntrada",
"strId"
})
public class ActualizarDocumentoWebType {
@XmlElement(name = "EncabezadoEntrada", namespace = "http://soaint.com/Servicios/Base/EncabezadosSOA", required = true)
protected EncabezadoEntradaType encabezadoEntrada;
@XmlElement(required = true)
protected String strId;
/**
* Gets the value of the encabezadoEntrada property.
*
* @return
* possible object is
* {@link EncabezadoEntradaType }
*
*/
public EncabezadoEntradaType getEncabezadoEntrada() {
return encabezadoEntrada;
}
/**
* Sets the value of the encabezadoEntrada property.
*
* @param value
* allowed object is
* {@link EncabezadoEntradaType }
*
*/
public void setEncabezadoEntrada(EncabezadoEntradaType value) {
this.encabezadoEntrada = value;
}
/**
* Gets the value of the strId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStrId() {
return strId;
}
/**
* Sets the value of the strId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStrId(String value) {
this.strId = value;
}
}
| true
|
e6cbbd95f571b3e59aa966501ea9f72e577ddba6
|
Java
|
RenanFucciScripts/Android
|
/Buscagro/app/src/main/java/com/example/renanfucci/buscagro/method/dao/MetodosDemanda_e_Oferta.java
|
UTF-8
| 800
| 2.203125
| 2
|
[] |
no_license
|
package com.example.renanfucci.buscagro.method.dao;
import java.sql.Date;
/**
* Created by _ on 18/09/2016.
*/
public class MetodosDemanda_e_Oferta {
private String nomeproduto;
private int quantidade;
private Date validade;
private int id;
public MetodosDemanda_e_Oferta(int id) {
this.id = id;
}
public MetodosDemanda_e_Oferta(String nomeproduto, int quantidade, Date validade) {
this.nomeproduto = nomeproduto;
this.quantidade = quantidade;
this.validade = validade;
}
public String getNomeproduto() {
return nomeproduto;
}
public int getQuantidade() {
return quantidade;
}
public Date getValidade() {
return validade;
}
public int getId() {
return id;
}
}
| true
|
eac2a9cf56261b3fb4d6b91534ad2c0f7eae4a20
|
Java
|
MiYazJE/Acepta-el-reto
|
/p634.java
|
UTF-8
| 617
| 3.171875
| 3
|
[] |
no_license
|
import java.util.*;
public class p634 {
public static void main(String[ ] args) {
Scanner s = new Scanner(System.in);
int cases = s.nextInt();
s.nextLine();
while (cases-- != 0) {
String line = s.nextLine();
int total = 0, current = 0;
for (char c : line.toCharArray()) {
if (c == 'O') {
current += 10;
total += current;
}
else {
current = 0;
}
}
System.out.println(total);
}
}
}
| true
|
d5e16317cea1791e32616b8479fbf92a5c3b8a53
|
Java
|
dtianyu/HHSC
|
/HHSC-war/src/java/com/hhsc/control/ItemFinishedRequestManagedBean.java
|
UTF-8
| 2,189
| 1.953125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hhsc.control;
import com.hhsc.entity.PurchaseRequestDetail;
import com.hhsc.lazy.ItemFinishedRequestModel;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
*
* @author kevindong
*/
@ManagedBean
@SessionScoped
public class ItemFinishedRequestManagedBean extends PurchaseRequestManagedBean {
/**
* Creates a new instance of ProductRequestManagedBean
*/
public ItemFinishedRequestManagedBean() {
}
@Override
public void create() {
super.create();
this.newEntity.setPurtype("100");
}
@Override
protected boolean doBeforePersist() throws Exception {
if (this.detailList != null && !this.detailList.isEmpty()) {
for (PurchaseRequestDetail detail : detailList) {
if (detail.getItemdesign() == null) {
showMsg(FacesMessage.SEVERITY_ERROR, "Error", "请输入花号");
return false;
}
if (detail.getItemmaster() == null) {
showMsg(FacesMessage.SEVERITY_ERROR, "Error", "请输入面料");
return false;
}
if (detail.getCustomer() == null) {
showMsg(FacesMessage.SEVERITY_ERROR, "Error", "请输入客户");
return false;
}
}
}
return super.doBeforePersist();
}
@Override
public void init() {
super.init();
setModel(new ItemFinishedRequestModel(purchaseRequestBean));
if (userManagedBean != null && !userManagedBean.getCurrentUser().getSuperuser()) {
this.model.getFilterFields().put("systemuser.id", userManagedBean.getCurrentUser().getId());
}
this.model.getFilterFields().put("status", "N");
}
@Override
public void reset() {
super.reset();
this.model.getFilterFields().put("status", "N");
}
}
| true
|
23f08b6d81f79364dce1b87aaf2e235a656fefaf
|
Java
|
CNxielong/Interview
|
/Interview/Interview/src/com/javaee/socket/UDPClient.java
|
GB18030
| 1,425
| 3.53125
| 4
|
[] |
no_license
|
package com.javaee.socket;
import java.io.IOException;
import java.net.*;
/**
* UDPͻ˷ͷ
* B(ͷ):
* (1)DatagramSocket͵Ķ
* (2)DatagramPacket͵ĶṩշIPַͶ˿ںš
* (3)send()ݡ
* (4)رSocketͷйصԴ
* @Auther: XDragon
* @Date: 2021/2/20/020 22:51
* @Email:cnxielong@gmail.com
*/
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();//(1)DatagramSocket͵Ķ
byte[] bytes = new byte[1024];
String s = new String("hello world!");
bytes = s.getBytes();
System.out.println("UDPClient ͵:"+s);
// InetAddress inetAddress = new InetAddress();//"192.168.31.248"
// DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,InetAddress.getByName("192.168.31.248"),8083);//(2)DatagramPacket͵ĶṩշIPַͶ˿ںš
DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,InetAddress.getLocalHost(),1235);//(2)DatagramPacket͵ĶṩշIPַͶ˿ںš
datagramSocket.send(datagramPacket);//(3)send()ݡ
datagramSocket.close();
}
}
| true
|
17417f0c13f9a8e31ea63524d07b0c3f2771c49c
|
Java
|
bestzmr/core_java
|
/src/tech/aistar/day16/myhomework/CalManyNums.java
|
UTF-8
| 1,509
| 3.328125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package tech.aistar.day16.myhomework;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author: Merlin
* @time: 2020/8/14 19:28
*/
public class CalManyNums {
public static void main(String[] args) {
int[] array = new int[100000000];
AtomicLong result1= new AtomicLong();
AtomicLong result2= new AtomicLong();
AtomicLong result3= new AtomicLong();
AtomicLong result4= new AtomicLong();
long result = 0;
Thread t1 = new Thread(()->{
for (int i = 1; i <= array.length/4; i++) {
result1.addAndGet(i);
}
});
Thread t2 = new Thread(()->{
for (int i = (array.length/4)+1; i <= array.length/2; i++) {
result2.addAndGet(i);
}
});
Thread t3 = new Thread(()->{
for (int i = (array.length/2)+1; i <= (array.length/4)*3; i++) {
result3.addAndGet(i);
}
});
Thread t4 = new Thread(()->{
for (int i = (array.length/4)*3+1; i <= array.length; i++) {
result4.addAndGet(i);
}
});
t1.start();
t2.start();
t3.start();
t4.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
result = result1.longValue() + result2.longValue() + result3.longValue() + result4.longValue();
System.out.println(result);
}
}
| true
|
53a50c2156e3463f20e4a0581970738d3b1e1bd5
|
Java
|
heboot/Candypie
|
/app/src/main/java/com/gdlife/candypie/adapter/user/UserFavAdapter.java
|
UTF-8
| 3,512
| 1.890625
| 2
|
[] |
no_license
|
package com.gdlife.candypie.adapter.user;
import android.view.ViewGroup;
import com.gdlife.candypie.R;
import com.gdlife.candypie.activitys.user.UserFavsListActivity;
import com.gdlife.candypie.common.MValue;
import com.gdlife.candypie.databinding.ItemFavUserListBinding;
import com.gdlife.candypie.serivce.UserService;
import com.gdlife.candypie.utils.IntentUtils;
import com.heboot.entity.User;
import com.heboot.recyclerview.baseadapter.BaseRecyclerViewAdapter;
import com.heboot.recyclerview.baseadapter.BaseRecyclerViewHolder;
import com.heboot.utils.LogUtil;
import com.yalantis.dialog.TipCustomDialog;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import io.reactivex.functions.Consumer;
public class UserFavAdapter extends BaseRecyclerViewAdapter {
protected Map<String, Object> params;
private TipCustomDialog tipCustomDialog;
private WeakReference<UserFavsListActivity> weakReference;
public UserFavAdapter(WeakReference<UserFavsListActivity> weakReference, List<User> mdata) {
data = mdata;
this.weakReference = weakReference;
}
@Override
public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new UserFavAdapter.ViewHolder(parent, R.layout.item_fav_user_list);
}
private class ViewHolder extends BaseRecyclerViewHolder<User, ItemFavUserListBinding> {
//
ViewHolder(ViewGroup parent, int layout) {
super(parent, layout);
}
@Override
public void onBindViewHolder(final User s, int position) {
binding.setUser(s);
binding.includeSexage.setUser(s);
UserService.getUserInfo(binding.tvInfo, s);
binding.clytContainer.setOnClickListener((v) -> {
IntentUtils.toHomepageActivity(v.getContext(), MValue.FROM_OTHER, s, null, null);
});
binding.bottomWrapper.setOnClickListener((v) -> {
tipCustomDialog = new TipCustomDialog.Builder(binding.getRoot().getContext(), new Consumer<Integer>() {
@Override
public void accept(Integer integer) throws Exception {
if (integer == 1) {
tipCustomDialog.dismiss();
weakReference.get().unFav(s.getId());
// params = SignUtils.getNormalParams();
// params.put(MKey.TO_UID, s.getId());
// HttpClient.Builder.getGuodongServer().unfavs(params).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new HttpObserver<BaseBeanEntity>() {
// @Override
// public void onSuccess(BaseBean<BaseBeanEntity> baseBean) {
//// remove(position);
//// notifyItemRemoved(position);
// weakReference.get().initCoupons();
// }
//
// @Override
// public void onError(BaseBean<BaseBeanEntity> baseBean) {
//
// }
// });
}
}
}, "确定取消收藏\n" + s.getNickname() + "?", "取消", "确定").create();
tipCustomDialog.show();
});
}
}
}
| true
|
3343edd673662e7bf1712ef6b70d31e8fa1ed21d
|
Java
|
vliolios/themoviedb-java-kit
|
/src/test/java/com/vliolios/tmdb/search/PeopleSearchTest.java
|
UTF-8
| 5,792
| 2.390625
| 2
|
[
"MIT"
] |
permissive
|
package com.vliolios.tmdb.search;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class PeopleSearchTest extends WireMockTest {
@Test
public void testSubmitResponseSuccessful() {
stub("/search/person", "search-people-success.json");
Response<PeopleResult> response = PeopleSearch.apiConfig(apiConfig).query("matrix").page(0).language("en").includeAdult(true).region("US").build().submit();
assertThat("The page value in the response is incorrect", response.getPage(), is(1));
assertThat("The total pages value in the response is incorrect", response.getTotalPages(), is(1));
assertThat("The total results value in the response is incorrect", response.getTotalResults(), is(1));
assertThat("The size of the results in the response is incorrect", response.getResults(), hasSize(1));
assertThat("The status message value in the response is incorrect", response.getStatusMessage(), nullValue());
assertThat("The status code value in the response is incorrect", response.getStatusCode(), nullValue());
assertThat("The success value in the response is incorrect", response.getSuccess(), nullValue());
PeopleResult result = response.getResults().get(0);
assertThat("The poster path in the response's result is incorrect", result.getProfilePath(), is("/2daC5DeXqwkFND0xxutbnSVKN6c.jpg"));
assertThat("The name in the response's result is incorrect", result.getName(), is("Bradley Hemmings"));
assertThat("The popularity in the response's result is incorrect", result.getPopularity(), is(1.273));
assertThat("The id in the response's result is incorrect", result.getId(), is(51329));
assertThat("The vore average in the response's result is incorrect", result.getAdult(), is(false));
MultiResult movieKnownFor = result.getKnownFor().get(0);
assertThat("The first known-for item in the response's result is not a movie", movieKnownFor.isMovie(), is(true));
assertThat("The poster path in the first known-for item in the response's result is incorrect", movieKnownFor.asMovie().getPosterPath(), is("/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg"));
assertThat("The title in the first known-for item in the response's result is incorrect", movieKnownFor.asMovie().getTitle(), is("Guardians of the Galaxy"));
MultiResult tvKnownFor = result.getKnownFor().get(1);
assertThat("The second known-for item in the response's result is a movie", tvKnownFor.isTV(), is(true));
assertThat("The scond known-for item in the response's result is not a tv show", tvKnownFor.asTV().getPosterPath(), is("/xn3QM6aInhQp631K2lXpGFox2Kc.jpg"));
assertThat("The name in the second known-for item in the response's result is incorrect", tvKnownFor.asTV().getName(), is("iZombie"));
}
@Test
public void testSubmitResponseWithError() {
stub("/search/person", "search-error.json");
Response<PeopleResult> response = PeopleSearch.apiConfig(apiConfig).query("brad").page(0).language("en").includeAdult(true).region("US").build().submit();
assertThat("The page value in the response is incorrect", response.getPage(), nullValue());
assertThat("The total pages value in the response is incorrect", response.getTotalPages(), nullValue());
assertThat("The total results value in the response is incorrect", response.getTotalResults(), nullValue());
assertThat("The size of the results in the response is incorrect", response.getResults(), nullValue());
assertThat("The status message value in the response is incorrect", response.getStatusMessage(), is("Invalid API key: You must be granted a valid key."));
assertThat("The status code value in the response is incorrect", response.getStatusCode(), is(7));
assertThat("The success value in the response is incorrect", response.getSuccess(), is(false));
}
@Test
public void testSubmitResponseInvalid() {
stub("/search/person", "search-invalid.json");
Response<PeopleResult> response = PeopleSearch.apiConfig(apiConfig).query("matrix").build().submit();
assertThat("The page value in the response is incorrect", response.getPage(), nullValue());
assertThat("The total pages value in the response is incorrect", response.getTotalPages(), nullValue());
assertThat("The total results value in the response is incorrect", response.getTotalResults(), nullValue());
assertThat("The size of the results in the response is incorrect", response.getResults(), nullValue());
assertThat("The status message value in the response is incorrect", response.getStatusMessage(), is("Failed to parse the response body"));
assertThat("The status code value in the response is incorrect", response.getStatusCode(), is(500));
assertThat("The success value in the response is incorrect", response.getSuccess(), is(false));
}
@Test
public void testQuery() {
PeopleSearch search = PeopleSearch.apiConfig(apiConfig).query("Brad").build();
assertThat("The query is incorrect", search.getQuery(), is("Brad"));
}
@Test
public void testPage() {
PeopleSearch search =PeopleSearch.apiConfig(apiConfig).query("Brad").page(1).build();
assertThat("The page is incorrect", search.getPage(), is(1));
}
@Test
public void testLanguage() {
PeopleSearch search =PeopleSearch.apiConfig(apiConfig).query("Brad").language("en").build();
assertThat("The language is incorrect", search.getLanguage(), is("en"));
}
@Test
public void testIncludeAdult() {
PeopleSearch search =PeopleSearch.apiConfig(apiConfig).query("Brad").includeAdult(true).build();
assertThat("The include adult flag is incorrect", search.getIncludeAdult(), is(true));
}
@Test
public void testRegion() {
PeopleSearch search = PeopleSearch.apiConfig(apiConfig).query("Brad").region("US").build();
assertThat("The region is incorrect", search.getRegion(), is("US"));
}
}
| true
|
d5d076c60c9a556d6de4760eb33de80e560e97da
|
Java
|
SwethaAdla/AndroidApps
|
/ChatApp/ChatAppPartB/app/src/main/java/com/app/hw09/Messages.java
|
UTF-8
| 1,388
| 2.40625
| 2
|
[] |
no_license
|
package com.app.hw09;
import java.io.Serializable;
public class Messages implements Serializable {
String text, sentBy, sentTime, tripId, imageUrl, key;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSentBy() {
return sentBy;
}
public void setSentBy(String sentBy) {
this.sentBy = sentBy;
}
public String getSentTime() {
return sentTime;
}
public void setSentTime(String sentTime) {
this.sentTime = sentTime;
}
public String getTripId() {
return tripId;
}
public void setTripId(String tripId) {
this.tripId = tripId;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String toString() {
return "Messages{" +
"text='" + text + '\'' +
", sentBy='" + sentBy + '\'' +
", sentTime='" + sentTime + '\'' +
", tripId='" + tripId + '\'' +
", imageUrl='" + imageUrl + '\'' +
", key='" + key + '\'' +
'}';
}
}
| true
|
6a199fd39bdc1e37f0b52de122c1ae64efe9fce2
|
Java
|
kamixiya/icm
|
/icm-rest-app/src/main/java/com/kamixiya/icm/configuration/WebConfig.java
|
UTF-8
| 2,865
| 2.09375
| 2
|
[] |
no_license
|
package com.kamixiya.icm.configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.kamixiya.icm.core.json.ObjectMapperFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* WebConfigAdapter
*
* @author Zhu Jie
* @date 2020-03-07
*/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
//允许跨域访问的路径
//允许请求方法
//允许跨域访问的源
//是否发送cookie
//预检间隔时间
registry.addMapping("/api/**")
.allowedMethods("POST", "PUT", "GET", "DELETE", "OPTIONS")
.allowedOrigins("*")
.allowCredentials(false)
.maxAge(3600);
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// 替换ObjectMapper
converters.forEach(c -> {
if (c instanceof MappingJackson2HttpMessageConverter) {
((MappingJackson2HttpMessageConverter) c).setObjectMapper(objectMapper());
}
});
}
@Bean
public PasswordEncoder passwordEncoderBean(){
return new BCryptPasswordEncoder();
}
@Bean
@Primary
public ObjectMapper objectMapper() {
// 创建缺省的ObjectMapper,提供动态过滤功能
return ObjectMapperFactory.getDefaultObjectMapper().registerModule(new Hibernate5Module()).setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
}
}
| true
|
2c7a596a4291437d56035914f61882147a66957f
|
Java
|
muresanalexandra/LabAssiAsseProjectV03
|
/src/test/java/GradeTest.java
|
UTF-8
| 3,218
| 2.59375
| 3
|
[] |
no_license
|
import Domain.Nota;
import Domain.Student;
import Domain.TemaLab;
import Exceptions.ValidatorException;
import Repository.MemoryRepository.NotaRepo;
import Repository.MemoryRepository.StudentRepo;
import Repository.MemoryRepository.TemaLabRepo;
import Validator.NotaValidator;
import Validator.StudentValidator;
import Validator.TemaLabValidator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.LocalDateTime;
public class GradeTest {
private static Logger logger = LogManager.getLogger(StudentTest.class);
private Student student = new Student("1", "Alexandru Kispal", 934, "kispal.alex@gmail.com", "Muresan Alexandra");
private Student studentInvalid = new Student("*3", (String)null, 67, "aa", "Ki$pal Mondi@lu");
private StudentValidator studentValidator = new StudentValidator();
private StudentRepo studentRepo = new StudentRepo(studentValidator);
private TemaLab temaLabValid = new TemaLab(1," Create a jenkins job",6,5);
private TemaLab temaLabInvalid = new TemaLab(200,"",18,19);
private TemaLabValidator temaLabValidator = new TemaLabValidator();
private TemaLabRepo temaLabRepo = new TemaLabRepo(temaLabValidator);
private Nota notaValida = new Nota(1,"1234",2,10, LocalDateTime.parse("2019-01-09T11:44:44"));
private Nota notaInvalida = new Nota(-1,"8*^",-1,-10,LocalDateTime.parse("2020-01-09T11:44:44"));
private NotaValidator notaValidator = new NotaValidator();
private NotaRepo notaRepo = new NotaRepo(notaValidator);
@BeforeClass
public static void setUp() {
logger.info("set up...");
}
@AfterClass
public static void tearDown() {
logger.info("tear down...");
}
@Test
public void idGradeTest() {
logger.info("Check if an id has only int digits");
try {
Assert.assertTrue("The id contains a char value", student.getId().matches("[*0-9]"));
}catch(Exception ex ) { System.out.println("Not a valid id");}
}
@Test
public void validValueTest() {
logger.info("Check if a grade has is in the correct format ");
try {
Assert.assertFalse("The assignment cannot be less than 1 and greater than 0", this.notaValida.getValoare() < 1 && this.notaValida.getValoare() > 10);
}catch (Exception ex) { System.out.println("Not a valid value");}
}
@Test
public void invalidValueTest() {
logger.info("Check if the grade is in the correct form");
try {
Assert.assertFalse("The assignment cannot be less than 1 and greater than 0", this.notaInvalida.getValoare() < 1 && this.notaInvalida.getValoare() > 10);
}catch (Exception ex) { System.out.println("The value is not valid"); }
}
@Test
public void addGradeTest() throws ValidatorException {
logger.info("This is a test for verifying the add of a grade ");
Assert.assertEquals("The repo is empty at the beginning", 0, this.notaRepo.size());
this.notaRepo.save(this.notaValida);
Assert.assertEquals("The lab grade was added", 1, this.notaRepo.size());
}
}
| true
|
f3f6d1888b37180aaf9189e1532c8314adac2c5a
|
Java
|
meta-abhinav-kanchhal/GET
|
/EAD Assignment 5/Functionality.java
|
UTF-8
| 1,403
| 2.546875
| 3
|
[] |
no_license
|
package com.abhinav.facade;
import java.util.Scanner;
import com.abhinav.dao.ImportExportDetails;
import com.abhinav.view.OptionChosen;
public class Functionality {
public void showItems() {
ImportExportDetails obj = new ImportExportDetails();
OptionChosen oc = new OptionChosen();
obj.showCart();
oc.chooseOption();
}
public void addItems() {
ImportExportDetails obj = new ImportExportDetails();
OptionChosen oc = new OptionChosen();
System.out.println("Enter code of item you want to add");
Scanner input = new Scanner(System.in);
int code = input.nextInt();
obj.addToCart(code);
oc.chooseOption();
}
public void deleteItems() {
ImportExportDetails obj = new ImportExportDetails();
OptionChosen oc = new OptionChosen();
System.out.println("Enter code of item you want to delete");
Scanner input = new Scanner(System.in);
int code = input.nextInt();
obj.deleteFromCart(code);
showItems();
oc.chooseOption();
}
public void editQuantity() {
ImportExportDetails obj = new ImportExportDetails();
OptionChosen oc = new OptionChosen();
System.out.println("Enter item code");
Scanner input = new Scanner(System.in);
int code = input.nextInt();
System.out.println("Enter quantity");
Scanner inputTwo = new Scanner(System.in);
int quantity = inputTwo.nextInt();
obj.editQuantity(code, quantity);
showItems();
oc.chooseOption();
}
}
| true
|
ca7d81afc4303797defcdebb427c71c4f9671af0
|
Java
|
stevenmontes/Proyecto-de-Patrones.
|
/proyecto_patrones_cl/src/cr/ac/cenfotec/proyecto/objetos/test/EmpleadoTest.java
|
UTF-8
| 1,577
| 2.5
| 2
|
[] |
no_license
|
package cr.ac.cenfotec.proyecto.objetos.test;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import org.junit.jupiter.api.Test;
import cr.ac.cenfotec.proyecto.conexion.Conector;
import cr.ac.cenfotec.proyecto.controlador.Controlador;
import cr.ac.cenfotec.proyecto.multis.MultiEmpleado;
public class EmpleadoTest {
Controlador c = new Controlador();
MultiEmpleado mE = new MultiEmpleado();
@Test
public void eliminartest() throws Exception {
eliminarRegistroSQL("templeado", "tes-02");
}
@Test
public void registrarEmpleado() {
assertEquals("Se ha registrado exitosamente el empleado.", c.registrarEmpleado("123428925", "queso", "queso2",
"queso4", "queso3", "queso@email.com", "quesito", "quesitoClave", "Cocinero", "CO-01"));
}
@Test
public void modificarTramite() throws Exception {
assertEquals("Se ha modificado exitosamente el empleado.", c.modificarEmpleado("123428925", "Queso", "Cheddar",
"amarillo", "conNachos", "queso@email.com", "quesito", "quesitoClave", "Cocinero", "CO-01"));
}
@Test
public void listar() throws Exception {
assertEquals(c.listarEmpleado().length, mE.listarTodosEmpleados().size());
}
private void eliminarRegistroSQL(String tabla, String cedula) throws Exception {
try {
Conector.getConector().ejecutarSQL("DELETE FROM " + tabla + " WHERE cedula = '" + cedula + "'");
System.out.println("Se elimino el empleado");
} catch (SQLException error) {
System.out.println("No se pudo eliminar el tramite" + error.getMessage());
}
}
}
| true
|
a58c9a916eba9235a495fc2837387f84bce097fc
|
Java
|
akidan/Gotya
|
/src/controller/spider/MyThread.java
|
GB18030
| 441
| 2.78125
| 3
|
[] |
no_license
|
package controller.spider;
import java.util.Date;
/**
* @author ֮Խ
* @date 2010-6-5
* ֹͣ,CPUʹ100%
* @param mills ֹͣǰmills
*/
public class MyThread {
public static void sleep(long mills){
long mills1 = new Date().getTime();
long mills2;
for(;;){
mills2 = new Date().getTime();
if(mills2 - mills1== mills){
return;
}
}
}
}
| true
|
503b5860cc9566d09f3124426cd1d47a62cafc53
|
Java
|
SanKing-Lee/JavaTools
|
/src/SQLiteBrowser/view/FileNavigator.java
|
UTF-8
| 751
| 2.59375
| 3
|
[] |
no_license
|
package SQLiteBrowser.view;
import SQLiteBrowser.model.SFileNode;
import SQLiteBrowser.model.SFileTreeRenderer;
import SQLiteBrowser.model.STreeModel;
import javax.swing.*;
import java.io.File;
public class FileNavigator extends JTree {
public static FileNavigator instance;
private File[] aFiles;
private FileNavigator() {
super();
SFileTreeRenderer renderer = new SFileTreeRenderer();
SFileNode root = new SFileNode();
STreeModel model = new STreeModel(root);
JTree fileTree = new JTree(model);
add(fileTree);
}
public static FileNavigator getInstance() {
if (instance == null) {
instance = new FileNavigator();
}
return instance;
}
}
| true
|
59059f92e46c5b76392023f4ffb4bd3f3b1a05e7
|
Java
|
CharlieNarita/TankWar
|
/src/com/charlie/tank/AbstractVehicle.java
|
UTF-8
| 1,530
| 2.75
| 3
|
[] |
no_license
|
package com.charlie.tank;
import java.awt.Graphics;
import java.awt.Rectangle;
public abstract class AbstractVehicle extends AbstractItem implements Movable {
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
public boolean isMoving() {
return moving;
}
public void setMoving(boolean moving) {
this.moving = moving;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public boolean alive = true;
public boolean moving = false;
public int speed = 0;
public Group group;
public Direction direction;
public AbstractVehicle(int x, int y, int width, int height, Group group, Direction direction) {
super(x, y, width, height);
// TODO Auto-generated constructor stub
this.group = group;
this.direction = direction;
}
public AbstractVehicle(int x, int y, Group group, Direction direction) {
super(x, y);
this.group = group;
this.direction = direction;
}
public abstract void paint(Graphics g);
public abstract void move();
public abstract Rectangle getRect();
public abstract void isDestroy();
public abstract void goBack();
}
| true
|
3ac765c9ef83324fae5ee30d98226abfefc7b720
|
Java
|
zdpwilliam/notes
|
/framework/netty/src/test/java/com/william/AppTest.java
|
UTF-8
| 346
| 1.78125
| 2
|
[] |
no_license
|
package com.william;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext();
context.getBean(String.class);
}
}
| true
|
0560f050c352df541f79e03b34088aa738559bc6
|
Java
|
droiders/Reportn_FinalVersion
|
/src/org/taptwo/android/widget/viewflow/example/JSONParser.java
|
UTF-8
| 2,654
| 2.46875
| 2
|
[] |
no_license
|
package org.taptwo.android.widget.viewflow.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl() {
try{
HttpClient client = new DefaultHttpClient();
//trie selon la date
// String getURL = "http://ville.terralego.com/open311/v2/requests.json?api_key=makinacorpus&api_pass=test_mobile_api_key&r=500&lon=10&lat=36";
//trie selon distance
String getURL = "http://ville.terralego.com/open311/v2/requests.json?api_key=makinacorpus&api_pass=test_mobile_api_key";
HttpGet get = new HttpGet(getURL);
get.addHeader("Authorization", "Basic "+ "Zml4bXlzdHJlZXQ6NUZ0OUMyQlVZbjRhM3pi");
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
is = resEntityGet.getContent();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
if(resEntityGet==null){
Log.i("GET RESPONSE","nuuuuuuuuuuul");}
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
| true
|
bd0d193eaedf87b4793dc3639de398439c7181d5
|
Java
|
jnleonard3/ChickenZombieBonanza
|
/src/ucf/chickenzombiebonanza/game/item/HealthInventoryObject.java
|
UTF-8
| 2,571
| 2.546875
| 3
|
[] |
no_license
|
/**
* Copyright (c) 2011, Chicken Zombie Bonanza Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Chicken Zombie Bonanza Project 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 CHICKEN ZOMBIE BONANZA PROJECT 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 ucf.chickenzombiebonanza.game.item;
public class HealthInventoryObject extends InventoryObject {
public static final HealthInventoryObject SMALL_HEALTH_KIT = new HealthInventoryObject("Small Health Kit", 10);
public static final HealthInventoryObject MEDIUM_HEALTH_KIT = new HealthInventoryObject("Medium Health Kit", 20);
public static final HealthInventoryObject LARGE_HEALTH_KIT = new HealthInventoryObject("Large Health Kit", 30);
private int count = 1;
private final int healingAmount;
public HealthInventoryObject(String name, int amount) {
super(name, InventoryObject.InventoryObjectTypeEnum.HEALTH);
this.healingAmount = amount;
}
public int getHealingAmount() {
return healingAmount;
}
public int getCount() {
return count;
}
public void incrementCount(int amount) {
count += amount;
}
public boolean use() {
if(count > 0) {
count -= 1;
return true;
}
return false;
}
}
| true
|
1382d8812c902925efef494c90b407115a48cd0c
|
Java
|
AlbertNie/wenda
|
/src/main/java/com/nowcoder/controller/MessageController.java
|
UTF-8
| 6,288
| 2.15625
| 2
|
[] |
no_license
|
package com.nowcoder.controller;
import com.nowcoder.model.*;
import com.nowcoder.service.*;
import com.nowcoder.util.WendaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by albert on 2017/8/11.
*/
@Controller
public class MessageController {
private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
@Autowired
MessageServive messageServive;
@Autowired
UserService userService;
@Autowired
SensitiveService sensitiveService;
@Autowired
HostHolder hostHolder;
@RequestMapping(value = "/msg/list",method = {RequestMethod.GET})
public String getConversationList(Model model){
User user = hostHolder.getUser();
if (user == null) return "redirect:/reglogin";
List<Message> conversationList = messageServive.selectMessageListByUserId(user.getId(),0,10);
List<ViewObject> conversations = new ArrayList<>();
for (Message conversation : conversationList) {
ViewObject vo = new ViewObject();
vo.set("conversation",conversation);
vo.set("user",userService.getUser(conversation.getFromId()));
vo.set("unRead",messageServive.getConversationCountUnread(user.getId(),conversation.getConversationId()));
conversations.add(vo);
}
model.addAttribute("conversations",conversations);
return "letter";
}
@RequestMapping(value = "/msg/detail")
public String getConversationDetails(@RequestParam(value = "conversationId",required = false) String conversationId,
Model model,
HttpServletRequest request){
User thisUser = hostHolder.getUser();
if (thisUser == null) return "redirect:/reglogin";
if (conversationId == null)
conversationId = (String) request.getAttribute("conversationId");
if (conversationId == null)
return "redirect:/msg/list";
if (!conversationId.matches("^\\d+_\\d+$"))
return "redirect:/msg/list";
String num[] = conversationId.split("_");
boolean flage = false;
int ids[] = new int[2];
for (int i = 0; i < 2; i++) {
ids[i] = Integer.valueOf(num[i]);
if (ids[i] == thisUser.getId())
flage = true;
}
if (!flage)
return "redirect:/msg/list";
int thatUser = ids[0]==thisUser.getId()?ids[1]:ids[0];
List<Message> messagess = messageServive.selectMessageByConversationId(conversationId,0,6);
List<ViewObject> messages = new ArrayList<>();
for (Message me : messagess) {
if (me.getToId() == thisUser.getId())
messageServive.updateHasRead(me.getId());
ViewObject vo = new ViewObject();
vo.set("message",me);
vo.set("user",userService.getUser(me.getFromId()));
if (me.getFromId() == thisUser.getId())
vo.set("mySelf",true);
messages.add(vo);
}
model.addAttribute("messages",messages);
model.addAttribute("thatUser",thatUser);
return "letterDetail";
}
@RequestMapping(value = "/msg/addMessage",method = {RequestMethod.POST})
@ResponseBody
public String sendMessage(@RequestParam("content") String content,
@RequestParam("toName") String toName){
User user = hostHolder.getUser();
if (user == null)
return WendaUtil.toJsonCode(999,"未登陆");
User toUser = userService.getUserByName(toName);
if (toName == null)
return WendaUtil.toJsonCode(1,"用户不存在");
try {
content = sensitiveService.filte(content);
content = HtmlUtils.htmlEscape(content);
Message message = new Message();
message.setCreatedDate(new Date());
message.setContent(content);
message.setToId(toUser.getId());
message.setFromId(user.getId());
message.setHasRead(0);
message.setConversationId(String.format("%d_%d",user.getId(),toUser.getId()));
messageServive.addMessage(message);
} catch (Exception e) {
logger.error(user.getId() + "发送消息失败:消息内容:" + content+ " 错误消息:"+ e.getMessage());
return WendaUtil.toJsonCode(1,"发送失败");
}
return WendaUtil.toJsonCode(0);
}
@RequestMapping(value = "/msg/sendMessage",method = {RequestMethod.POST})
public String sendMessageInDetail(@RequestParam("content") String content,
@RequestParam("toId") int toId,
HttpServletRequest request){
User user = hostHolder.getUser();
if (user == null)
return "redirect:/reglogin";
Message message = new Message();
try {
content = sensitiveService.filte(content);
content = HtmlUtils.htmlEscape(content);
message.setCreatedDate(new Date());
message.setContent(content);
message.setToId(toId);
message.setFromId(user.getId());
message.setHasRead(0);
message.setConversationId(String.format("%d_%d",user.getId(),toId));
messageServive.addMessage(message);
request.setAttribute("conversationId",message.getConversationId());
} catch (Exception e) {
logger.error(user.getId() + "发送消息失败:消息内容:" + content+ " 错误消息:"+ e.getMessage());
}
return "forward:/msg/detail";
}
}
| true
|
d67049e6818be81034ebc42f1410aafc9c93a9e2
|
Java
|
mgunes17/turquas
|
/src/test/java/db/dao/SentenceDAOTest.java
|
UTF-8
| 449
| 2.21875
| 2
|
[] |
no_license
|
package db.dao;
import model.Sentence;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Created by ercan on 13.05.2017.
*/
public class SentenceDAOTest {
@Test
public void getAllSentences() throws Exception {
SentenceDAO sentenceDAO = new SentenceDAO();
List<Sentence> sentenceList = sentenceDAO.getAllSentences();
assertEquals(250, sentenceList.size());
}
}
| true
|
671c963f6821019ffb62d9b606b120469e2c7ba0
|
Java
|
bohan2345/LeetcodeSolutions
|
/src/main/java/string/DecodeWays.java
|
UTF-8
| 1,211
| 4.125
| 4
|
[] |
no_license
|
package string;
/**
* A message containing letters from A-Z is being encoded to numbers using the following mapping:
* <p>
* 'A' -> 1
* 'B' -> 2
* ...
* 'Z' -> 26
* Given an encoded message containing digits, determine the total number of ways to decode it.
* <p>
* For example,
* Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
* <p>
* The number of ways decoding "12" is 2.
* <p>
* Created by Bohan Zheng on 4/27/2016.
*
* @author Bohan Zheng
*/
public class DecodeWays {
/**
* f(i) = f(i - 1) the digit i converted to a letter if s(i) != 0
* + f(i - 2) the digit i - 1 and i converted to a letter, if 10 < s(i - 1, i) <= 26
*/
public int numDecodings(String s) {
if (s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
int f1 = 1, f2 = 1;
for (int i = 1; i < s.length(); i++) {
int tmp = 0;
if (s.charAt(i) != '0') {
tmp += f2;
}
int x = Integer.valueOf(s.substring(i - 1, i + 1));
if (10 <= x && x <= 26) {
tmp += f1;
}
f1 = f2;
f2 = tmp;
}
return f2;
}
}
| true
|
ce07f4dc75e826f82dc8dd0b46ee2491697a6ee3
|
Java
|
TUANHSY/Jdbc_Exercise
|
/src/com/dx/dao/Excute.java
|
UTF-8
| 3,326
| 3.03125
| 3
|
[] |
no_license
|
package com.dx.dao;
import com.dx.model.BeautyInfoEntity;
import com.dx.util.JdbcUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.Scanner;
/**
* 对数据库的增删查改操作
* @Author: duanxu
* @Date: 2019/5/9 22:22
*/
public class Excute {
private JdbcUtil jdbcUtil ;
private Statement statement ;
/**
* 增
*/
public void add()throws SQLException{
jdbcUtil =new JdbcUtil();
BeautyInfoEntity beautyInfoEntity = new BeautyInfoEntity();
Scanner in = new Scanner(System.in);
GetNow getNow = new GetNow();
Timestamp now=getNow.timeNow();
String sql = "insert into beauty_info "+
"(name, telphone, email, create_Time)"+
"values "+
"(?,?,?,current_timestamp );";
System.out.println("输入用户信息:");
System.out.println("姓名:");
beautyInfoEntity.setName(in.next());
System.out.println("邮箱:");
beautyInfoEntity.setEmail(in.next());
System.out.println("电话:");
beautyInfoEntity.setTelphone(in.next());
PreparedStatement prepareStatement = jdbcUtil.getConnection().prepareStatement(sql);
prepareStatement.setString(1,beautyInfoEntity.getName());
prepareStatement.setString(2,beautyInfoEntity.getTelphone());
prepareStatement.setString(3,beautyInfoEntity.getEmail());
prepareStatement.execute();
}
/**
* 删
*/
public void deleteByName() throws SQLException {
System.out.println("请输入要删除的姓名:");
Scanner in = new Scanner(System.in);
String name=in.next();
Connection connection=jdbcUtil.getConnection();
String sql="delete from beauty_info where name = ?";
PreparedStatement preparedStatement =connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.execute();
}
/**
* 改
*/
public void update(){
}
/**
* 查
* 查询所有数据并返回到集合Arraylist
*/
public void queryAll() throws SQLException {
jdbcUtil =new JdbcUtil();
statement =jdbcUtil.getConnection().createStatement();
ArrayList<BeautyInfoEntity> beautyInfoEntityArrayList = new ArrayList<>();
String sql="select * from beauty_info";
try {
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
BeautyInfoEntity beautyInfoEntity = new BeautyInfoEntity();
beautyInfoEntity.setId(resultSet.getInt("id"));
beautyInfoEntity.setName(resultSet.getString("name"));
beautyInfoEntity.setEmail(resultSet.getString("email"));
beautyInfoEntity.setCreateTime(resultSet.getTimestamp("create_Time"));
beautyInfoEntity.setUpdateTime(resultSet.getTimestamp("update_Time"));
beautyInfoEntityArrayList.add(beautyInfoEntity);
}
for (BeautyInfoEntity beautyInfoEntity:beautyInfoEntityArrayList){
System.out.println(beautyInfoEntity.toString());
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
28b1f471c832fc75bf41370dfbd217046255d60b
|
Java
|
xueyi123/smart-netbox
|
/src/main/java/com/iih5/netbox/codec/ws/WsTextForDefaultJsonEncoder.java
|
UTF-8
| 820
| 2.421875
| 2
|
[] |
no_license
|
package com.iih5.netbox.codec.ws;
import com.iih5.netbox.message.StringMessage;
import io.netty.channel.Channel;
public class WsTextForDefaultJsonEncoder extends WsTextEncoder {
@Override
public void encode(Channel ctx, Object msg, StringBuffer text) {
pack(msg, text);
}
public void pack(Object msg, StringBuffer text) {
synchronized (this) {
//Text协议定义: "【协议ID】#【加密类型】#【内容】",比如 10001#0#hello world!
StringMessage jm = (StringMessage) msg;
StringBuffer sb = new StringBuffer();
sb.append(jm.getId());
sb.append("#");
sb.append(jm.getEncrypt());
sb.append("#");
sb.append(jm.getContent());
text.append(sb.toString());
}
}
}
| true
|
0bb22e35a58e07e409a5fe9e714f7ff999f123e2
|
Java
|
apache/cloudstack
|
/core/src/main/java/com/cloud/serializer/GsonHelper.java
|
UTF-8
| 3,540
| 1.804688
| 2
|
[
"GPL-2.0-only",
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] |
permissive
|
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.serializer;
import java.util.List;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.SecStorageFirewallCfgCommand.PortConfig;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.transport.ArrayTypeAdaptor;
import com.cloud.agent.transport.InterfaceTypeAdaptor;
import com.cloud.agent.transport.LoggingExclusionStrategy;
import com.cloud.agent.transport.Request.NwGroupsCommandTypeAdaptor;
import com.cloud.agent.transport.Request.PortConfigListTypeAdaptor;
import com.cloud.utils.Pair;
public class GsonHelper {
private static final Logger s_logger = Logger.getLogger(GsonHelper.class);
protected static final Gson s_gson;
protected static final Gson s_gogger;
static {
GsonBuilder gsonBuilder = new GsonBuilder();
s_gson = setDefaultGsonConfig(gsonBuilder);
GsonBuilder loggerBuilder = new GsonBuilder();
loggerBuilder.disableHtmlEscaping();
loggerBuilder.setExclusionStrategies(new LoggingExclusionStrategy(s_logger));
s_gogger = setDefaultGsonConfig(loggerBuilder);
s_logger.info("Default Builder inited.");
}
static Gson setDefaultGsonConfig(GsonBuilder builder) {
builder.setVersion(1.5);
InterfaceTypeAdaptor<DataStoreTO> dsAdaptor = new InterfaceTypeAdaptor<DataStoreTO>();
builder.registerTypeAdapter(DataStoreTO.class, dsAdaptor);
InterfaceTypeAdaptor<DataTO> dtAdaptor = new InterfaceTypeAdaptor<DataTO>();
builder.registerTypeAdapter(DataTO.class, dtAdaptor);
ArrayTypeAdaptor<Command> cmdAdaptor = new ArrayTypeAdaptor<Command>();
builder.registerTypeAdapter(Command[].class, cmdAdaptor);
ArrayTypeAdaptor<Answer> ansAdaptor = new ArrayTypeAdaptor<Answer>();
builder.registerTypeAdapter(Answer[].class, ansAdaptor);
builder.registerTypeAdapter(new TypeToken<List<PortConfig>>() {
}.getType(), new PortConfigListTypeAdaptor());
builder.registerTypeAdapter(new TypeToken<Pair<Long, Long>>() {
}.getType(), new NwGroupsCommandTypeAdaptor());
Gson gson = builder.create();
dsAdaptor.initGson(gson);
dtAdaptor.initGson(gson);
cmdAdaptor.initGson(gson);
ansAdaptor.initGson(gson);
return gson;
}
public final static Gson getGson() {
return s_gson;
}
public final static Gson getGsonLogger() {
return s_gogger;
}
public final static Logger getLogger() {
return s_logger;
}
}
| true
|
747c5a779a39080743aa7afefd0ede58999482cc
|
Java
|
AnEntireHam/IRE-game
|
/com.IRE/src/ire/combat/actions/attackactions/spellattacks/DebuffSpell.java
|
UTF-8
| 784
| 2.5625
| 3
|
[] |
no_license
|
package ire.combat.actions.attackactions.spellattacks;
import ire.audio.AudioStream;
public abstract class DebuffSpell extends SpellAttack {
// Busted because of debuff implementation.
// Will replace with debuff object later.
protected int debuffID;
public DebuffSpell(String name, String description, AudioStream SOUND, int DURATION, int DELAY,
float coefficient, String[] postfixNames, int spellLevel, int baseManaCost, int debuffID) {
super(name, description, SOUND, DURATION, DELAY, coefficient, postfixNames, spellLevel, baseManaCost);
this.debuffID = debuffID;
}
public int getDebuffID() {
return debuffID;
}
public void setDebuffID(int debuffID) {
this.debuffID = debuffID;
}
}
| true
|
ec5d65b23f592be91976ae9aef4158d3ed47a52f
|
Java
|
guohongming1/technologyforum
|
/src/main/java/com/example/technologyforum/web/mapper/QuestionCommentMapper.java
|
UTF-8
| 606
| 1.703125
| 2
|
[] |
no_license
|
package com.example.technologyforum.web.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.technologyforum.web.pojo.QuestionComment;
import org.springframework.stereotype.Repository;
@Repository
public interface QuestionCommentMapper extends BaseMapper<QuestionComment> {
int deleteByPrimaryKey(Integer id);
int insert(QuestionComment record);
int insertSelective(QuestionComment record);
QuestionComment selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(QuestionComment record);
int updateByPrimaryKey(QuestionComment record);
}
| true
|
31fade4800a86500dc24a6aa741e9a02bb4cb2e4
|
Java
|
520ZH1314/ZhiXings
|
/tpmlib/src/main/java/com/zhixing/tpmlib/bean/EquipmentBaseDataPostBean.java
|
UTF-8
| 1,486
| 1.914063
| 2
|
[] |
no_license
|
package com.zhixing.tpmlib.bean;
public class EquipmentBaseDataPostBean {
public EquipmentBaseDataPostBean(String lineCode, String appCode, String apiCode, String tenantId, String stationCode) {
LineCode = lineCode;
AppCode = appCode;
ApiCode = apiCode;
TenantId = tenantId;
StationCode = stationCode;
}
public EquipmentBaseDataPostBean(String appCode, String apiCode, String tenantId, String stationCode) {
AppCode = appCode;
ApiCode = apiCode;
TenantId = tenantId;
StationCode = stationCode;
}
public String getLineCode() {
return LineCode;
}
public void setLineCode(String lineCode) {
LineCode = lineCode;
}
public String LineCode;
public String AppCode;
public String getAppCode() {
return AppCode;
}
public void setAppCode(String appCode) {
AppCode = appCode;
}
public String getApiCode() {
return ApiCode;
}
public void setApiCode(String apiCode) {
ApiCode = apiCode;
}
public String getTenantId() {
return TenantId;
}
public void setTenantId(String tenantId) {
TenantId = tenantId;
}
public String getStationCode() {
return StationCode;
}
public void setStationCode(String stationCode) {
StationCode = stationCode;
}
public String ApiCode;
public String TenantId;
public String StationCode;
}
| true
|
80fc0c877431a01ba813f11b1488698c5db709c3
|
Java
|
jocodepeasant/leetcode
|
/src/贪心算法/q5638_吃苹果的最大数目/s1/Solution.java
|
UTF-8
| 1,097
| 3.5625
| 4
|
[] |
no_license
|
package 贪心算法.q5638_吃苹果的最大数目.s1;
/**
* 贪心:
* 优先吃快过期的苹果,时间复杂度O(N*N)
*/
class Solution {
public int eatenApples(int[] apples, int[] days) {
int day = 0;
//找出苹果还未全部腐烂的最后日期
for (int i = 0; i < days.length; i++) {
day = Math.max(i + days[i], day);
}
//下标值表示失效日期,存储在当天后即腐烂的苹果数
int[] tmp = new int[day];
int res = 0;
for (int i = 0; i < day; i++) {
//保存当天新长出的苹果
if (i < apples.length && apples[i] != 0) {
tmp[i + days[i] - 1] += apples[i];
}
int idx = i;
//取出最先腐烂的苹果
while (idx < day && tmp[idx] == 0) {
idx++;
}
//没有可取出的苹果
if (idx == day) {
continue;
} else {
tmp[idx]--;
res++;
}
}
return res;
}
}
| true
|
7259c10ebeaa333c1ed2c5a005fd3d3d790e94f5
|
Java
|
suyash-capiot/operations
|
/src/main/java/com/coxandkings/travel/operations/repository/bookstopenquiry/BookstopEnquiryRepository.java
|
UTF-8
| 680
| 1.90625
| 2
|
[] |
no_license
|
package com.coxandkings.travel.operations.repository.bookstopenquiry;
import com.coxandkings.travel.operations.criteria.bookstopenquiry.BookstopEnquiryCriteria;
import com.coxandkings.travel.operations.model.bookstopenquiry.BookstopEnquiry;
import java.util.List;
public interface BookstopEnquiryRepository {
BookstopEnquiry saveBookstopEnquiry(BookstopEnquiry bookstopEnquiry);
BookstopEnquiry updateBookstopEnquiry(BookstopEnquiry bookstopEnquiry);
List<BookstopEnquiry> getBookstopEnquiryByCriteria(BookstopEnquiryCriteria criteria);
BookstopEnquiry getBookstopEnquiryById(String id);
BookstopEnquiry updateBookstopEnquiryStatusToClosed(String id);
}
| true
|
8a478c2943adf82f17e781e2632455dd3aa686a4
|
Java
|
happyhater/silent-text-android
|
/src/com/silentcircle/silenttext/fragment/ListFragment.java
|
UTF-8
| 3,483
| 2.078125
| 2
|
[] |
no_license
|
/*
Copyright (C) 2013-2015, Silent Circle, LLC. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Any redistribution, use, or modification is done solely for personal
benefit and not for any commercial purpose or for monetary gain
* 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 Silent Circle 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 SILENT CIRCLE, LLC 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.silentcircle.silenttext.fragment;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.silentcircle.silenttext.view.ListView;
import com.silentcircle.silenttext.view.adapter.BaseListAdapter;
public class ListFragment extends BaseFragment implements OnItemClickListener, OnItemLongClickListener {
private List<?> items;
protected List<?> getItems() {
return items;
}
protected ListView getListView() {
View view = getUnwrappedView();
return view instanceof ListView ? (ListView) view : null;
}
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
ListView view = new ListView( inflater.getContext() );
view.setOnItemClickListener( this );
view.setOnItemLongClickListener( this );
return view;
}
@Override
public void onItemClick( AdapterView<?> parent, View view, int position, long itemID ) {
onItemClick( parent.getAdapter().getItem( position ) );
}
/**
* @param item
*/
protected void onItemClick( Object item ) {
// By default, do nothing.
}
@Override
public boolean onItemLongClick( AdapterView<?> parent, View view, int position, long itemID ) {
return onItemLongClick( parent.getAdapter().getItem( position ) );
}
/**
* @param item
*/
protected boolean onItemLongClick( Object item ) {
return false;
}
public void setItems( int layoutResourceID, List<?> items ) {
this.items = items;
ListView view = getListView();
if( view != null && items != null ) {
view.setAdapter( new BaseListAdapter( layoutResourceID, items ) );
}
}
}
| true
|
270456db30f9fecbdda923c5f32eac23d59e99a6
|
Java
|
meikanfeng/RongXinMedical
|
/app/src/main/java/com/huagu/RX/rongxinmedical/Activity/WiFiConfirmInfoSettingActivity.java
|
UTF-8
| 2,850
| 1.960938
| 2
|
[] |
no_license
|
package com.huagu.RX.rongxinmedical.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.huagu.RX.rongxinmedical.Adapter.DeviceInfoAdapter;
import com.huagu.RX.rongxinmedical.Dialog.DialogShows;
import com.huagu.RX.rongxinmedical.Interface.DialogShowsOkLinstener;
import com.huagu.RX.rongxinmedical.R;
import com.huagu.RX.rongxinmedical.Service.UartService;
public class WiFiConfirmInfoSettingActivity extends BaseActivity implements View.OnClickListener, DialogShowsOkLinstener.ClickOKLintener {
private EditText wifi_name,wifi_password;
private TextView search_device;
private String wifiname,wifipassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_confirm_info_setting);
InitView();
}
private void InitView() {
super.initTile();
refresh.setVisibility(View.GONE);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
tcd.setText(R.string.Confirm_Wifi_Info);
wifi_name = (EditText) this.findViewById(R.id.wifi_name);
wifi_password = (EditText) this.findViewById(R.id.wifi_password);
search_device = (TextView) this.findViewById(R.id.search_device);
search_device.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.search_device:
wifiname = wifi_name.getText().toString().trim();
wifipassword = wifi_password.getText().toString().trim();
if (TextUtils.isEmpty(wifiname)){
Toast.makeText(this,R.string.wifi_name_enter,Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(wifipassword)){
Toast.makeText(this,R.string.wifi_password_enter,Toast.LENGTH_SHORT).show();
return;
}
DialogShows.getInstance(this).TextDialogShow(getResources().getString(R.string.Confirm_Wifi_Info_tips),"").setDialogShowsOKLintener(this);
break;
}
}
@Override
public void ClickOK(DialogShowsOkLinstener dialog,String tag) {
Intent intent = new Intent(this,DeviceListActivity.class);//WiFiConnectingActivity
intent.putExtra("wifiname", wifiname);
intent.putExtra("wifipassword", wifipassword);
startActivity(intent);
}
}
| true
|
5f9a6e22f9d878edcb10d00f212baf396df3ecee
|
Java
|
rpenco/republicraft
|
/plugins/papermc/papermc-republicraft/src/main/java/fr/republicraft/papermc/world/managers/TelePortalManager.java
|
UTF-8
| 9,925
| 2.0625
| 2
|
[] |
no_license
|
package fr.republicraft.papermc.world.managers;
import fr.republicraft.common.api.channel.events.ChannelEventName;
import fr.republicraft.common.api.config.EntityConfig;
import fr.republicraft.common.api.helper.FullLocation;
import fr.republicraft.common.api.managers.Manager;
import fr.republicraft.papermc.world.RepublicraftPlugin;
import fr.republicraft.papermc.world.api.channels.PaperChannelListener;
import fr.republicraft.papermc.world.api.channels.events.RemoteTeleportEvent;
import fr.republicraft.papermc.world.commands.PortalCommand;
import fr.republicraft.papermc.world.commands.SpawnCommand;
import fr.republicraft.papermc.world.config.portals.PortalConfig;
import fr.republicraft.papermc.world.config.spawn.SpawnConfig;
import fr.republicraft.papermc.world.listeners.PortalListener;
import fr.republicraft.papermc.world.listeners.WordListener;
import fr.republicraft.papermc.world.managers.portal.Portal;
import fr.republicraft.papermc.world.managers.portal.PortalParticle;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.*;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.*;
import static fr.republicraft.papermc.world.api.utils.StringUtils.parseLocation;
import static org.bukkit.Bukkit.getLogger;
import static org.bukkit.Bukkit.getWorld;
/**
* Gestion des portails de téléportation
*/
public class TelePortalManager extends Manager implements Listener, PaperChannelListener {
private final RepublicraftPlugin plugin;
private final List<PortalConfig> portalConfigs;
private final Map<UUID, Portal> portals;
private final Map<UUID, PortalParticle> portalParticles;
private final int MAX_HEALTH = 40;
private int bukkitTask;
public TelePortalManager(RepublicraftPlugin plugin, List<PortalConfig> portalConfigs) {
this.plugin = plugin;
this.portalConfigs = portalConfigs;
this.portals = new HashMap<>();
this.portalParticles = new HashMap<>();
}
/**
* Creation de toutes les entitiés servant à interagir pour se téléporter
*/
@Override
public void start() {
plugin.getCommand("spawn").setExecutor(new SpawnCommand(plugin));
plugin.getCommand("portal").setExecutor(new PortalCommand(plugin));
plugin.getServer().getPluginManager().registerEvents(new PortalListener(plugin), plugin);
plugin.getServer().getPluginManager().registerEvents(new WordListener(plugin), plugin);
plugin.getChannel().register(this, ChannelEventName.SERVER_TELEPORT);
// PortalParticle portalParticle = new PortalParticle();
// portalParticle.addLocation(new Location(plugin.getWorld(), 1404, 64, 922));
// portalParticle.addLocation(new Location(plugin.getWorld(), 1405, 64, 922));
// portalParticle.addLocation(new Location(plugin.getWorld(), 1404, 65, 922));
// portalParticle.addLocation(new Location(plugin.getWorld(), 1405, 65, 922));
// portalParticle.addLocation(new Location(plugin.getWorld(), 1404, 66, 922));
// portalParticle.addLocation(new Location(plugin.getWorld(), 1405, 66, 922));
// portalParticles.put(UUID.randomUUID(), portalParticle);
// bukkitTask = schedule();
if (portalConfigs != null) {
for (PortalConfig portalConfig : portalConfigs) {
Entity entity = spawn(plugin.getWorld(), portalConfig);
if (entity != null) {
portals.put(entity.getUniqueId(), new Portal(entity, portalConfig));
}
}
}
}
/**
* Suppression de toutes les entités créé par le manager.
* Important! A appeller à chaque arrête/désactivation du plugin.
*/
@Override
public void stop() {
for (Map.Entry<UUID, Portal> entry : portals.entrySet()) {
Entity entity = entry.getValue().getEntity();
plugin.getLogger().info("remove portal name=" + entity.getCustomName());
entity.remove();
}
// portalParticles.clear();
// if (bukkitTask > 0) {
// plugin.getServer().getScheduler().cancelTask(bukkitTask);
// }
}
private void cleanupEntityLocation(World world, Location location, Class type) {
if (world != null) {
Collection<LivingEntity> entities = location.getNearbyEntitiesByType(type, 3);
for (LivingEntity entity : entities) {
plugin.getSLF4JLogger().info("remove previous entity={}", entity.getName());
entity.remove();
}
}
}
/**
* Creation d'une entité
*
* @param world
* @param portalConfig
* @return
*/
Entity spawn(World world, PortalConfig portalConfig) {
switch (portalConfig.getEntity().getType()) {
case "villager":
return spawnVillager(world, portalConfig.getEntity());
case "particles":
return spawnParticles(world, portalConfig.getEntity());
default:
plugin.getLogger().severe("Failed to spawn portal for entity type=" + portalConfig.getEntity().getType());
return null;
}
}
/**
* Creation d'une entité de type villageois
*
* @param world
* @param entity
* @return
*/
Entity spawnVillager(World world, EntityConfig entity) {
Location location = parseLocation(world, entity.getLocation());
cleanupEntityLocation(world, location, Villager.class);
location.setYaw(entity.getYaw());
Villager v = (Villager) world.spawnEntity(location, EntityType.VILLAGER);
v.setAI(false);
v.setCustomName(entity.getName());
v.setProfession(Villager.Profession.FLETCHER);
v.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(MAX_HEALTH);
v.setHealth(MAX_HEALTH);
v.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 3560000, 356000));
plugin.getLogger().info("create portal name=" + v.getCustomName() + " at location=" + location);
return v;
}
private Entity spawnParticles(World world, EntityConfig entity) {
return null;
}
public void remoteTeleport(Player player, FullLocation location) {
RemoteTeleportEvent event = new RemoteTeleportEvent();
event.setPlayer(player);
event.setFullLocation(location);
plugin.getChannel().sendChannelEvent(event);
}
public void localTeleport(Player player, FullLocation location) {
plugin.getServer().getScheduler().runTask(plugin, () -> {
Location loc = new Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ());
loc.setYaw(location.getYaw());
if(loc.getX() == 0 && loc.getY() == 0 && loc.getZ() == 0){
loc.setX(loc.getWorld().getSpawnLocation().getX());
loc.setY(loc.getWorld().getSpawnLocation().getY());
loc.setZ(loc.getWorld().getSpawnLocation().getZ());
}
getLogger().info("local teleport player=" + player.getDisplayName() + " location=" + location);
player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);
});
}
public void spawn(Player player, SpawnConfig spawnConfig) {
if (spawnConfig != null) {
Location location = parseLocation(player.getServer().getWorld(spawnConfig.getWorld()), spawnConfig.getLocation());
location.setYaw(spawnConfig.getYaw());
player.teleport(location);
}
}
public void spawn(Player player) {
spawn(player, plugin.getWorldConfig().getSpawn());
}
@Override
public void onChannelMessage(Player player, String channel, String event, List<String> input) {
FullLocation location = new FullLocation();
String type = input.get(0);
switch (type){
case "location":
location.setServer(input.get(1));
location.setWorld(input.get(2));
location.setX(Float.parseFloat(input.get(3)));
location.setY(Float.parseFloat(input.get(4)));
location.setZ(Float.parseFloat(input.get(5)));
location.setYaw(Float.parseFloat(input.get(6)));
localTeleport(player, location);
break;
case "player":
String username = input.get(1);
Player remotePlayer = plugin.getServer().getPlayer(username);
if(remotePlayer != null ) {
location.setServer(remotePlayer.getServer().getName());
location.setWorld(remotePlayer.getWorld().getName());
location.setX((float) remotePlayer.getLocation().getX());
location.setY((float) remotePlayer.getLocation().getY());
location.setZ((float) remotePlayer.getLocation().getZ());
location.setYaw(remotePlayer.getLocation().getYaw());
localTeleport(player, location);
}
break;
default:
plugin.getSLF4JLogger().warn("no teleport event type={} matching options", type);
}
}
public Portal getPortal(UUID uniqueId) {
return portals.get(uniqueId);
}
protected int schedule() {
bukkitTask = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
portalParticles.entrySet().parallelStream().forEach(uuidPortalParticleEntry -> {
PortalParticle portal = uuidPortalParticleEntry.getValue();
portal.update();
});
}, 0, 100L);
return bukkitTask;
}
}
| true
|
383b27890bd6403d5371f87afb7c168602d3ce03
|
Java
|
vdorozco/CS380E2
|
/Exercise2Client.java
|
UTF-8
| 1,216
| 3.3125
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.zip.CRC32;
import java.net.Socket;
public class Exercise2Client {
public static void main(String[] args) throws IOException{
try(Socket s = new Socket("cs380.codebank.xyz",38102)){
System.out.println("Connected to server.");
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
int[] array = new int[100];
byte[] bArray = new byte[100];
System.out.println("Received byte:");
for(int i = 0; i < array.length; i++){
int firstB = is.read();
int secondB = is.read();
array[i] = (firstB<<4)|secondB;
if(i%10==0)
System.out.print("\t");
System.out.printf("%02X", array[i]);
if((i+1)%10==0)
System.out.println();
bArray[i] = (byte)array[i];
}
CRC32 crc = new CRC32();
crc.update(bArray);
long code = crc.getValue();
System.out.printf("Generated CRC32: %08X.\n", code);
byte[] outArray = new byte[4];
for(int i = outArray.length-1; i >= 0; i--){
long ones = 255;
outArray[i] = (byte)(code&ones);
code>>=8;
}
os.write(outArray);
if(is.read()==1)
System.out.println("Response good.");
}
System.out.println("Disconnected from server.");
}
}
| true
|
c5a00f4779cdbc4d73ca823e6a2e74799b1c4e50
|
Java
|
namthse03439/Take-Attendance-V2-Application
|
/app/src/main/java/com/example/intern/takeattendanceapplicationv2t/Fragment/TakeAttendanceToday.java
|
UTF-8
| 14,804
| 1.992188
| 2
|
[] |
no_license
|
package com.example.intern.takeattendanceapplicationv2t.Fragment;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.intern.takeattendanceapplicationv2t.BaseClass.GlobalVariable;
import com.example.intern.takeattendanceapplicationv2t.BaseClass.ServiceGenerator;
import com.example.intern.takeattendanceapplicationv2t.BaseClass.StringClient;
import com.example.intern.takeattendanceapplicationv2t.DetailedInformationActivity;
import com.example.intern.takeattendanceapplicationv2t.Information.ScheduleManager;
import com.example.intern.takeattendanceapplicationv2t.Preferences;
import com.example.intern.takeattendanceapplicationv2t.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TakeAttendanceToday.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TakeAttendanceToday#newInstance} factory method to
* create an instance of this fragment.
*/
public class TakeAttendanceToday extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Calendar calendar;
private TableLayout[] tls = new TableLayout[2];
TextView textTime;
private View myView;
private Activity context;
private OnFragmentInteractionListener mListener;
private static final int MY_CHILD_ACTIVITY = 1;
public static final String UPDATE_SCHEDULE_VIEW = "updateSchedule";
public TakeAttendanceToday() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment TakeAttendanceToday.
*/
// TODO: Rename and change types and number of parameters
public static TakeAttendanceToday newInstance(String param1, String param2) {
TakeAttendanceToday fragment = new TakeAttendanceToday();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalVariable.checkConnected(getActivity());
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = this.getActivity();
}
private String getDateOfWeekString(int dateOfWeek)
{
switch (dateOfWeek)
{
case 1:
return "MON";
case 2:
return "TUES";
case 3:
return "WED";
case 4:
return "THUR";
case 5:
return "FRI";
case 6:
return "SAT";
case 7:
return "SUN";
default:
return "null";
}
}
int getTime(String time)
{
int temp_index = time.lastIndexOf(":");
String temp_current_time = String.valueOf(time.subSequence(0, temp_index));
int current_time = Integer.parseInt(temp_current_time);
return current_time;
}
private void getTableLayout()
{
tls[0] = (TableLayout) myView.findViewById(R.id.tableLayout1);
tls[1] = (TableLayout) myView.findViewById(R.id.tableLayout2);
}
private void displayTimeColumn()
{
for(int i = 0; i < ScheduleManager.timeNumber; i++)
{
List<String> values = new ArrayList<>();
values.add(ScheduleManager.dailyTime[i]);
TextView tvs = new TextView(context);
tvs.setGravity(Gravity.CENTER);
if (i % 2 == 1)
{
tvs.setBackgroundColor(Color.parseColor("#bbdefb"));
}
else
{
tvs.setBackgroundColor(Color.WHITE);
}
tvs.setText(values.get(0));
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, Gravity.CENTER);
params.height = 140;
tvs.setLayoutParams(params);
TableRow trs = new TableRow(context);
TableLayout.LayoutParams layoutRow = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
trs.setLayoutParams(layoutRow);
trs.addView(tvs);
tls[0].addView(trs);
}
}
private void createSubjectView(boolean isExistSubject, final int startTime, final int endTime, final int index, final JSONObject subject)
{
if (!isExistSubject)
{
for(int i = startTime; i < endTime; i++)
{
TextView tvs = new TextView(context);
//tvs.setLines(5);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, Gravity.CENTER);
params.height = 140;
tvs.setLayoutParams(params);
TableRow trs = new TableRow(context);
TableLayout.LayoutParams layoutRow = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
trs.setLayoutParams(layoutRow);
trs.addView(tvs);
tls[1].addView(trs);
}
return;
}
try
{
TextView tvs = new TextView(context);
String temp;
String result = "";
String subject_area = subject.getString("subject_area");
String class_section = subject.getString("class_section");
temp = subject_area + " " + class_section + System.getProperty ("line.separator");
result += temp;
temp = subject.getString("location");
result += temp;
tvs.setGravity(Gravity.CENTER);
tvs.setTextColor(Color.WHITE);
tvs.setText(result);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT, Gravity.CENTER);
params.height = 140 * (endTime - startTime);
tvs.setLayoutParams(params);
GradientDrawable gd = new GradientDrawable();
final int status = Integer.parseInt(subject.getString("status"));
switch (status) {
case 0:
gd.setColor(0xFFC0C0C0);
//tvs.setBackgroundColor(Color.LTGRAY);
break;
case 1:
gd.setColor(0xFF00FF7F);
//tvs.setBackgroundColor(Color.GREEN);
break;
case 2:
gd.setColor(0xFFFFA500);
//tvs.setBackgroundColor(Color.YELLOW);
break;
case 3:
gd.setColor(0xFFCC0000);
//tvs.setBackgroundColor(Color.RED);
break;
}
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
tvs.setBackgroundDrawable(gd);
TableRow trs = new TableRow(context);
TableLayout.LayoutParams layoutRow = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
trs.setLayoutParams(layoutRow);
trs.addView(tvs);
tls[1].addView(trs);
tvs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GlobalVariable.scheduleManager.setCurrentLession(index);
Intent intend = new Intent(context, DetailedInformationActivity.class);
startActivityForResult(intend, MY_CHILD_ACTIVITY);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (MY_CHILD_ACTIVITY) : {
if (resultCode == Activity.RESULT_OK) {
int result = data.getIntExtra(UPDATE_SCHEDULE_VIEW, 0);
if (result == 1)
{
tls[1].removeAllViews();
displayScheduleToday();
}
}
break;
}
}
}
public void displayScheduleToday()
{
JSONArray schedule = GlobalVariable.scheduleManager.getDailySchedule();
int time = 8;
for(int subjectIndex = 0; subjectIndex < schedule.length(); subjectIndex++)
{
JSONObject subject = null;
try
{
subject = schedule.getJSONObject(subjectIndex);
int startSubjectTime = getTime(subject.getString("start_time"));
int endSubjectTime = getTime(subject.getString("end_time"));
createSubjectView(false, time, startSubjectTime, -1, null);
createSubjectView(true, startSubjectTime, endSubjectTime, subjectIndex, subject);
time = endSubjectTime;
} catch (Exception e)
{
e.printStackTrace();
}
}
createSubjectView(false, time, 17, -1, null);
}
private void setTimeView()
{
calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MM/dd/yyyy");
String stringTime = simpleDateFormat.format(calendar.getTime());
textTime = (TextView) myView.findViewById(R.id.text_Time);
textTime.setText(stringTime);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_take_attendance_today, container, false);
setTimeView();
try {
Preferences.showLoading(context, "Setup", "Loading data from server...");
SharedPreferences pref = getActivity().getSharedPreferences("ATK_pref", 0);
String auCode = pref.getString("authorizationCode", null);
StringClient client = ServiceGenerator.createService(StringClient.class, auCode);
Call<ResponseBody> call = client.getTimetableToday();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try{
Preferences.dismissLoading();
JSONArray data = new JSONArray(response.body().string());
GlobalVariable.scheduleManager.setDailySchedule(data);
getTableLayout();
displayTimeColumn();
displayScheduleToday();
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.print("Tung");
}
});
}
catch(Exception e){
System.out.print("load timetable today!");
}
return myView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_takeattendancetitle, menu);
ActionBar actionBar = context.getActionBar();
if(actionBar != null){
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(getString(R.string.title_fragment_take_attendance));
}
super.onCreateOptionsMenu(menu, inflater);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| true
|
3c780c90b9e48aa974a083dd245f63e08046c95f
|
Java
|
ahad1105/ExpediaProject
|
/StayPage.java
|
UTF-8
| 410
| 2.046875
| 2
|
[] |
no_license
|
package POM;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class StayPage {
WebDriver driver;
WebDriverWait wt = null;
public StayPage(WebDriver driver) {
this.driver = driver;
}
public void bookStay() {
driver.findElement(By.cssSelector("a[data-stid='open-hotel-information']")).click();
}
}
| true
|
b17a2457c9ed1b452a3b237b3bb17837ae0b6f97
|
Java
|
happydhKim/MyDataStructureAlgorithm
|
/newMyDataStructureAlgorithm/solve/boj/bfs/5022.java
|
UTF-8
| 2,922
| 2.859375
| 3
|
[] |
no_license
|
package onlineStudy;
//fail
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public class goDs {
static final int X[] = { 0, 0, -1, 1 };
static final int Y[] = { -1, 1, 0, 0 };
static int N, M, cnt, ans, a[][], dist[][], temp[][];
static boolean check[][];
static Pair point[];
static Queue<Pair> q;
static void clean(int depth) {
while (!q.isEmpty()) {
Pair p = q.remove();
int x = p.x;
int y = p.y;
if (depth == 0) {
dist[x][y] = 999;
return;
}
for (int k = 0; k < 4; k++) {
int nx = x + X[k];
int ny = y + Y[k];
if (nx < 0 || ny < 0 || nx >= N + 1 || ny >= M + 1 || check[nx][ny]) {
continue;
}
if (temp[nx][ny] == depth - 1) {
depth--;
dist[nx][ny] = depth;
check[nx][ny] = true;
q.add(new Pair(nx, ny));
break;
}
}
}
}
static void bfs(int caseP) {
int num = 0;
if (caseP == -1) {
num = 0;
} else if (caseP == -2) {
num = 2;
}
q = new LinkedList<>();
q.add(new Pair(point[num].x, point[num].y));
check = new boolean[N + 1][M + 1];
check[point[num].x][point[num].y] = true;
while (!q.isEmpty()) {
Pair p = q.remove();
int x = p.x;
int y = p.y;
for (int k = 0; k < 4; k++) {
int nx = x + X[k];
int ny = y + Y[k];
if (nx < 0 || ny < 0 || nx >= N + 1 || ny >= M + 1 || check[nx][ny]) {
continue;
}
if (dist[nx][ny] != 0 || (a[nx][ny] != 0 && a[point[num].x][point[num].y] != caseP)) {
continue;
}
if (dist[nx][ny] == 0) {
q.add(new Pair(nx, ny));
check[nx][ny] = true;
dist[nx][ny] = dist[x][y] + 1;
}
if (a[nx][ny] == a[point[num].x][point[num].y]) {
dist[nx][ny] = dist[x][y] + 1;
ans += dist[nx][ny];
cnt++;
q = new LinkedList<>();
q.add(new Pair(nx, ny));
if (cnt == 2) {
return;
} else {
int tp = dist[nx][ny];
temp = new int[N + 1][M + 1];
for (int i = 0; i <= N; i++) {
for (int j = 0; j <= M; j++) {
temp[i][j] = dist[i][j];
}
}
dist[nx][ny] = tp;
check = new boolean[N + 1][M + 1];
dist = new int[N + 1][M + 1];
clean(tp);
}
}
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
a = new int[N + 1][M + 1];
dist = new int[N + 1][M + 1];
point = new Pair[4];
ans = 0;
cnt = 0;
for (int i = 0; i < 4; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
point[i] = new Pair(x, y);
if (i == 0 || i == 1) {
a[x][y] = -1;
} else {
a[x][y] = -2;
}
}
bfs(-1);
System.out.println(ans);
int answer = ans;
bfs(-2);
System.out.println(ans);
if (answer == ans) {
System.out.println("IMPOSSIBLE");
} else {
System.out.println(ans);
}
sc.close();
}
}
| true
|
b27df9c9e1c15ee2a496f5a2135557629d792380
|
Java
|
Nayanava/algorithms_in_java
|
/src/com/design/level/low/rate/limiter/middleware/RateLimitMiddleware.java
|
UTF-8
| 2,216
| 2.34375
| 2
|
[] |
no_license
|
package com.design.level.low.rate.limiter.middleware;
/**
* @author nayanava
*/
import com.design.level.low.rate.limiter.RateLimitConfig;
import com.design.level.low.rate.limiter.model.RateLimitRequest;
import com.design.level.low.rate.limiter.model.RateLimitResponse;
import com.design.level.low.rate.limiter.model.RateLimiter;
import com.design.level.low.rate.limiter.schedulers.Schedulers;
import com.design.level.low.rate.limiter.service.IRateLimiterService;
import com.design.level.low.rate.limiter.service.RateLimiterService;
import com.design.level.low.repository.IRateLimitRepository;
import com.design.level.low.repository.impl.InMemoryRateLimitRepository;
import java.io.*;
import java.util.Random;
public class RateLimitMiddleware {
private static String testApi = "/v1/someApi";
public static void main(String[] args) throws InterruptedException {
IRateLimitRepository repository = new InMemoryRateLimitRepository();
IRateLimiterService rateLimiterService = new RateLimiterService(repository);
RateLimitConfig.initConfig();
RateLimitRequest[] requests = new RateLimitRequest[2];
requests[0] = new RateLimitRequest();
requests[0].apiName = testApi;
requests[0].clientId = "user_123";
requests[1] = new RateLimitRequest();
requests[1].apiName = testApi;
requests[1].clientId = "user_124";
try {
for(int i = 1; i < 10; i++) {
RateLimitRequest request = getRequest(requests);
RateLimitResponse response = rateLimiterService.validateLimit(request);
if(!response.isSuccessfulRequest) {
System.out.println("for user " + request.clientId + response.toString());
Thread.sleep(response.rateLimitRetryAfter + 100);
}
System.out.println("for user " + request.clientId + response.toString());
}
} finally {
Schedulers.SCHEDULED_EXECUTOR_SERVICE.shutdown();
}
}
private static RateLimitRequest getRequest(RateLimitRequest[] requests) {
Random rand = new Random();
return requests[rand.nextInt(requests.length)];
}
}
| true
|
788502bc80fa86a61bd0b703ca6f9b268df2b461
|
Java
|
saithurpati/c0debaseBot
|
/src/main/java/de/c0debase/bot/commands/general/PingCommand.java
|
UTF-8
| 788
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
package de.c0debase.bot.commands.general;
import de.c0debase.bot.CodebaseBot;
import de.c0debase.bot.commands.Command;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Message;
import java.awt.*;
/**
* @author Biosphere
* @date 23.01.18
*/
public class PingCommand extends Command {
public PingCommand() {
super("ping", "Zeigt dir den Ping des Bots zu Discord", Category.GENERAL);
}
@Override
public void execute(String[] args, Message msg) {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.appendDescription(":stopwatch: " + CodebaseBot.getInstance().getJda().getPing());
embedBuilder.setColor(Color.GREEN);
msg.getTextChannel().sendMessage(embedBuilder.build()).queue();
}
}
| true
|
5b0449ca487a8cd0ee29f6ad045d50b8367a23e2
|
Java
|
yefim/Squirrel-Toss
|
/src/pennapps/s2012/Squirrel.java
|
UTF-8
| 4,443
| 2.46875
| 2
|
[] |
no_license
|
package pennapps.s2012;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
public class Squirrel extends Sprite {
private int _fuel = 100;
private boolean _inFreeFall, _nearGround = true;
// dv = dt * a
private final double GRAVITY_CONSTANT = 9.8;
private final double GRAVITY_DROP = GRAVITY_CONSTANT / GameThread.FPS;
private final double TILT_ANGLE_RADIANS = 0.2;
private final double BOOST = 1.0;
private final double SLOW_DOWN = 0.01;
private final float POS_X = (float) (HomeScreenActivity.screen_width / 4.0);
private final float POS_Y = (float) (HomeScreenActivity.screen_height / 2.0);
private final double MAX_MIN_ANGLE = 65.0;
private float _bottom;
private boolean _done;
private boolean _stop;
static final double CATCH_UP_SPEED = 5.0;
public Squirrel(Bitmap bmp) {
super(bmp);
_x = 0;
_y = HomeScreenActivity.screen_height-80;
}
public boolean intersects(Sprite other) {
int height = this._bmp.getHeight();
int width = this._bmp.getWidth();
int pos_x = (int) POS_X;
int pos_y = (int) POS_Y;
int oneFourthHeight = height / 4;
int oneFourthWidth = width / 4;
Rect thisRect = new Rect(pos_x + oneFourthWidth, pos_y
+ oneFourthHeight, pos_x + width - oneFourthWidth, pos_y
+ height - oneFourthHeight);
Rect otherRect = new Rect((int) other._x, (int) other._y,
(int) other._x + _width, (int) other._y + _height);
return Rect.intersects(thisRect, otherRect);
}
public void setPosition(double x, double y) {
double deltaX = x - _width / 2 - _x;
double deltaY = y - _width / 2 - _y;
_x += deltaX;
_y += deltaY;
_velocity = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
_angle_radians = Math.atan2(deltaY, deltaX);
_inFreeFall = false;
}
public void inFreeFall() {
_inFreeFall = true;
_x = POS_X;
_y = POS_Y;
}
public void update() {
move();
accelerate_due_to_gravity();
decelerate();
rotate();
if (_bottom < 340)
_nearGround = true;
else
_nearGround = false;
if (_y <= POS_Y)
_nearGround = false;
}
public boolean isNearGround() {
return _nearGround;
}
public void setBottom(float bottom) {
_bottom = bottom;
}
public void move() {
if (_done) {
_x += getXSpeed() / 8;
_velocity -= 8;
if (_velocity <= 0) {
_velocity = 0;
_stop = true;
}
}
_x += _velocity * Math.cos(_angle_radians) / 4;
_y += _velocity * Math.sin(_angle_radians) / 4;
if (!_done && _y >= 630) {
_y = 630;
_x = POS_X;
_angle_radians = 0.0;
_done = true;
}
}
public void tiltUp() {
if (_done || _angle_radians <= Math.toRadians(-MAX_MIN_ANGLE) || _fuel <= 0)
return;
_angle_radians -= TILT_ANGLE_RADIANS;
_fuel -= 5;
}
public void tiltDown() {
if (_done || _angle_radians >= Math.toRadians(MAX_MIN_ANGLE) || _fuel <= 0)
return;
_angle_radians += TILT_ANGLE_RADIANS;
_fuel -= 5;
}
public void increaseVelocity() {
_velocity += 60 * SLOW_DOWN;
}
public void boost() {
if (_fuel <= 0) return;
_velocity += BOOST;
_fuel -= 1;
}
private void accelerate_due_to_gravity() {
if (!_done) {
// break up velocity into X and Y, reduce Y velocity
// then combine them again and adjust the angle
double xVelocity = _velocity * Math.cos(_angle_radians);
double yVelocity = _velocity * Math.sin(_angle_radians);
yVelocity += GRAVITY_DROP;
_velocity = Math
.sqrt(xVelocity * xVelocity + yVelocity * yVelocity);
_angle_radians = Math.atan2(yVelocity, xVelocity);
}
}
public boolean isDone() {
return _done;
}
private void decelerate() {
if (_velocity <= 0)
return;
_velocity -= SLOW_DOWN;
}
public void onDraw(Canvas canvas) {
if(_stop)
canvas.drawBitmap(_bmp, _matrix, null);
else if (_inFreeFall) {
update();
canvas.drawBitmap(_bmp, _matrix, null);
} else {
canvas.drawBitmap(_bmp, _x, _y, null);
}
}
private void rotate() {
float rotation_degrees = (float) Math.toDegrees(_angle_radians);
_matrix.setRotate(rotation_degrees, _bmp.getWidth() / 2,
_bmp.getHeight() / 2);
if (_nearGround)
if (_done)
_matrix.postTranslate(_x, _y);
else
_matrix.postTranslate(POS_X, _y);
else
_matrix.postTranslate(POS_X, POS_Y);
}
public boolean isInFreeFall() {
return this._inFreeFall;
}
public int getFuel() {
return _fuel;
}
public boolean isStopped() {
// TODO Auto-generated method stub
return _stop;
}
}
| true
|
ba2b248fc77324ca52c4d6203cea24df7c707195
|
Java
|
chibd2000/Burp-Extender-Study-Develop
|
/src/main/java/burp/core/scanner/active/shiroscanner/CVE_2016_6802.java
|
UTF-8
| 468
| 2.0625
| 2
|
[] |
no_license
|
package burp.core.scanner.active.shiroscanner;
public class CVE_2016_6802 {
public String exp;
CVE_2016_6802(String requestURI){
// CVE_2016_6802
if (!requestURI.endsWith("/")){
this.exp = requestURI + "/";
}else{
this.exp = "/xxxxxxxxxxxxxxxxxxxxxx";
}
}
public String getExp() {
return exp;
}
@Override
public String toString() {
return "CVE_2016_6802";
}
}
| true
|
4c91a98f9461d62feaf2ab88ffa4e3eaba7c8f1e
|
Java
|
boapinta/randomtext
|
/src/main/java/com/github/randomtext/text/history/ProcessedEventRandomTextService.java
|
UTF-8
| 1,203
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.github.randomtext.text.history;
import com.github.randomtext.text.RandomTextService;
import com.github.randomtext.text.TextResponse;
import org.springframework.context.ApplicationEventPublisher;
import rx.Observable;
/**
* Created by alexey on 6/17/17.
*/
class ProcessedEventRandomTextService implements RandomTextService {
private final RandomTextService delegate;
private final ApplicationEventPublisher publisher;
ProcessedEventRandomTextService(RandomTextService delegate, ApplicationEventPublisher publisher) {
this.delegate = delegate;
this.publisher = publisher;
}
@Override
public Observable<TextResponse> compute(int start, int end, int min, int max) {
return delegate.compute(start, end, min, max)
.doOnNext(res -> publisher.publishEvent(new TextResponseProcessedEvent.Builder()
.freqWord(res.getFreqWord())
.avgParagraphProcessingTime(res.getAvgParagraphProcessingTime())
.avgParagraphSize(res.getAvgParagraphSize())
.totalProcessingTime(res.getTotalProcessingTime())
.build()));
}
}
| true
|
363c76c6c8a45d3c198e75a3cab6e2d2668194bb
|
Java
|
robiulpro/atws-api
|
/src/main/java/com/browntape/amz/tws/pact/GtsService.java
|
UTF-8
| 905
| 1.632813
| 2
|
[] |
no_license
|
package com.browntape.amz.tws.pact;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.gtsexternalsecurity.GTSExternalSecurityService;
import com.amazonaws.services.gtsexternalsecurity.GTSExternalSecurityServiceClient;
import com.browntape.amz.tws.configuration.Configuration;
public abstract class GtsService {
protected final GTSExternalSecurityService gts;
public GtsService() {
AWSCredentials awsCredentials = new BasicAWSCredentials(Configuration.AWSAccessKey, Configuration.AWSSecretKey);
ClientConfiguration clientConfiguration = new ClientConfiguration();
GTSExternalSecurityService gts = new GTSExternalSecurityServiceClient(awsCredentials, clientConfiguration);
gts.setEndpoint(Configuration.GTSPreprodEndpoint_EU);
this.gts = gts;
}
}
| true
|
119c745452b08b721f7af31b93a24715c25a4deb
|
Java
|
orolle/verticleflow.sbpm-flows
|
/src/main/java/net/orolle/verticleflow/http/WebRequest.java
|
UTF-8
| 3,596
| 2.296875
| 2
|
[] |
no_license
|
package net.orolle.verticleflow.http;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map.Entry;
import java.util.UUID;
import net.kuujo.vertigo.io.group.OutputGroup;
import net.kuujo.vertigo.java.ComponentVerticle;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.core.json.JsonObject;
import com.jetdrone.vertx.yoke.engine.Jade4JEngine;
public class WebRequest extends ComponentVerticle {
int requestId = 0;
@Override
public void start() {
final RouteMatcher m = new RouteMatcher();
final Jade4JEngine renderer = new Jade4JEngine("web/index/");
renderer.setVertx(getVertx());
m.all("/", new Handler<HttpServerRequest>() {
final SecureRandom ssid = new SecureRandom();
@Override
public void handle(final HttpServerRequest req) {
final String file = "index.jade";
final JsonObject params = new JsonObject().putString("id", "instance"+new BigInteger(130, ssid).toString());
renderer.render(file, params.toMap(), new Handler<AsyncResult<Buffer>> () {
@Override
public void handle(AsyncResult<Buffer> res) {
if(res.succeeded()) {
req.response().end(res.result());
} else {
req.response().end("<html><body>" +
"render "+file+" with "+params+"<br><br>" +
res.cause().getMessage().replace("\n", "<br>")+"</body><html>");
}
}
});
}
});
m.all("/process/:instance/:subject", new Handler<HttpServerRequest>() {
@Override
public void handle(final HttpServerRequest req) {
final String id = UUID.randomUUID().toString();
//System.out.println("WebRequest["+id+"]");
vertx.eventBus().registerHandler(id, new Handler<Message<String>>() {
@Override
public void handle(Message<String> msg) {
vertx.eventBus().unregisterHandler(id, this);
req.response().end(msg.body());
}
});
if(req.method().equals("POST") || req.method().equals("PUT")) {
req.expectMultiPart(true);
}
req.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer body) {
final JsonObject params = new JsonObject();
for (Entry<String, String> e : req.params().entries()) {
params.putString(e.getKey(), e.getValue());
}
if(req.method().equals("POST") || req.method().equals("PUT")) {
for (Entry<String, String> e : req.formAttributes().entries()) {
params.putString(e.getKey(), e.getValue());
}
}
//System.out.println(params.encodePrettily());
output.port("request").group(id, new Handler<OutputGroup>() {
@Override
public void handle(OutputGroup group) {
group.send(params).end();
}
});
}
});
}
});
vertx.createHttpServer()
.requestHandler(m)
.listen(8080, new Handler<AsyncResult<HttpServer>>() {
@Override
public void handle(AsyncResult<HttpServer> event) {
System.out.println("start web server on 0.0.0.0:8080");
}
});
}
}
| true
|
91ca3eb611d2a494f6677d6d91faed536ca805c1
|
Java
|
wellcao/InterviewQuestion
|
/app/src/main/java/wellcao/com/myresume/factory/abstractfactory/RedPie.java
|
UTF-8
| 247
| 2.609375
| 3
|
[] |
no_license
|
package wellcao.com.myresume.factory.abstractfactory;
/**
* @author wellcao
* @date 2018/8/8
* class introduction:
*/
public class RedPie implements Pie {
@Override
public String display() {
return "我是 红 Pie";
}
}
| true
|
1c35feeb20b4c13f73e52e2c5defb7f4a6c7cece
|
Java
|
wmdkanhai/LasProject
|
/app/src/main/java/xm/lasproject/app/MyApplication.java
|
UTF-8
| 2,226
| 2.28125
| 2
|
[] |
no_license
|
package xm.lasproject.app;
import android.app.Application;
import com.zhy.http.okhttp.OkHttpUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.TimeUnit;
import cn.bmob.newim.BmobIM;
import cn.bmob.v3.Bmob;
import okhttp3.OkHttpClient;
import xm.lasproject.util.DemoMessageHandler;
import static xm.lasproject.config.SystemVar.BMOB_APPLICATION_ID;
/**
* <pre>
* author : xm
* e-mail : wmdkanhai@qq.com
* time : 2017/03/24
* desc : xxx描述
* version: 1.0
* </pre>
*/
public class MyApplication extends Application {
private static MyApplication INSTANCE;
public static MyApplication INSTANCE() {
return INSTANCE;
}
private void setInstance(MyApplication app) {
setBmobIMApplication(app);
}
private static void setBmobIMApplication(MyApplication a) {
MyApplication.INSTANCE = a;
}
@Override
public void onCreate() {
super.onCreate();
Bmob.initialize(this, BMOB_APPLICATION_ID);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
//其他配置
.build();
OkHttpUtils.initClient(okHttpClient);
//只有主进程运行的时候才需要初始化
if (getApplicationInfo().packageName.equals(getMyProcessName())) {
//im初始化
BmobIM.init(this);
//注册消息接收器
BmobIM.registerDefaultMessageHandler(new DemoMessageHandler(this));
}
}
/**
* 获取当前运行的进程名
*
* @return
*/
public static String getMyProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| true
|
bf1a986453711eb690ad059bd1c07dcc558b6eac
|
Java
|
AfteRRaIN-Sys/EX4
|
/src/test/TestWorker.java
|
UTF-8
| 631
| 2.5
| 2
|
[] |
no_license
|
package test;
import static org.junit.Assert.*;
import java.lang.reflect.Modifier;
import org.junit.Before;
import org.junit.Test;
import model.Bot;
import model.Worker;
public class TestWorker {
@Test
public void testInterface() {
try{
assertEquals(true,Modifier.isInterface((Worker.class).getModifiers()));
}catch (Exception e) {
// TODO: handle exception
fail("Worker doesnt exist");
}
}
@Test
public void testInterfaceMethod() {
try{
assertEquals(true,Modifier.isAbstract((Worker.class).getMethod("work", null).getModifiers()));}
catch(Exception e){
fail("work doesnt exist");
}
}
}
| true
|
6956d1faad1109269ecc7d5ef86d1c7833d394a4
|
Java
|
johanberggren/mimic-projektarbete
|
/group_project/src/main/java/print_3/group_project/Sprint3Runner.java
|
UTF-8
| 387
| 1.664063
| 2
|
[] |
no_license
|
package print_3.group_project;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src\\main\\java\\print_3\\group_project\\Sprint3.feature"}, glue = {""}, plugin = {"pretty",
"html:target/ResultsTable/index.html"})
public class Sprint3Runner {
}
| true
|
e3f99307d10e6e597978e2c70bb07f6cb5544b7c
|
Java
|
cluzt/spring-boot-activiti
|
/src/main/java/com/example/domain/LeaveRequest.java
|
UTF-8
| 2,830
| 2.34375
| 2
|
[] |
no_license
|
package com.example.domain;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author muhammad.duano Uses XmlRootElement annotation to support both JSON
* and XML
*
*/
@Entity
@XmlRootElement
public class LeaveRequest {
@Id
@GeneratedValue
private Long id;
private String type;
private String project;
private String permissionType;
private String description;
private Long assessedBy;
private Date assessedDate;
private String status;
@ManyToOne
@JoinColumn(name = "employeeId")
private Employee employee;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "leaveRequestId")
Set<LeaveDate> leaveDates;
public LeaveRequest() {
super();
}
public LeaveRequest(Long id, String type, String project, String permissionType, String description,
Long assessedBy, Date assessedDate, String status, Employee employee, Set<LeaveDate> leaveDates) {
super();
this.id = id;
this.type = type;
this.project = project;
this.permissionType = permissionType;
this.description = description;
this.assessedBy = assessedBy;
this.assessedDate = assessedDate;
this.status = status;
this.employee = employee;
this.leaveDates = leaveDates;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getPermissionType() {
return permissionType;
}
public void setPermissionType(String permissionType) {
this.permissionType = permissionType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getAssessedBy() {
return assessedBy;
}
public void setAssessedBy(Long assessedBy) {
this.assessedBy = assessedBy;
}
public Date getAssessedDate() {
return assessedDate;
}
public void setAssessedDate(Date assessedDate) {
this.assessedDate = assessedDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Set<LeaveDate> getLeaveDates() {
return leaveDates;
}
public void setLeaveDates(Set<LeaveDate> leaveDates) {
this.leaveDates = leaveDates;
}
}
| true
|
9a8c865bab39b5f4b398fd1fdffd63f1ba8bc02b
|
Java
|
imbkj/BMSbate
|
/src/bll/EmBodyCheck/OutExcelImpl.java
|
UTF-8
| 5,336
| 2.34375
| 2
|
[] |
no_license
|
package bll.EmBodyCheck;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import service.ExcelService;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import Model.EmBcItemGroupModel;
import Model.EmBodyCheckItemModel;
import Model.EmBodyCheckModel;
public class OutExcelImpl implements ExcelService {
private File file;// excel文件对象
private String sheetName;// sheet名称
private String[] title;// 标题字符串
private List<EmBodyCheckModel> bclist;// excel中的内容
private EmBcInfo_SelectBll bll = new EmBcInfo_SelectBll();
public OutExcelImpl(File file, String sheetName, String[] title,
List<EmBodyCheckModel> lists) {
// TODO Auto-generated method stub
this.file = file;
this.sheetName = sheetName;
this.title = title;
this.bclist = lists;
}
@Override
public void writeExcel() throws Exception {
WritableWorkbook wwb = Workbook.createWorkbook(new FileOutputStream(
file));
WritableSheet sheet = wwb.createSheet(sheetName, 0);
// 设置标题的文字格式
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD, true, UnderlineStyle.NO_UNDERLINE);// 字体、粗体、斜体、下划线
WritableCellFormat wcf = new WritableCellFormat(wf);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
wcf.setAlignment(Alignment.CENTRE);
// 行高设置行高,参数(行数,高度)
sheet.setRowView(0, 500);
// 开始写入第一行(即标题栏)
for (int i = 0; i < title.length; i++) {
// 用于写入文本内容到工作表中去
Label label = null;
// 在Label对象的构造中指明单元格位置(参数依次代表列数、行数、内容 )
label = new Label(i, 0, title[i], wcf);
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
// 开始写入内容
for (int row = 1; row < bclist.size() + 1; row++) {
// 用model获取每一行数据
EmBodyCheckModel cop = bclist.get(row - 1);
// 将每列数据写入工作表中
Label label = null;
label = new Label(0, row, row + "");
sheet.addCell(label);
label = new Label(1, row, cop.getCid().toString());
sheet.addCell(label);
String gid = "";
if (cop.getGid() != null) {
gid = cop.getGid().toString();
}
label = new Label(2, row, gid);
sheet.addCell(label);
label = new Label(3, row, cop.getEmbc_client());
sheet.addCell(label);
label = new Label(4, row, cop.getCoba_manager());
sheet.addCell(label);
label = new Label(5, row, cop.getEmbc_shortname());
sheet.addCell(label);
label = new Label(6, row, cop.getEmbc_name());
sheet.addCell(label);
label = new Label(7, row, cop.getEmbc_idcard());
sheet.addCell(label);
label = new Label(8, row, cop.getEbcl_bcid());
sheet.addCell(label);
label = new Label(9, row, cop.getEbcs_hospital());
sheet.addCell(label);
label = new Label(10, row, cop.getEbcl_itemsstr());
sheet.addCell(label);
String fee = "";
if (cop.getEbcl_charge() != null) {
fee = cop.getEbcl_charge().toString();
}
label = new Label(11, row, fee);
sheet.addCell(label);
String disfee = "";
if (cop.getEbcl_discount() != null) {
disfee = cop.getEbcl_discount().toString();
} else {
if (cop.getEbcl_charge() != null) {
disfee = cop.getEbcl_charge().toString();
}
}
label = new Label(12, row, disfee);
sheet.addCell(label);
label = new Label(13, row, cop.getEbcl_typename());
sheet.addCell(label);
String bookdate = cop.getEbcl_plandate() == null ? cop
.getEbcl_bookdate() : cop.getEbcl_plandate();
label = new Label(14, row, bookdate);
sheet.addCell(label);
label = new Label(15, row, cop.getEbcl_completedate());
sheet.addCell(label);
label = new Label(16, row, cop.getEbsa_address());
sheet.addCell(label);
label = new Label(17, row, cop.getEbcl_showclient());
sheet.addCell(label);
label = new Label(18, row, cop.getEbcl_clientshowdate());
sheet.addCell(label);
label = new Label(19, row, cop.getEbcl_balancedate());
sheet.addCell(label);
label = new Label(20, row, cop.getEmpType());
sheet.addCell(label);
}
// 写入数据
wwb.write();
// 关闭文件
wwb.close();
}
private String getLimit(String itemsId) {
EmBodyCheckItemModel m = new EmBodyCheckItemModel();
m.setIdList(itemsId);
List<EmBodyCheckItemModel> list = bll.getGroupItemList(m);
String limit = "";
for (EmBodyCheckItemModel ml : list) {
if (ml.getSex() != null && !ml.getSex().equals("无限制")) {
limit = limit + ml.getSex() + ",";
}
if (ml.getMarry() != null && !ml.getMarry().equals("无限制")) {
limit = limit + ml.getMarry() + ",";
}
}
if (limit.length() > 0) {
limit = limit.substring(0, limit.length() - 1);
} else {
limit = "无限制";
}
return limit;
}
@Override
public void exportExcel() throws Exception {
// TODO Auto-generated method stub
}
}
| true
|
d0c841b031c79c64a909b92bd24020be274b73f5
|
Java
|
kirill-grouchnikov/ixent
|
/src/org/jvnet/ixent/algorithms/geometry/spacefilling/SpaceFillingCurveStructure.java
|
UTF-8
| 13,702
| 2.9375
| 3
|
[] |
no_license
|
package org.jvnet.ixent.algorithms.geometry.spacefilling;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.List;
import org.jvnet.ixent.algorithms.graphics.edgedetection.EdgeDetector;
import org.jvnet.ixent.algorithms.graphics.edgedetection.EdgeDetectorFactory;
import org.jvnet.ixent.graphics.IndexBitmapObject;
import org.jvnet.ixent.math.coord.Vertex2D;
/**
* Space filling curve based on structure vicinity. The distance between any
* given pair of centers depends on how close they lie to some image feature.
*
* @author Kirill Grouchnikov
*/
public final class SpaceFillingCurveStructure extends SpaceFillingCurveBase {
// public static final int CELL_MAX_RADIUS = 3;
private int width, height;
private int cellMaxRadius, cellMinRadius;
private boolean toAllocateAlongEdges;
/**
* Construct space filling curve
*
* @param cellMaxRadius minimal distance between any two centers
* that lie far from image features
* @param pToAllocateAlongEdges if <code>true</code>, additional points will
* be allocated along the edges of the image
*/
public SpaceFillingCurveStructure(int cellMaxRadius,
boolean pToAllocateAlongEdges) {
this.cellMaxRadius = cellMaxRadius;
this.cellMinRadius = (int) (Math.ceil((double) cellMaxRadius / 2.0));
this.minDistanceBetweenCenters = this.cellMinRadius;
this.toAllocateAlongEdges = pToAllocateAlongEdges;
}
/**
* Create coverage by centering a "disk" of given radius at given location.
* If this location is already "taken" (covered or disk center), this
* function returns. Otherwise it marks the central pixel as "disk center"
* and its immediate vicinity (using regular distance metric) as "covered"
*
* @param xc pixel center column
* @param yc pixel center row
* @param radius distance. All pixels lying at most <b>distance</b> pixels
* away will be marked as "covered"
*/
private void createDiskCoverage(int xc, int yc, int radius) {
if (this.pixelStatus[xc][yc] == PixelStatus.diskCenter) {
return;
}
if (radius < this.cellMinRadius) {
radius = this.cellMinRadius;
}
int radius2 = radius * radius;
for (int dx = -radius; dx <= radius; dx++) {
for (int dy = -radius; dy <= radius; dy++) {
int nx = xc + dx;
if ((nx < 0) || (nx >= this.width)) {
continue;
}
int ny = yc + dy;
if ((ny < 0) || (ny >= this.height)) {
continue;
}
if (this.pixelStatus[nx][ny] != PixelStatus.notTaken) {
continue;
}
if ((dx * dx + dy * dy) > radius2) {
continue;
}
this.pixelStatus[nx][ny] = PixelStatus.covered;
}
}
this.pixelStatus[xc][yc] = PixelStatus.diskCenter;
this.centerCount++;
}
/**
* Initialize this filling curve using given true-color bitmap. Throws an
* exception if the input image is null
*
* @param bitmapObject the input image
* @throws IllegalArgumentException if the input image is null
*/
public void init(BufferedImage bitmapObject) {
if (bitmapObject == null) {
throw new IllegalArgumentException("Can't pass null object");
}
this.width = bitmapObject.getWidth();
this.height = bitmapObject.getHeight();
IndexBitmapObject structureVicinityMap = new IndexBitmapObject(width,
height);
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++) {
structureVicinityMap.setValue(col, row,
this.cellMaxRadius);
}
}
// compute structure vicinity map based only on edges
EdgeDetector edgeDetector = EdgeDetectorFactory.getEdgeDetector(
bitmapObject);
IndexBitmapObject edgeObject = edgeDetector.getValueMap2D(
EdgeDetector.EdgeFuzzyness.exact,
EdgeDetector.EdgeStrength.soft);
// update structure vicinity map based on the edge closeness
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++) {
if (edgeObject.getValue(col, row) > 0) {
// edge point
for (int dx = -this.cellMaxRadius;
dx <= this.cellMaxRadius; dx++) {
int nx = col + dx;
if ((nx < 0) || (nx >= width)) {
continue;
}
int ddx = (dx > 0) ? dx : -dx;
for (int dy = -this.cellMaxRadius;
dy <= this.cellMaxRadius; dy++) {
int ny = row + dy;
if ((ny < 0) || (ny >= height)) {
continue;
}
int ddy = (dy > 0) ? dy : -dy;
int dist = ddx + ddy;
if (structureVicinityMap.getValue(nx, ny) > dist) {
structureVicinityMap.setValue(nx, ny, dist);
}
}
}
}
}
}
// call initializer that takes structure vicinity map as a parameter
this.init(structureVicinityMap);
}
/**
* Initialize this filling curve using given true-color bitmap. Throws an
* exception if the bitmap is null or one of the entries in it is negative
*
* @param structureVicinityMap the structure vicinity map. Each pixel has an
* associated non-negative integer value
* specifying how far does it lie from some
* image feature (such as edge or segment
* boundary)
* @throws IllegalArgumentException if the map is null or one of the entries
* in the map is negative
*/
public void init(IndexBitmapObject structureVicinityMap) {
if (structureVicinityMap == null) {
throw new IllegalArgumentException("Can't pass null object");
}
this.width = structureVicinityMap.getWidth();
this.height = structureVicinityMap.getHeight();
// check that there are no negative entries
for (int col = 0; col < this.width; col++) {
for (int row = 0; row < this.height; row++) {
if (structureVicinityMap.getValue(col, row) < 0) {
throw new IllegalArgumentException("Negative entry at [" +
col + ", " + row + "]: " +
structureVicinityMap.getValue(col, row));
}
}
}
// compute amount of points for each edge distance
int[] edgeDistanceCount = new int[2 * this.cellMaxRadius + 1];
for (int i = 0; i < edgeDistanceCount.length; i++) {
edgeDistanceCount[i] = 0;
}
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++) {
edgeDistanceCount[structureVicinityMap.getValue(col, row)]++;
}
}
// for (int i=0; i<edgeDistanceCount.length; i++)
// System.out.println(edgeDistanceCount[i] + " points at distance " + i);
// allocate permutation array
int total = this.width * this.height;
int[] visitOrder = new int[total];
for (int i = 0; i < total; i++) {
visitOrder[i] = -1;
}
int[] countBeforeEdgeDistance = new int[2 * this.cellMaxRadius + 1];
countBeforeEdgeDistance[0] = 0;
for (int i = 0; i < (countBeforeEdgeDistance.length - 1); i++) {
countBeforeEdgeDistance[i + 1] = countBeforeEdgeDistance[i] +
edgeDistanceCount[i];
}
// for (int i=0; i<countBeforeEdgeDistance.length; i++)
// System.out.println(countBeforeEdgeDistance[i] + " points at distance < " + i);
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++) {
// get edge distance
int edgeDistance = structureVicinityMap.getValue(col, row);
// setLocation visiting order
visitOrder[countBeforeEdgeDistance[edgeDistance]] = row *
width +
col;
// update count
countBeforeEdgeDistance[edgeDistance]++;
}
}
// create random permutation among each group
for (int i = 0; i < edgeDistanceCount.length; i++) {
int startIndex = (i == 0) ? 0 : countBeforeEdgeDistance[i - 1];
int endIndex = countBeforeEdgeDistance[i] - 1;
// System.out.println("permuting in [" + startIndex + ", " + endIndex + "]");
for (int j = startIndex; j <= endIndex; j++) {
int newPos = startIndex +
(int) ((endIndex - startIndex) * Math.random());
int tmp = visitOrder[j];
visitOrder[j] = visitOrder[newPos];
visitOrder[newPos] = tmp;
}
}
// create centers array and allocate along edges
this.pixelStatus = new PixelStatus[width][height];
for (int col = 0; col < width; col++) {
for (int row = 0; row < height; row++) {
pixelStatus[col][row] = PixelStatus.notTaken;
}
}
// visit
for (int visit = 0; visit < total; visit++) {
int centerIndex = visitOrder[visit];
int centerX = centerIndex % this.width;
int centerY = centerIndex / this.width;
// check if already visited
if (pixelStatus[centerX][centerY] != PixelStatus.notTaken) {
continue;
}
this.createDiskCoverage(centerX, centerY,
structureVicinityMap.getValue(centerX, centerY));
}
this.centers = new Vertex2D[this.centerCount];
int count = 0;
for (int col = 0; col < this.width; col++) {
for (int row = 0; row < this.height; row++) {
if (pixelStatus[col][row] == PixelStatus.diskCenter) {
this.centers[count++] = new Vertex2D(col, row);
}
}
}
if (this.toAllocateAlongEdges) {
// replicate centers in the vicinity of the edges
List<Vertex2D> replicatedCenters = new LinkedList<Vertex2D>();
int offset = 5 + 2 * this.getMinDistanceBetweenCenters();
int leftMarginX = offset;
int rightMarginX = this.width - offset;
int topMarginY = offset;
int bottomMarginY = this.height - offset;
for (int i = 0; i < this.centers.length; i++) {
double x = this.centers[i].getX();
double y = this.centers[i].getY();
// borders
if (x < leftMarginX) {
replicatedCenters.add(new Vertex2D(this.width + x, y));
}
if (x > rightMarginX) {
replicatedCenters.add(new Vertex2D(x - this.width, y));
}
if (y < topMarginY) {
replicatedCenters.add(new Vertex2D(x, this.height + y));
}
if (y > bottomMarginY) {
replicatedCenters.add(new Vertex2D(x, y - this.height));
}
// corners
if ((x < leftMarginX) && (y < topMarginY)) {
replicatedCenters.add(
new Vertex2D(this.width + x, this.height + y));
}
if ((x > rightMarginX) && (y < topMarginY)) {
replicatedCenters.add(
new Vertex2D(x - this.width, this.height + y));
}
if ((x < leftMarginX) && (y > bottomMarginY)) {
replicatedCenters.add(
new Vertex2D(this.width + x, y - this.height));
}
if ((x > rightMarginX) && (y > bottomMarginY)) {
replicatedCenters.add(
new Vertex2D(x - this.width, y - this.height));
}
}
Vertex2D[] newCenters = new Vertex2D[this.centers.length +
replicatedCenters.size()];
int prevCount = this.centers.length;
for (int i = 0; i < prevCount; i++) {
newCenters[i] = this.centers[i];
}
for (Vertex2D currVertex : replicatedCenters) {
newCenters[prevCount++] = currVertex;
}
this.centers = newCenters;
}
}
/**
* Initialize this filling curve using only width and height. Throws an
* exception as this operation is not supported by this class
*
* @param width image width
* @param height image height
* @throws UnsupportedOperationException
*/
public void init(int width, int height) {
throw new UnsupportedOperationException();
}
}
| true
|
f71ca3f06128036cd6f7f47e72ff4334420f3d90
|
Java
|
EEIT10204/HyacinthProj
|
/src/main/java/controller/BlogPage1Controller.java
|
UTF-8
| 17,629
| 1.914063
| 2
|
[] |
no_license
|
package controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import model.BGCommentBean;
import model.BGCommentService;
import model.BlogBean;
import model.BlogService;
import model.CityBean;
import model.MemberBean;
import model.MemberBlogBean;
import model.MemberBlogService;
@Controller
public class BlogPage1Controller {
@Autowired
private BlogService blogService;
@Autowired
private MemberBlogService memberBlogService;
@Autowired
private BGCommentService bGCommentService;
@InitBinder
public void registerPropertyEditor(WebDataBinder webDataBinder) {
// webDataBinder.registerCustomEditor(Byte[].class,new ByteArrayMultipartFileEditor());
webDataBinder.registerCustomEditor(byte[].class,new ByteArrayMultipartFileEditor());
}
//MemberBlogselectScoreONload用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/MemberBlogselectScoreONload.controller"})
@ResponseBody
public Double MemberBlogselectScoreONload(
@RequestParam("memberID")Integer memberID
,@RequestParam("blogSNum")Integer blogSNum) {
// System.out.println("run controller MemberBlogselectScoreONload");
Double selectScore = memberBlogService.selectScore(memberID, blogSNum);
// System.out.println("selectScore = "+selectScore);
return selectScore;
}
//MemberBlogUpdatelike用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/MemberBlogScoreUpdate.controller"})
@ResponseBody
public MemberBlogBean MemberBlogScoreUpdate(
@RequestParam("memberID")Integer memberID,
@RequestParam("blogSNum")Integer blogSNum,
String score
) {
//Console沒印---------------------------------------
// System.out.println("檢查是否有MEMBERID = "+memberID);
// System.out.println("檢查是否有blogSNum = "+blogSNum);
// System.out.println("檢查是否有score = "+score);
// System.out.println("run controller MemberBlogScore!!!!Update");
MemberBlogBean tempScore = memberBlogService.updateupdateScoreike(memberID, blogSNum, Double.valueOf(score));
// System.out.println("檢查評分是否成功回傳 = "+tempScore);
return tempScore;
}
//MemberBlogUpdatelike用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/MemberBloglikeUpdate.controller"})
@ResponseBody
public MemberBlogBean MemberBloglikeUpdate(
@RequestParam("memberID")Integer memberID,
@RequestParam("blogSNum")Integer blogSNum,
String like
) {
// System.out.println("run controller MemberBloglikeUpdate");
MemberBlogBean temp = memberBlogService.updateLike(memberID, blogSNum, Integer.valueOf(like));
// System.out.println("MemberBloglikeUpdate = "+temp);
return temp;
}
//MemberBloglikeONload用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/MemberBloglikeONload.controller"})
@ResponseBody
public Boolean MemberBloglikeONload(
@RequestParam("memberID")Integer memberID
,@RequestParam("blogSNum")Integer blogSNum) {
System.out.println("run controller MemberBloglikeONload");
Boolean temp = memberBlogService.selectLike(memberID, blogSNum);
// System.out.println("MemberBloglikeONload = "+temp);
return temp;
}
//MemberBloglike用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/MemberBloglike.controller"})
@ResponseBody
public Object[] MemberBloglike(@RequestParam("blogSNum")Integer blogSNum) {
System.out.println("run controller MemberBloglike");
Object[] temp = memberBlogService.findSavesAVGScores(blogSNum);
// System.out.println("MemberBloglike = "+ temp[0]);
return temp;
}
//BlogDelete用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogDelete.controller"})
@ResponseBody
public Map<String, String> BlogDelete(
@RequestParam("blogSNum")Integer blogSNum,
Model model
) {
// System.out.println("run controller BlogDelete");
// System.out.println("blogSNum = "+blogSNum);
Map<String, String> map = new HashMap<>();
BlogBean beanDelete = blogService.updateDelete(blogSNum);
// System.out.println("beanDelete = "+beanDelete);
// model.addAttribute("beanDelete", beanDelete);
if(beanDelete!=null) {
map.put("result", "網誌刪除成功");
}
else{map.put("result", "網誌刪除失敗");}
return map;
}
//BlogUpdate用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogUpdate.controller"})
public String BlogUpdate(
@RequestParam("blogSNum")Integer blogSNum,
Model model
) {
// System.out.println("run controller BlogUpdate");
List<Object[]> BeanSNum = blogService.selectByBlogNewPage(blogSNum);
model.addAttribute("BeanSNum", BeanSNum);
return "BlogUpdate";
}
//BlogEditor用----首頁至個人網誌用-------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogMember.controller"})
public String BlogEditor(
@RequestParam("blogSNum")Integer blogSNum,
Model model,BGCommentBean bean,BindingResult bindingResult
) {
// System.out.println("run controller Editor");
List<Object[]> BeanSNum = blogService.selectByBlogNewPage(blogSNum);
// for(Object[] BeanSNum1:BeanSNum) {
// System.out.println(((CityBean)BeanSNum1[1]).getNation());
// }
List<Object[]> catchAllComment = bGCommentService.selectBlogCommMemberJoin(blogSNum);
model.addAttribute("BGComment",catchAllComment);
model.addAttribute("BeanSNum", BeanSNum);
return "BlogMember";
}
//Blog留言新增功能
@RequestMapping(path= {"/Blog/BlogMember.comment"})
public String BlogCommentInsert(
@RequestParam("blogSNum")Integer blogSNum,
Model model,BGCommentBean bean,BindingResult bindingResult
) {
// System.out.println("run commet: " + bean.toString());
BGCommentBean result = bGCommentService.insert(bean);
List<Object[]> InsertComment = bGCommentService.selectBlogCommMemberJoin(blogSNum);
// System.out.println("comment catch reply: " + InsertComment.size());
List<Object[]> BeanSNum = blogService.selectByBlogNewPage(blogSNum);
model.addAttribute("BGComment",InsertComment);
model.addAttribute("BeanSNum", BeanSNum);
return "BlogMember";
}
//Blog留言修改功能
@RequestMapping(path = {"/BGCommentUpdate.Controller"})
public String method2(Integer blogSNum,Integer memberID,Model model,
BGCommentBean bean,BindingResult bindingResult) {
BGCommentBean result = bGCommentService.update(bean);
// System.out.println("beanid="+bean.getBGCommentID());
// System.out.println("bean="+bean);
// System.out.println("blogSNum="+blogSNum);
// System.out.println("memberID="+memberID);
// System.out.println("result="+result);
// model.addAttribute("update",result);
List<Object[]> beans = bGCommentService.selectBlogCommMemberJoin(blogSNum);
// System.out.println("beans="+beans);
List<Object[]> BeanSNum = blogService.selectByBlogNewPage(blogSNum);
model.addAttribute("BeanSNum", BeanSNum);
model.addAttribute("BGComment",beans);
return "BlogMember";
}
//BlogIndex用 圖片問題未解-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogIndex.controller"})
public String forSubmit(//String傳入使用
// BlogBean bean,BindingResult bindingResult,
String search,
String page,
String newhot,
Model model) {
// System.out.println("run controller1111");
// System.out.println("page = " + page);
// System.out.println("search = " + search);
// System.out.println("newhot = " + newhot);
List<Object[]> beanMain = blogService.selectByInput(search, page,6,newhot);
List<Object[]> beanAsideHot = blogService.selectByInput(null,"1",4,"hot");
List<Object[]> beanAsideNew = blogService.selectByInput(null,"1",4,"new");
// for(Object[] beanAsideHot1:beanAsideHot) {
// System.out.println((BlogBean)beanAsideHot1[0]);
// }
// for(Object[] beanAsideHot1:beanAsideHot) {
// System.out.println("test = "+((BlogBean)beanAsideHot1[0]).getBlogCoverToBase64());
// }
// for(Object[] beanAsideNew1:beanAsideNew) {
// System.out.println(((BlogBean)beanAsideNew1[0]).getBlogReleaseTime());
// }
// System.out.println("beanAsideHot = " + beanAsideHot);
// System.out.println("beanAsideNew = " + beanAsideNew);
// for(Object[] beanMain1:beanMain) {
// System.out.println("test22 = "+((BlogBean)beanMain1[0]).getBlogCover());
//
// }
model.addAttribute("result", beanMain);
model.addAttribute("result2", beanAsideHot);
model.addAttribute("result3", beanAsideNew);
model.addAttribute("search", search);
model.addAttribute("newhot", newhot);
if(beanMain==null) {
// System.out.println("!!!!");
return "errorPage1";
}
return "okPage1";
}
//BlogIndex用
@RequestMapping(path= {"/Blog/BlogIndexNav.controller"})
@ResponseBody
public List<BlogBean> forNavLoad() {//預先載入Date使用
// System.out.println("run controller NAV");
List<BlogBean> select1 = blogService.selectByCityNav();
return select1;
}
//BlogIndex用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogIndexFirstOnload2.controller"})
@ResponseBody
public List<Object[]> forFirstLoad2() {//預先載入使用
// System.out.println("run controller WWWWWWWW");
List<Object[]> main = blogService.selectByInput("台灣", "1",6,"hot");
List<Object[]> mainAsideNew = blogService.selectByInput(null,"1",4,"new");
List<Object[]> mainAsideHot = blogService.selectByInput(null,"1",4,"hot");
main.addAll(mainAsideNew);
main.addAll(mainAsideHot);
// System.out.println("main = "+main);
return main;
}
//BlogNew用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogNew.controller"},method={RequestMethod.POST})
public String forNewBlog(
Model model,
@ModelAttribute(name="form")BlogBean blogBean,BindingResult bindingResult,
// @SessionAttribute(name="memberID")BlogBean memberID,
// @RequestParam(value="memberID",required = false)Integer memberID,
// @RequestParam("memberID")String memberID,
// @RequestParam("blogCover") MultipartFile blogCover,
@RequestParam("summernote") String summernote
// @RequestParam("blogSNum")Integer blogSNum
) {
// Integer mID = Integer.valueOf(memberID);
// System.out.println("run controller NEW~~");
// System.out.println("memberID = "+memberID);
// System.out.println("blogBean now = "+blogBean);
// System.out.println("summernote = "+summernote);
// try {
// System.out.println("blogCover = "+blogCover.getBytes());
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
if(blogBean.getBlogSNum()!=null && !"".equals(blogBean.getBlogSNum())) {
blogBean.setBlogSNum(blogBean.getBlogSNum());
}
if(blogBean.getBlogReleaseTime()==null||"".equals(blogBean.getBlogReleaseTime())) {
blogBean.setBlogReleaseTime(new java.util.Date());
}
blogBean.setUpdateTime(new java.util.Date());
blogBean.setBlogVisibility(1);
// blogBean.setBlogCity(blogBean.getBlogCity());
blogBean.setBlogContext(summernote);
// System.out.println("Cover = "+blogBean.getBlogCover());
// System.out.println("Cover = "+blogBean.getBlogCover().length);
if(blogBean.getBlogCover().length==0) {
BlogBean pic = blogService.selectByPk(blogBean.getBlogSNum());
blogBean.setBlogCover(pic.getBlogCover());
blogBean.setBlogCover(blogBean.getBlogCover());
}
// blogBean.setBlogTitle(blogBean.getBlogTitle());
// System.out.println("BlogTitle = "+blogBean.getBlogTitle());
blogBean.setBlogView(0);
blogBean.setMemberID(blogBean.getMemberID());
// System.out.println("getBlogContext = "+);
model.addAttribute("summernote", summernote);
// blogService.insert(blogBean);
blogService.saveUpdate(blogBean);
// System.out.println("AAA = "+AAA);
return "newPage1";
}
//未使用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogIndexFirstOnload.controller"})
@ResponseBody
public List<Object[]> forFirstLoad() {//預先載入使用
// System.out.println("run controller 2222");
// if(page==null) {
// BlogBean bb=new BlogBean();
// bb.setBlogCity("台中");
// System.out.println("beanCITY="+bean.getBlogCity());
// List<BlogBean> bean1 = blogService.selectByCity(bb,1);
List<Object[]> select = blogService.selectByNation("台灣",1);
// for( Object[] select1:select) {
// System.out.println("select1 = "+(CityBean)select1[1]);
// }
// }
return select;
}
//未使用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogIndexDate2222.controller"})
@ResponseBody
public List<Object[]> forFirstLoadDate() {//預先載入Date使用
// if(page==null) {
// BlogBean bb=new BlogBean();
// bb.setBlogCity("台中");
// System.out.println("run controller 33333");
// System.out.println("beanCITY="+bean.getBlogCity());
List<Object[]> select1 = blogService.selectByNationDate("台灣",1);
// for( Object[] select11:select1) {
// System.out.println("select1 = "+(BlogBean)select11[0]);
// }
// System.out.println("bean1="+bean1);
// }
return select1;
}
//未使用-----------------------------------------------------------
@RequestMapping(path= {"/Blog/BlogIndexNONE.controller"})
public String forSubmitNONE(//String傳入使用
// BlogBean bean,BindingResult bindingResult,
String search,
String page,
String newhot,
Model model) {
// System.out.println("run controller1111");
// System.out.println("page = " + page);
// System.out.println("search = " + search);
// System.out.println("newhot = " + newhot);
List<Object[]> beanMain = blogService.selectByInput(search, page,6,newhot);
List<Object[]> beanAsideHot = blogService.selectByInput(null,"1",4,"hot");
List<Object[]> beanAsideNew = blogService.selectByInput(null,"1",4,"new");
// for(Object[] beanAsideHot1:beanAsideHot) {
// System.out.println((BlogBean)beanAsideHot1[0]);
// }
// for(Object[] beanAsideHot1:beanAsideHot) {
// System.out.println(((BlogBean)beanAsideHot1[0]).getBlogView());
// }
// for(Object[] beanAsideNew1:beanAsideNew) {
// System.out.println(((BlogBean)beanAsideNew1[0]).getBlogReleaseTime());
// }
// System.out.println("beanAsideHot = " + beanAsideHot);
// System.out.println("beanAsideNew = " + beanAsideNew);
model.addAttribute("result", beanMain);
model.addAttribute("result2", beanAsideHot);
model.addAttribute("result3", beanAsideNew);
model.addAttribute("search", search);
model.addAttribute("newhot", newhot);
if(beanMain==null) {
// System.out.println("!!!!");
return "errorPage1";
}
// if(!"".equals(search)&&page==null) {
// List<Object[]> bean1 = blogService.selectByNation(search,1);
// model.addAttribute("result", bean1);
// model.addAttribute("search", search);
// List<Object[]> bean3 = blogService.selectByNation("台灣",1);
// model.addAttribute("result3", bean3);
// List<Object[]> bean2 = blogService.selectByNationDate("台灣",1);
// model.addAttribute("result2", bean2);
// if(bean1==null) {
// System.out.println("!!!!");
// return "errorPage1";
// }
// System.out.println("?????");
// }
// else if("".equals(search)&&page!=null) {
// BlogBean bb=new BlogBean();
// List<Object[]> bean1 = blogService.selectByNation("台灣",Integer.valueOf(page));
// model.addAttribute("result", bean1);
// List<Object[]> bean2 = blogService.selectByNationDate("台灣",Integer.valueOf(page));
// model.addAttribute("result2", bean2);
// List<Object[]> bean3 = blogService.selectByNation("台灣",Integer.valueOf(page));
// model.addAttribute("result3", bean3);
// }
// else if(!"".equals(search)&&page!=null) {
//
// List<Object[]> bean1 = blogService.selectByNation(search,Integer.valueOf(page));
// model.addAttribute("result", bean1);
// model.addAttribute("search", search);
// List<Object[]> bean3 = blogService.selectByNation("台灣",Integer.valueOf(page));
// model.addAttribute("result3", bean3);
// List<Object[]> bean2 = blogService.selectByNationDate("台灣",Integer.valueOf(page));
// model.addAttribute("result2", bean2);
//
// }
// if("new".equals(newhot)) {
// List<Object[]> newbean = blogService.selectByNation("台灣",1);
// model.addAttribute("newPage", newbean);
// model.addAttribute("newhot", newhot);
// System.out.println("newhotEEEEEEEE = " + newhot);
// }
return "okPage1";
}
}
| true
|
f41db911974c265bcc6f8636115da31c806ab25b
|
Java
|
ghaseen/intervention
|
/src/main/java/org/sid/entities/Reclamation.java
|
UTF-8
| 3,142
| 2.109375
| 2
|
[] |
no_license
|
package org.sid.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
@SpringBootApplication
@Entity
@Table(name = "Reclamation")
public class Reclamation implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idR;
@NotBlank(message = "Ne doit pas etre vide")
private String Fixe;//chnya hetha
@NotBlank(message="Ne doit pas etre vide")
@Size (min=5, max=70,message="taille incorrect doit etre supérieur à 5")
private String addresse;
@Min(value = 0, message = "le valeur doit etre positive")
private int codeP;
@NotBlank(message="Ne doit pas etre vide")
private String typeR;
@NotBlank(message="Ne doit pas etre vide")
private String explication;
@ManyToOne
@JoinColumn(name = "client_id")
@JsonIgnore
private Client client;
@ManyToOne
@JoinColumn(name = "produit_id",referencedColumnName = "id")
@NotNull(message="veuillez selectionner un produit")
private Produit produit;
public Produit getProduit() {
return produit;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public Reclamation(Long idR, String fixe, String addresse, int codeP, String typeR,
String explication, Client client) {
super();
this.idR=idR;
this.Fixe = fixe;
this.addresse = addresse;
this.codeP = codeP;
this.typeR = typeR;
this.explication = explication;
this.client = client;
}
public Reclamation( String fixe, String addresse, int codeP, String typeR,
String explication ) {
super();
this.Fixe = fixe;
this.addresse = addresse;
this.codeP = codeP;
this.typeR = typeR;
this.explication = explication;
}
public Reclamation() {
super();
// TODO Auto-generated constructor stub
}
public Long getIdR() {
return idR;
}
public void setIdR(Long idR) {
this.idR = idR;
}
public String getFixe() {
return Fixe;
}
public void setFixe(String fixe) {
Fixe = fixe;
}
public String getAddresse() {
return addresse;
}
public void setAddresse(String addresse) {
this.addresse = addresse;
}
public int getCodeP() {
return codeP;
}
public void setCodeP(int codeP) {
this.codeP = codeP;
}
public String getTypeR() {
return typeR;
}
public void setTypeR(String typeR) {
this.typeR = typeR;
}
public String getExplication() {
return explication;
}
public void setExplication(String explication) {
this.explication = explication;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
}
| true
|
378eb599f7b8dae193a4cad848524168fd7d3161
|
Java
|
Kartm/university-dsaa
|
/src/dsaa/lab_10/Graph.java
|
UTF-8
| 5,069
| 3.453125
| 3
|
[] |
no_license
|
package dsaa.lab_10;
import java.util.*;
public class Graph {
private final int[][] adjacencyMatrix; // filled with zeroes by default
private final Document[] indexToDocument;
private final Map<String, Integer> linkToNode = new HashMap<>();
@SuppressWarnings("unchecked")
public Graph(SortedSet<Document> documents) {
int size = documents.size();
adjacencyMatrix = new int[size][size];
indexToDocument = new Document[size];
// setup the nodes
int nodeIndex = 0;
for(Document doc: documents) {
indexToDocument[nodeIndex] = doc;
linkToNode.put(doc.name, nodeIndex);
nodeIndex++;
}
// setup the edges
nodeIndex = 0;
for(Document doc: documents) {
// all the outgoing edges
for(Link link: doc.link.values()) {
if(linkToNode.containsKey(link.ref)) { // if target node exists
int targetIndex = linkToNode.get(link.ref);
adjacencyMatrix[nodeIndex][targetIndex] = link.weight;
}
}
nodeIndex++;
}
}
public String generateAdjacencyMatrix() {
StringBuilder result = new StringBuilder();
for(int i = 0; i < adjacencyMatrix.length; i++) {
for(int j = 0; j < adjacencyMatrix[i].length; j++) {
result.append(adjacencyMatrix[i][j] == 0 ? "O " : adjacencyMatrix[i][j] + " ");
}
result.append("\n");
}
return result.toString();
}
// todo in a case you have many way to go, analyze vertices in lexicographical order
public String bfs(String start) {
StringBuilder result = new StringBuilder();
if(!checkNode(start)) {
return null;
}
int startNode = linkToNode.get(start);
boolean[] visited = new boolean[adjacencyMatrix.length];
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(startNode);
while(!queue.isEmpty()) {
int currentNode = queue.poll();
if(!visited[currentNode]) {
result.append(indexToDocument[currentNode].name).append(", ");
visited[currentNode] = true;
// loop all adjacent nodes
for (int i = 0; i < adjacencyMatrix[currentNode].length; i++) {
if (adjacencyMatrix[currentNode][i] != 0 && !visited[i]) { // if connection exists and is unvisited
queue.add(i);
}
}
}
}
return result.toString().replaceAll(", $", "");
}
// in a case you have many way to go, analyze vertices in lexicographical order
public String dfs(String start) {
StringBuilder result = new StringBuilder();
boolean[] visited = new boolean[adjacencyMatrix.length];
Stack<Integer> stack = new Stack<>();
if(!checkNode(start)) {
return null;
}
int startNode = linkToNode.get(start);
stack.add(startNode);
while(!stack.isEmpty()) {
int currentNode = stack.pop();
if(!visited[currentNode]) {
visited[currentNode] = true;
result.append(indexToDocument[currentNode].name).append(", ");
// loop all adjacent nodes
for (int i = adjacencyMatrix[currentNode].length - 1; i >= 0; i--) {
if (adjacencyMatrix[currentNode][i] != 0 && !visited[i]) { // if connection exists and is unvisited
stack.add(linkToNode.get(indexToDocument[i].name));
}
}
}
}
return result.toString().replaceAll(", $", "");
}
public int connectedComponents() {
return countNumberOfDisjointSets();
}
public int countNumberOfDisjointSets() {
DisjointSetForest sets = new DisjointSetForest(adjacencyMatrix.length);
for(int nodeIndex = 0; nodeIndex < adjacencyMatrix.length; nodeIndex++) { // for each node u in V do
sets.makeSet(nodeIndex); // MakeSet(u)
}
for(int nodeIndex = 0; nodeIndex < adjacencyMatrix.length; nodeIndex++) { // for each node u in V do
for(int childIndex = 0; childIndex < adjacencyMatrix[nodeIndex].length; childIndex++) {
if(nodeIndex != childIndex && adjacencyMatrix[nodeIndex][childIndex] != 0) {
//System.out.println(nodeIndex + " => " + childIndex);
sets.union(nodeIndex, childIndex); // Union(u,v)
}
}
}
// count the representants
Set<Integer> representants = new HashSet<>();
for(int nodeIndex = 0; nodeIndex < adjacencyMatrix.length; nodeIndex++) {
representants.add(sets.findSet(nodeIndex));
}
return representants.size(); // todo
}
private boolean checkNode(String name) {
return linkToNode.containsKey(name);
}
}
| true
|
b089aef2b0e6a3ecd680d708cadafbf323f5b05b
|
Java
|
wychen/dom-distiller
|
/java/org/chromium/distiller/PageParameterDetector.java
|
UTF-8
| 21,144
| 2.375
| 2
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.distiller;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Background:
* The long article/news/forum thread/blog document may be partitioned into several partial pages
* by webmaster. Each partial page has outlinks pointing to the adjacent partial pages. The
* anchor text of those outlinks is numeric.
*
* Definitions:
* A paging document is one of the partial pages.
* "digital" means the text contains only digits.
* A page pattern is a paging URL whose page parameter value is replaced with a place holder
* (PAGE_PARAM_PLACEHOLDER).
* Example: if the original URL is "http://www.foo.com/a/b-3.html", the page pattern is
* "http://www.foo.com/a/b-[*!].html".
*
* This class extracts the page parameter from a document's outlinks.
* The basic idea:
* #1. Collect groups of adjacent plain text numbers and outlinks with digital anchor text.
* #2. For each group, determine the relationship between digital anchor texts and digital parts
* (either a query value or a path component) in URL. If one part of a URL is always a linear
* map from its digital anchor text, we guess the part is the page parameter of the URL.
*
* As an example, consider a document http://a/b?c=1&p=10, which contains the following digital
* outlinks:
* <a href=http://a/b?c=1&p=20>3</a>
* <a href=http://a/b?c=1&p=30>4</a>
* <a href=http://a/b?c=1&p=40>5</a>
* This class finds that the "p" parameter is always equal to "anchor text" * 10 - 10, and so
* guesses it is the page parameter. The associated page pattern is http://a/b?c=1&p=[*!].
*/
public class PageParameterDetector {
static final String PAGE_PARAM_PLACEHOLDER = "[*!]";
static final int PAGE_PARAM_PLACEHOLDER_LEN = PAGE_PARAM_PLACEHOLDER.length();
// The max number of paging documents for a document, beyond which the document is ignored and
// pagination detection is aborted.
// The original heuristic has this at 50, but it fails one of the URLs in the
// multi-page-golden-data.sstable dataset: http://m.worldstarhiphop.com/apple/index.php?pg=13,
// where there're always 100 pagination outlinks available regardless of which page you're
// looking at.
static final int MAX_PAGING_DOCS = 100;
/**
* The interface that page pattern handlers must implement to detect page parameter from
* potential pagination URLs.
*/
interface PagePattern {
/**
* Returns the string of the URL page pattern.
*/
String toString();
/**
* Returns the page number extracted from the URL during creation of object that implements
* this interface.
*/
int getPageNumber();
/**
* Validates this page pattern according to the current document URL through a pipeline of
* rules.
*
* Returns true if page pattern is valid.
*
* @param docUrl the current document URL
*/
boolean isValidFor(ParsedUrl docUrl);
/**
* Returns true if a URL matches this page pattern based on a pipeline of rules.
*
* @param url the URL to evaluate
*/
boolean isPagingUrl(String url);
}
/**
* Stores a map of URL pattern to its associated list of PageLinkInfo's.
*/
private static class PageCandidatesMap {
private static class Info {
private final PagePattern mPattern;
private final List<PageLinkInfo> mLinks;
Info(PagePattern pattern, PageLinkInfo link) {
mPattern = pattern;
mLinks = new ArrayList<PageLinkInfo>();
mLinks.add(link);
}
}
private final Map<String, Info> map = new HashMap<String, Info>();
/**
* Adds urlPattern with its PageLinkInfo into the map. If the urlPattern already exists,
* adds the link to the list of LinkInfo's. Otherwise, creates a new map entry.
*/
private void add(PagePattern pattern, PageLinkInfo link) {
final String patternStr = pattern.toString();
if (map.containsKey(patternStr)) {
map.get(patternStr).mLinks.add(link);
} else {
map.put(patternStr, new Info(pattern, link));
}
}
}
/**
* Keeps track of the detection state:
* - best PageParamInfo detected so far
* - if multiple page patterns have been found.
*/
private static class DetectionState {
PageParamInfo mBestPageParamInfo = null;
boolean mMultiPagePatterns = false;
DetectionState() {
}
DetectionState(PageParamInfo pageParamInfo) {
mBestPageParamInfo = pageParamInfo;
}
boolean isEmpty() {
return mBestPageParamInfo == null;
}
boolean hasMultiPagePatterns() {
return mMultiPagePatterns;
}
void update(DetectionState state) {
mBestPageParamInfo = state.mBestPageParamInfo;
mMultiPagePatterns = state.mMultiPagePatterns;
}
void compareAndUpdate(DetectionState state) {
if (isEmpty()) {
update(state);
return;
}
// Compare both PageParamInfo's.
int ret = mBestPageParamInfo.compareTo(state.mBestPageParamInfo);
if (ret == -1) { // The formal one is better.
update(state);
} else if (ret == 0) { // Can't decide which one is better.
mMultiPagePatterns = true;
}
}
}
// All the known bad page param names.
private static Set<String> sBadPageParamNames = null;
/**
* Entry point for PageParameterDetector.
* Creates a PageParamInfo based on outlinks and numeric text around them.
*
* @return PageParamInfo (see PageParamInfo.java), always. If no page parameter is detected or
* determined to be best, its mType is PageParamInfo.Type.UNSET.
*
* @param adjacentNumbersGroups all numeric content parsed from the document, grouped by their
* adjacency and monotonicity (see MonotonicPageInfosGroups)
* @param docUrl the current document URL that was parsed
*/
public static PageParamInfo detect(MonotonicPageInfosGroups adjacentNumbersGroups,
String docUrl) {
ParsedUrl parsedDocUrl = ParsedUrl.create(docUrl);
if (parsedDocUrl == null) return new PageParamInfo(); // Invalid document URL.
parsedDocUrl.setUsername("");
parsedDocUrl.setPassword("");
DetectionState detectionState = new DetectionState();
for (MonotonicPageInfosGroups.Group group : adjacentNumbersGroups.getGroups()) {
if (group.mList.size() < 2) continue;
DetectionState state = detectPageParamForMonotonicNumbers(group.mList,
group.mDeltaSign < 0, parsedDocUrl,
detectionState.isEmpty() ? "" : detectionState.mBestPageParamInfo.mPagePattern);
if (state != null) detectionState.compareAndUpdate(state);
} // for all adjacentNumbersGroups.
if (detectionState.isEmpty()) return new PageParamInfo();
// For now, if there're multiple page patterns, we take the first one.
// If this doesn't work for most sites, we might have to return nothing.
if (detectionState.hasMultiPagePatterns() &&
LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) {
LogUtil.logToConsole("Detected multiple page patterns");
}
final PageParamInfo bestPageParamInfo = detectionState.mBestPageParamInfo;
bestPageParamInfo.determineNextPagingUrl(docUrl);
return bestPageParamInfo;
}
/**
* Detects the page parameter info for the given list of monotonic numbers.
*
* @return a populated detection state with the best PageParamInfo detected so far, null if none
* is detected.
*
* @param monotonicNumbers list of numeric values which are either ascending or descending;
* a descending list will be reversed and list elements could be mutated here.
* @param isDescending true for a descending monotonicNumbers
* @param parsedDocUrl ParsedUrl of the current document URL that was parsed
* @param acceptedPagePattern the best accepted URL pattern if available so far, which contains
* a PAGE_PARAM_PLACEHOLDER to replace the page parameter, and yields the best PageParamInfo.
*/
private static DetectionState detectPageParamForMonotonicNumbers(
List<PageParamInfo.PageInfo> monotonicNumbers, boolean isDescending,
ParsedUrl parsedDocUrl, String acceptedPagePattern) {
// Count number of outlinks.
int outlinks = 0;
for (PageParamInfo.PageInfo pageInfo : monotonicNumbers) {
if (!pageInfo.mUrl.isEmpty()) outlinks++;
}
if (outlinks == 0) return null;
if (isDescending) Collections.reverse(monotonicNumbers);
// Some documents only have two partial pages, where each has a digital outlink to the
// other. But we need at least 2 URLs to extract page parameters. To handle this case, use
// current doc URL as the URL for the original plain text number.
// Note we only do this when the known digital link's page number is 1 or 2.
if (monotonicNumbers.size() == 2 && outlinks == 1 &&
monotonicNumbers.get(0).mPageNum == 1 && monotonicNumbers.get(1).mPageNum == 2) {
if (monotonicNumbers.get(0).mUrl.isEmpty()) {
monotonicNumbers.set(0, new PageParamInfo.PageInfo(1, parsedDocUrl.toString()));
} else {
monotonicNumbers.set(1, new PageParamInfo.PageInfo(2, parsedDocUrl.toString()));
}
outlinks++; // Increment to include current document URL.
}
// Now, extract the the page parameter.
if (outlinks >= 2) {
return extractPageParam(monotonicNumbers, parsedDocUrl, acceptedPagePattern);
}
return null;
}
/**
* Extracts page parameter from given list of ascending PageParamInfo.PageInfo's.
* From each PageInfo.mURL, detects the page parameter, and formulates the URL pattern which
* contains a PAGE_PARAM_PLACEHOLDER to replace the page parameter.
* For each URL pattern, validates it, compares the detected PageParamInfo with previously
* detected one, and updates the better one in mPageParamInfo.
*
* @return a populated detection state with the best PageParamInfo detected among all page
* patterns, null if none is detected.
*
* @param ascendingNumbers list of PageParamInfo.PageInfo's with ascending mPageNum's.
* @param parsedDocUrl ParsedUrl of the current document URL that was parsed
* @param acceptedPagePattern the best accepted URL pattern if available so far
*/
private static DetectionState extractPageParam(List<PageParamInfo.PageInfo> ascendingNumbers,
ParsedUrl parsedDocUrl, String acceptedPagePattern) {
// Eliminate calendar date links.
if (areCalendarDates(ascendingNumbers)) return null;
String firstPageUrl = "";
PageCandidatesMap pageCandidates = new PageCandidatesMap();
// An array of ParsedUrl objects for URLs in ascendingNumbers' PageInfo's.
ParsedUrl[] parsedUrls = new ParsedUrl[ascendingNumbers.size()];
// First, try query components of URLs, looking out for first page URL.
for (int i = 0; i < ascendingNumbers.size(); i++) {
final PageParamInfo.PageInfo page = ascendingNumbers.get(i);
if (!page.mUrl.isEmpty()) {
ParsedUrl url = ParsedUrl.create(page.mUrl);
parsedUrls[i] = url;
if (url == null) continue;
url.setUsername("");
url.setPassword("");
extractPageParamCandidatesFromQuery(url, page.mPageNum, i, pageCandidates);
if (page.mPageNum == 1) firstPageUrl = page.mUrl;
}
}
// If query components yield nothing, try paths of URLs.
if (pageCandidates.map.isEmpty()) {
for (int i = 0; i < ascendingNumbers.size(); i++) {
final PageParamInfo.PageInfo page = ascendingNumbers.get(i);
if (parsedUrls[i] != null) {
extractPageParamCandidatesFromPath(parsedUrls[i], page.mPageNum, i,
pageCandidates);
}
}
}
// Determine which URL page pattern is valid with a valid, and the best, PageParamInfo.
DetectionState state = new DetectionState();
for (Map.Entry<String, PageCandidatesMap.Info> entry : pageCandidates.map.entrySet()) {
final String patternStr = entry.getKey();
final PageCandidatesMap.Info info = entry.getValue();
if (patternStr.equals(acceptedPagePattern) || info.mLinks.size() > MAX_PAGING_DOCS ||
!info.mPattern.isValidFor(parsedDocUrl)) {
continue;
}
PageParamInfo pageParamInfo = PageParamInfo.evaluate(info.mPattern, info.mLinks,
ascendingNumbers, firstPageUrl);
if (pageParamInfo == null) continue;
// If feasible, insert current document URL as first page.
// Otherwise, we enhance the heuristic: if current document URL fits the paging pattern
// of the potential pagination URLs, consider it as first page too.
final String docUrl = parsedDocUrl.getCleanHref();
if (pageParamInfo.canInsertFirstPage(docUrl, ascendingNumbers)) {
pageParamInfo.insertFirstPage(docUrl);
} else if (info.mPattern.isPagingUrl(docUrl)) {
final PageParamInfo.PageInfo firstPage = pageParamInfo.mAllPageInfo.get(0);
if (firstPage.mPageNum == 2 && !firstPage.mUrl.equals(docUrl) &&
docUrl.length() < firstPage.mUrl.length()) {
pageParamInfo.insertFirstPage(docUrl);
}
}
state.compareAndUpdate(new DetectionState(pageParamInfo));
} // for each URL pattern in pageCandidates.
return state.isEmpty() ? null : state;
}
/**
* Returns true if given list of page numbers are calendar dates.
*/
private static boolean areCalendarDates(List<PageParamInfo.PageInfo> ascendingNumbers) {
int possibleDateNum = 0; // Match consecutive increasing numbers starting from 1.
for (PageParamInfo.PageInfo page : ascendingNumbers) {
if (page.mPageNum == possibleDateNum + 1) possibleDateNum++;
}
return possibleDateNum >= 28 && possibleDateNum <= 31;
}
/**
* Extracts page parameter candidates from the query part of given URL and adds the associated
* links into pageCandidates which is keyed by page pattern.
*
* A page parameter candidate is one where:
* - the name of a query name-value component is not one of sBadPageParamNames, and
* - the value of the query component is a plain number (>= 0).
* E.g. a URL query with 3 plain number query values will generate 3 URL page patterns with 3
* PageLinkInfo's, and hence 3 page parameter candidates.
*
* @param url ParsedUrl of the URL to process
* @param pageNum the page number as represented in original plain text
* @param posInAscendingNumbers position of this page number in the list of ascending numbers
* @param pageCandidates the map of URL pattern to its associated list of PageLinkInfo's
*/
private static void extractPageParamCandidatesFromQuery(ParsedUrl url, int pageNum,
int posInAscendingNumbers, PageCandidatesMap pageCandidates) {
String[][] queryParams = url.getQueryParams();
if (queryParams.length == 0) return; // No query.
for (int i = 0; i < queryParams.length; i++) {
String[] nameValue = queryParams[i];
PagePattern pattern = QueryParamPagePattern.create(url, i == 0, nameValue[0],
nameValue[1]);
if (pattern != null) {
pageCandidates.add(pattern,
new PageLinkInfo(pageNum, pattern.getPageNumber(), posInAscendingNumbers));
}
}
}
private static RegExp sDigitsRegExp = null; // Match at least 1 digit.
/**
* Extracts page parameter candidates from the path part of given URL (without query components)
* and adds the associated links into pageCandidates which is keyed by page pattern.
*
* A page parameter candidate is one where a path component contains consecutive digits which
* can be converted to a plain number (>= 0).
* E.g. a URL path with 3 path components that contain plain numbers will generate 3 URL page
* patterns with 3 PageLinkInfo's, and hence 3 page parameter candidates.
*
* @param url ParsedUrl of the URL to process
* @param pageNum the page number as represented in original plain text
* @param posInAscendingNumbers position of this page number in the list of ascending numbers
* @param pageCandidates the map of URL pattern to its associated list of PageLinkInfo's
*/
private static void extractPageParamCandidatesFromPath(ParsedUrl url, int pageNum,
int posInAscendingNumbers, PageCandidatesMap pageCandidates) {
String path = url.getTrimmedPath();
if (path.isEmpty() || !StringUtil.containsDigit(path)) return;
// Extract digits (either one or consecutive) from path, replace the digit(s) with
// PAGE_PARAM_PLACEHOLDER to formulate the page pattern, add it as page candidate.
final String urlStr = url.toString();
final int pathStart = url.getOrigin().length();
if (sDigitsRegExp == null) sDigitsRegExp = RegExp.compile("(\\d+)", "gi");
sDigitsRegExp.setLastIndex(pathStart);
while (true) {
MatchResult match = sDigitsRegExp.exec(urlStr);
if (match == null) break;
final int matchEnd = sDigitsRegExp.getLastIndex();
final int matchStart = matchEnd - match.getGroup(1).length();
PagePattern pattern = PathComponentPagePattern.create(url, pathStart, matchStart,
matchEnd);
if (pattern != null) {
pageCandidates.add(pattern,
new PageLinkInfo(pageNum, pattern.getPageNumber(), posInAscendingNumbers));
}
} // while there're matches
}
/**
* Returns true if given name is blacklisted as a known bad page param name.
*/
static boolean isPageParamNameBad(String name) {
initBadPageParamNames();
return sBadPageParamNames.contains(name.toLowerCase());
}
/**
* Returns true if given string can be converted to a number >= 0.
*/
static boolean isPlainNumber(String str) {
return StringUtil.toNumber(str) >= 0;
}
/**
* If sBadPageParamNames is null, initialize it with all the known bad page param names, in
* alphabetical order.
*/
private static void initBadPageParamNames() {
if (sBadPageParamNames != null) return;
sBadPageParamNames = new HashSet<String>();
sBadPageParamNames.add("baixar-gratis");
sBadPageParamNames.add("category");
sBadPageParamNames.add("content");
sBadPageParamNames.add("day");
sBadPageParamNames.add("date");
sBadPageParamNames.add("definition");
sBadPageParamNames.add("etiket");
sBadPageParamNames.add("film-seyret");
sBadPageParamNames.add("key");
sBadPageParamNames.add("keys");
sBadPageParamNames.add("keyword");
sBadPageParamNames.add("label");
sBadPageParamNames.add("news");
sBadPageParamNames.add("q");
sBadPageParamNames.add("query");
sBadPageParamNames.add("rating");
sBadPageParamNames.add("s");
sBadPageParamNames.add("search");
sBadPageParamNames.add("seasons");
sBadPageParamNames.add("search_keyword");
sBadPageParamNames.add("search_query");
sBadPageParamNames.add("sortby");
sBadPageParamNames.add("subscriptions");
sBadPageParamNames.add("tag");
sBadPageParamNames.add("tags");
sBadPageParamNames.add("video");
sBadPageParamNames.add("videos");
sBadPageParamNames.add("w");
sBadPageParamNames.add("wiki");
}
}
| true
|