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
a6bbf638822bfe8712b1e09db0732ea9a16368c0
Java
J0703-SSM/Netctoss_SSM_SGX
/src/main/java/com/lanou/base/mapper/ModuleMapper.java
UTF-8
210
1.625
2
[]
no_license
package com.lanou.base.mapper; import com.lanou.role.domain.Module; import java.util.List; /** * Created by dllo on 17/11/17. */ public interface ModuleMapper { List<Module> findModuleByRoleId(); }
true
bb1f842708db8834b417a98511d94ebc2c4eedfd
Java
yuervsxiami/pmes
/src/main/java/com/cnuip/pmes2/domain/el/User.java
UTF-8
5,753
2.265625
2
[]
no_license
package com.cnuip.pmes2.domain.el; import com.cnuip.pmes2.domain.BaseModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; /** * Created by IntelliJ IDEA. * User:zhaozhihui * Date: 2018/10/16. * Time: 9:53 */ @Data public class User extends BaseModel { @ApiModelProperty( value = "ID系统自动生成", name = "id", dataType = "Long" ) private Long id; @ApiModelProperty( value = "组织ID", name = "organizationId", dataType = "Long" ) private Long organizationId; @ApiModelProperty( value = "组织", name = "organizationName", dataType = "String" ) private String organizationName; @ApiModelProperty( value = "用户名", name = "username", dataType = "String", example = "admin" ) private String username; @ApiModelProperty( value = "密码", name = "password", dataType = "String", example = "123456" ) private String password; @ApiModelProperty( value = "姓名", name = "realName", dataType = "String", example = "张三" ) private String realName; @ApiModelProperty( value = "昵称", name = "nickName", dataType = "String", example = "zhangdan" ) private String nickName; @ApiModelProperty( value = "手机号", name = "phone", dataType = "String", example = "18000000000" ) private String phone; @ApiModelProperty( value = "性别", name = "sex", dataType = "String", example = "男" ) private String sex; @ApiModelProperty( value = "民族", name = "nation", dataType = "String", example = "汉族" ) private String nation; @ApiModelProperty( value = "籍贯", name = "nativePlace", dataType = "String", example = "江苏南京" ) private String nativePlace; @ApiModelProperty( value = "身份证号", name = "idCardNo", dataType = "String" ) private String idCardNo; @ApiModelProperty( value = "出生日期", name = "birthday", dataType = "java.util.Date" ) private Date birthday; @ApiModelProperty( value = "绑定微信号", name = "wchat", dataType = "String" ) private String wchat; @ApiModelProperty( value = "证件照", name = "imageUrl", dataType = "String", example = "http://xxx.com/xxx.png" ) private String imageUrl; @ApiModelProperty( value = "职称与头衔", name = "title", dataType = "String", example = "教授" ) private String title; @ApiModelProperty( value = "部门ID", name = "departmentId", dataType = "Long" ) private Long departmentId; @ApiModelProperty( value = "部门名称", name = "departmentName", dataType = "String" ) private String departmentName; @ApiModelProperty( value = "岗位ID", name = "postId", dataType = "Long" ) private Long postId; @ApiModelProperty( value = "岗位名称", name = "postName", dataType = "String" ) private String postName; @ApiModelProperty( value = "职权ID", name = "powersId", dataType = "Long" ) private Long powersId; @ApiModelProperty( value = "职权名称", name = "powersName", dataType = "String" ) private String powersName; @ApiModelProperty( value = "科研方向", name = "direction", dataType = "String", example = "航天航空,飞机发动机,火星探测器" ) private String direction; @ApiModelProperty( value = "简介", name = "introduction", dataType = "String", example = "又名南京大学医学院附属鼓楼医院" ) private String introduction; @ApiModelProperty( value = "荣誉", name = "honor", dataType = "String" ) private String honor; @ApiModelProperty( value = "是否删除 [ YES.是 NO.否 ]", name = "isDelete", dataType = "String", example = "NO" ) private String isDelete; @ApiModelProperty( value = "操作人ID", name = "editorId", dataType = "Long" ) private Long editorId; @ApiModelProperty( value = "操作人", name = "editorName", dataType = "String", example = "admin" ) private String editorName; @ApiModelProperty( value = "创建日期", name = "createdTime", dataType = "java.util.Date" ) private Date createdTime; @ApiModelProperty( value = "更新日期", name = "updatedTime", dataType = "java.util.Date" ) private Date updatedTime; }
true
080bcd65d196ecfe0339628c7420f2b155137b1a
Java
yifanzhu1592/Trinity-Introduction-to-Programming
/All programs/Assignment problems/week 6 HiLoGame.java
UTF-8
2,639
3.5
4
[]
no_license
import java.util.NoSuchElementException; import java.util.Random; import java.util.Scanner; import javax.swing.JOptionPane; public class HiLoGame { public static void main(String[] args) { try { final int CARD_NUMBERS = 13; final int REQUIREMENT = 4; final int JACK = 11; final int QUEEN = 12; final int KING = 13; final int ACE = 14; final int LOWEST_NUMBER = 2; final int HIGHEST_NUMBER = 9; final int FIRST_TIME = 0; String guess = ""; String input = ""; Scanner inputScanner = new Scanner(input); Random rand = new Random(); int successfulTimes = 0; int guessTimes = 0; int lastCard = 0; boolean lose = false; boolean valid = true; do { int card = rand.nextInt(CARD_NUMBERS) + LOWEST_NUMBER; if (card >= LOWEST_NUMBER && card <= HIGHEST_NUMBER) { JOptionPane.showMessageDialog(null, "The card is a "+ card + "."); } else if (card == ACE){ JOptionPane.showMessageDialog(null, "The card is a Ace."); } else if (card == JACK){ JOptionPane.showMessageDialog(null, "The card is a Jack."); } else if (card == QUEEN){ JOptionPane.showMessageDialog(null, "The card is a Queen."); } else if (card == KING){ JOptionPane.showMessageDialog(null, "The card is a King."); } if (guessTimes != FIRST_TIME) { if ((guess.equals("higher") && (card > lastCard)) || (guess.equals("lower") && (card < lastCard)) || (guess.equals("equal") && (card == lastCard))) { successfulTimes++; } else { lose = true; } } if (!lose && (successfulTimes < REQUIREMENT)) { lastCard = card; input = JOptionPane.showInputDialog("Do you think the next card will be higher, lower or equal? "); inputScanner = new Scanner(input); guess = inputScanner.next(); if (!guess.equals("higher") && !guess.equals("lower") && !guess.equals("equal")) { valid = false; lose = true; } guessTimes++; } inputScanner.close(); } while (successfulTimes < REQUIREMENT && !lose); if (successfulTimes == REQUIREMENT) { JOptionPane.showMessageDialog(null, "Congratulations. You got them all correct."); } else if (valid) { JOptionPane.showMessageDialog(null, "Try it next time."); } else { JOptionPane.showMessageDialog(null, "Invalid input. Good Bye."); } } catch (NoSuchElementException exception) { JOptionPane.showMessageDialog(null, "Invalid input. Good Bye."); } catch (NullPointerException exception) { JOptionPane.showMessageDialog(null, "You exit the game"); } } }
true
877f53344465bcf1ecee6b38d68f54b7ad6498fb
Java
biaderbia/algorithm011-class01
/Week_02/ValidAnagram.java
UTF-8
857
3.421875
3
[]
no_license
import java.util.Arrays; public class ValidAnagram{ public static void main(String[] args) { Solution solution = new ValidAnagram().new Solution(); String s = "anagram"; String t = "nagaram"; boolean result = solution.isAnagram(s, t); System.out.println(result); } class Solution { public boolean isAnagram(String s, String t) { if (s == null || t == null || s.length() != t.length()) { return false; } char[] sArr = s.toCharArray(); char[] tArr = t.toCharArray(); Arrays.sort(sArr); Arrays.sort(tArr); for (int i = 0; i < sArr.length; i++) { if (sArr[i] != tArr[i]) { return false; } } return true; } } }
true
f6e6da9f0356e9b9c7678e129d63b823477d1fbf
Java
KarmaANDfenrisulfr/Android_videoPlayer
/video_test/src/main/java/com/example/video_test/SearchListInfo.java
UTF-8
414
1.921875
2
[]
no_license
package com.example.video_test; public class SearchListInfo { String searchHistory; public SearchListInfo(){ } public SearchListInfo(String searchHistory) { this.searchHistory = searchHistory; } public String getSearchHistory() { return searchHistory; } public void setSearchHistory(String searchHistory) { this.searchHistory = searchHistory; } }
true
9ef18ecb725ab2bd6097885a351304aae62a19c6
Java
pkt1583/untitled1-proj
/proj-util/src/main/java/com/pkt/assign/domain/PaymentMethod.java
UTF-8
136
1.648438
2
[]
no_license
package com.pkt.assign.domain; /** * Created by pankaj on 25-11-2014. */ public enum PaymentMethod { CHEQUE, DIRECTDEBIT, CASH }
true
924f9b282ebffbb687a76a2eb81108d1c9d0d5fc
Java
Safiet/WeAllAreReallyTired
/src/HomewWork03312021/Task2/Visa.java
UTF-8
149
2.203125
2
[]
no_license
package HomewWork03312021.Task2; public class Visa extends CreditCard { double calculateInteres() { return balance * interest; } }
true
e380f005740bd608df4842e648a0d357ccc470d3
Java
iamtalhaasghar/deitel-java-how-to-program
/chp2/Q31.java
UTF-8
805
3.171875
3
[]
no_license
package Chapter2; public class Q31{ public static void main(String []args){ System.out.printf("%-15s %-15s %-15s %n", "Number", "Square", "Cube"); System.out.printf("%-15d %-15d %-15d %n", 1, 1*1, 1*1*1 ); System.out.printf("%-15d %-15d %-15d %n", 2, 2*2, 2*2*2 ); System.out.printf("%-15d %-15d %-15d %n", 3, 3*3, 3*3*3 ); System.out.printf("%-15d %-15d %-15d %n", 4, 4*4, 4*4*4 ); System.out.printf("%-15d %-15d %-15d %n", 5, 5*5, 5*5*5 ); System.out.printf("%-15d %-15d %-15d %n", 6, 6*6, 6*6*6 ); System.out.printf("%-15d %-15d %-15d %n", 7, 7*7, 7*7*7 ); System.out.printf("%-15d %-15d %-15d %n", 8, 8*8, 8*8*8 ); System.out.printf("%-15d %-15d %-15d %n", 9, 9*9, 9*9*9 ); System.out.printf("%-15d %-15d %-15d %n", 10, 10*10, 10*10*10 ); } }
true
eab51f3f1721e0454c173b0633cabeb4430c1dfe
Java
kldev/trader-dw-api
/src/main/java/com/kldev/dw/controller/model/CreateBookRequest.java
UTF-8
765
2.09375
2
[]
no_license
package com.kldev.dw.controller.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class CreateBookRequest { @JsonProperty private String id; @JsonProperty private String traderId; @JsonProperty private String author; @JsonProperty private String title; @JsonProperty private double price; public String getId() { return id; } public String getTraderId() { return traderId; } public String getAuthor() { return author; } public double getPrice() { return price; } public String getTitle() { return title; } }
true
2b0a30fbe527c4ca7e9534912d1e465ada9e53c1
Java
ksAvinash/6AM
/app/src/main/java/com/sixamdev/jci/a6am/firebase/MyFirebaseInstanceIDService.java
UTF-8
2,659
2.328125
2
[]
no_license
package com.sixamdev.jci.a6am.firebase; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by avinashk on 05/11/17. */ public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { public SharedPreferences sharedPreferences; public static String signInPreferences = "6am_users"; @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d("FIREBASE", "onTokenRefresh: "+refreshedToken); // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. // sendRegistrationToServer(refreshedToken); } public void sendRegistrationToServer(Context context,String token) { // TODO: Implement this method to send token to your app server. sharedPreferences = context.getSharedPreferences(signInPreferences, MODE_PRIVATE); String email = sharedPreferences.getString("email", null); if(email != null){ try{ URL url = new URL("https://zra7dwvb6b.execute-api.ap-south-1.amazonaws.com/prod/update-fb-instance-id"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("email", email); jsonParam.put("fb_instance_id",token); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(jsonParam.toString()); os.flush(); BufferedReader serverAnswer = new BufferedReader(new InputStreamReader(conn.getInputStream())); Log.d("FIREBASE : ", "updateToken : "+serverAnswer.readLine()); //response from server os.close(); conn.disconnect(); }catch (Exception e){ } } } }
true
379c43d49c7d35ac46a0c4837b04bc5ca77d03eb
Java
emilien23/LoginTemplate
/app/src/main/java/com/emilien23/logintemplate/di/module/ExceptionHandlerModule.java
UTF-8
694
2.09375
2
[]
no_license
package com.emilien23.logintemplate.di.module; import com.emilien23.logintemplate.di.annotation.AppServiceScope; import com.emilien23.logintemplate.utils.exception.ExceptionHandler; import com.emilien23.logintemplate.utils.exception.HttpExceptionHandler; import dagger.Module; import dagger.Provides; @Module public class ExceptionHandlerModule { private final HttpExceptionHandler.HttpExceptionCallback callback; public ExceptionHandlerModule(HttpExceptionHandler.HttpExceptionCallback callback){ this.callback = callback; } @Provides @AppServiceScope public ExceptionHandler exceptionHandler(){ return new HttpExceptionHandler(callback); } }
true
4fa103a5541a978630163942ca8077325b60f51b
Java
cinnndy9/liferay-ide
/tools/plugins/com.liferay.ide.project.ui/src/com/liferay/ide/project/ui/LiferayPluginProjectDecorator.java
UTF-8
5,400
1.539063
2
[]
no_license
/******************************************************************************* * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * 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. * *******************************************************************************/ package com.liferay.ide.project.ui; import java.net.URL; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework; /** * @author Greg Amerson */ public class LiferayPluginProjectDecorator extends LabelProvider implements ILightweightLabelDecorator { private static ImageDescriptor EXT; private static final String EXT_FACET = "liferay.ext"; //$NON-NLS-1$ private static ImageDescriptor HOOK; private static final String HOOK_FACET = "liferay.hook"; //$NON-NLS-1$ private static final String ICON_DIR = "icons/ovr"; //$NON-NLS-1$ private static ImageDescriptor LAYOUTTPL; private static final String LAYOUTTPL_FACET = "liferay.layouttpl"; //$NON-NLS-1$ private static ImageDescriptor PORTLET; /* The constants are duplicated here to avoid plugin loading. */ private static final String PORTLET_FACET = "liferay.portlet"; //$NON-NLS-1$ private static ImageDescriptor THEME; private static final String THEME_FACET = "liferay.theme"; //$NON-NLS-1$ private static ImageDescriptor getExt() { if( EXT == null ) { EXT = getImageDescriptor( "liferay_ovr" ); //$NON-NLS-1$ } return EXT; } private static ImageDescriptor getHook() { if( HOOK == null ) { HOOK = getImageDescriptor( "liferay_ovr" ); //$NON-NLS-1$ } return HOOK; } /** * This gets a .gif from the icons folder. */ private static ImageDescriptor getImageDescriptor( String key ) { ImageDescriptor imageDescriptor = null; if( key != null ) { String gif = "/" + key + ".png"; //$NON-NLS-1$ //$NON-NLS-2$ IPath path = new Path( ICON_DIR ).append( gif ); URL gifImageURL = FileLocator.find( Platform.getBundle( ProjectUIPlugin.PLUGIN_ID ), path, null ); if( gifImageURL != null ) { imageDescriptor = ImageDescriptor.createFromURL( gifImageURL ); } } return imageDescriptor; } private static ImageDescriptor getLayoutTpl() { if( LAYOUTTPL == null ) { LAYOUTTPL = getImageDescriptor( "liferay_ovr" ); //$NON-NLS-1$ } return LAYOUTTPL; } private static ImageDescriptor getPortlet() { if( PORTLET == null ) { PORTLET = getImageDescriptor( "liferay_ovr" ); //$NON-NLS-1$ } return PORTLET; } private static ImageDescriptor getTheme() { if( THEME == null ) { THEME = getImageDescriptor( "liferay_ovr" ); //$NON-NLS-1$ } return THEME; } public void decorate( Object element, IDecoration decoration ) { if( element instanceof IProject ) { IProject project = (IProject) element; ImageDescriptor overlay = null; if( hasFacet( project, PORTLET_FACET ) ) { overlay = getPortlet(); } else if( hasFacet( project, HOOK_FACET ) ) { overlay = getHook(); } else if( hasFacet( project, EXT_FACET ) ) { overlay = getExt(); } else if( hasFacet( project, LAYOUTTPL_FACET ) ) { overlay = getLayoutTpl(); } else if( hasFacet( project, THEME_FACET ) ) { overlay = getTheme(); } if( overlay != null ) { // next two lines dangerous! // DecorationContext ctx = (DecorationContext) decoration.getDecorationContext(); // ctx.putProperty( IDecoration.ENABLE_REPLACE, true ); decoration.addOverlay( overlay ); } } } private boolean hasFacet( IProject project, String facet ) { try { return FacetedProjectFramework.hasProjectFacet( project, facet ); } catch( CoreException e ) { ProjectUIPlugin.logError( e ); return false; } } }
true
0e725cc9714c3e9c9909b64fa6423e4febe50ad2
Java
SMATHUR93/coreExperiments
/src/com/shrek/thread/application/trignometery/CosineCalculator.java
UTF-8
467
3.078125
3
[]
no_license
package com.shrek.thread.application.trignometery; public class CosineCalculator implements Runnable { double value; Thread t; double sol; CosineCalculator(double value){ this.value=value; t = new Thread(this,"cosine"); t.start(); } public void run(){ try{ sol = Math.cos(Math.toRadians(value)); //System.out.println("cos sol is "+sol); Thread.sleep(1000); } catch(Exception e){ e.printStackTrace(); } } }
true
94b72da290054fb26d4972e3679a792d302d97a1
Java
KeithDeRuiter/PongLine
/src/pongline/network/messages/Message.java
UTF-8
419
1.671875
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 pongline.network.messages; import java.io.Serializable; import pongline.network.MessageType; /** * * @author Yeaman */ public interface Message extends Serializable { public MessageType getType(); }
true
945f7dab97cf00ee44b4e379d716ddb510de2c9b
Java
ironya/stepcounter
/eclipse-plugin/jp.sf.amateras.stepcounter/src/jp/sf/amateras/stepcounter/preferences/PreferenceInitializer.java
UTF-8
982
1.992188
2
[ "Apache-2.0" ]
permissive
package jp.sf.amateras.stepcounter.preferences; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import jp.sf.amateras.stepcounter.StepCounterPlugin; /** * Class used to initialize default preference values. */ public class PreferenceInitializer extends AbstractPreferenceInitializer { /* * (non-Javadoc) * * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ public void initializeDefaultPreferences() { IPreferenceStore store = StepCounterPlugin.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.P_SHOW_DIRECTORY, false); store.setDefault(PreferenceConstants.P_IGNORE_GENERATED_FILE, false); store.setDefault(PreferenceConstants.P_EXTENSION_PAIRS, ""); store.setDefault(PreferenceConstants.P_IGNORE_FILENAME_PATTERNS, false); store.setDefault(PreferenceConstants.P_FILENAME_PATTERNS, ""); } }
true
a98d0ad9af330d852e8f5a45465dc0bbff1ed059
Java
Redmancometh/Bloom
/Bloom/src/com/redmancometh/bloom/flowers/FlowerContainer.java
UTF-8
2,447
2.15625
2
[]
no_license
package com.redmancometh.bloom.flowers; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.JarFile; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; import com.redmancometh.bloom.configuration.FlowerConfigManager; /** * * @author Redmancometh * */ @Component public class FlowerContainer { private Map<String, Flower> loadedFlowers = new ConcurrentHashMap(); private Map<String, AnnotationConfigApplicationContext> contextMap = new ConcurrentHashMap(); @Autowired private FlowerConfigManager plugConfmon; @PostConstruct public void loadFlowers() throws IOException { Path flowerPath = Paths.get("flowers"); if (!Files.exists(flowerPath)) Files.createDirectory(flowerPath); List<URL> plugins = new ArrayList(); Files.walk(flowerPath).filter((path) -> path.toString().endsWith(".jar")).forEach((jar) -> { try { plugins.add(jar.toUri().toURL()); try (URLClassLoader loader = new URLClassLoader(plugins.toArray(new URL[plugins.size()]))) { JarFile jarContainer = new JarFile(jar.toFile()); FlowerConfiguration config = plugConfmon.load(jarContainer); Class<?> loadedClass = loader.loadClass(config.getFlowerClass()); Flower fl = (Flower) loadedClass.getConstructor(FlowerConfiguration.class).newInstance(config); AnnotationConfigApplicationContext pluginContext = fl.getPluginContext(loader); fl.setPluginContext(pluginContext); contextMap.put(fl.getFlowerConfig().getFlowerName(), pluginContext); loadedFlowers.put(fl.getFlowerConfig().getFlowerName(), fl); fl.enable(); } } catch (ClassNotFoundException | IOException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } }); } public void loadFlower(Flower flower) { } public void unloadFlower(Flower flower) { } }
true
f04a2d576e2ddc9a786f3c2186addfcb668882f4
Java
DesarrolloWebIcesi/ActivityToPeopleUpdater
/src/co/edu/icesi/activitytopeopleupdater/peoplenet/model/M4ccbCvActInves.java
UTF-8
14,083
1.695313
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package co.edu.icesi.activitytopeopleupdater.peoplenet.model; import java.io.Serializable; import java.util.Date; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; /** * * @author 38555240 */ @Entity @Table(name = "M4CCB_CV_ACT_INVES") @XmlRootElement @NamedQueries({ @NamedQuery(name = "M4ccbCvActInves.findAll", query = "SELECT m FROM M4ccbCvActInves m"), @NamedQuery(name = "M4ccbCvActInves.findByIdOrganization", query = "SELECT m FROM M4ccbCvActInves m WHERE m.m4ccbCvActInvesPK.idOrganization = :idOrganization"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOrActInv", query = "SELECT m FROM M4ccbCvActInves m WHERE m.m4ccbCvActInvesPK.ccbOrActInv = :ccbOrActInv"), @NamedQuery(name = "M4ccbCvActInves.findByStdIdHr", query = "SELECT m FROM M4ccbCvActInves m WHERE m.m4ccbCvActInvesPK.stdIdHr = :stdIdHr"), @NamedQuery(name = "M4ccbCvActInves.findByCcbDtStart", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbDtStart = :ccbDtStart"), @NamedQuery(name = "M4ccbCvActInves.findByCcbDtEnd", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbDtEnd = :ccbDtEnd"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOtraAct", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbOtraAct = :ccbOtraAct"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOtraRea", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbOtraRea = :ccbOtraRea"), @NamedQuery(name = "M4ccbCvActInves.findByCcbTituloProy", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbTituloProy = :ccbTituloProy"), @NamedQuery(name = "M4ccbCvActInves.findByCcbInstitucion", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbInstitucion = :ccbInstitucion"), @NamedQuery(name = "M4ccbCvActInves.findByCcbFacultad", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbFacultad = :ccbFacultad"), @NamedQuery(name = "M4ccbCvActInves.findByCcbDepto", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbDepto = :ccbDepto"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOtrOrg", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbOtrOrg = :ccbOtrOrg"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOtrPart", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbOtrPart = :ccbOtrPart"), @NamedQuery(name = "M4ccbCvActInves.findByCcbRolAct", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbRolAct = :ccbRolAct"), @NamedQuery(name = "M4ccbCvActInves.findByCcbValorProy", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbValorProy = :ccbValorProy"), @NamedQuery(name = "M4ccbCvActInves.findByCcbOtrEst", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbOtrEst = :ccbOtrEst"), @NamedQuery(name = "M4ccbCvActInves.findByCcbDtEnvio", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbDtEnvio = :ccbDtEnvio"), @NamedQuery(name = "M4ccbCvActInves.findByCcbDtProp", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbDtProp = :ccbDtProp"), @NamedQuery(name = "M4ccbCvActInves.findByCcbResumInv", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbResumInv = :ccbResumInv"), @NamedQuery(name = "M4ccbCvActInves.findByCcbUrl", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbUrl = :ccbUrl"), @NamedQuery(name = "M4ccbCvActInves.findByCcbIdActInv", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbIdActInv = :ccbIdActInv"), @NamedQuery(name = "M4ccbCvActInves.findByCcbIdAreaEstrat", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbIdAreaEstrat = :ccbIdAreaEstrat"), @NamedQuery(name = "M4ccbCvActInves.findByCcbIdOrganiz", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbIdOrganiz = :ccbIdOrganiz"), @NamedQuery(name = "M4ccbCvActInves.findByCcbIdEstInves", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbIdEstInves = :ccbIdEstInves"), @NamedQuery(name = "M4ccbCvActInves.findByCcbIdEstadoAct", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbIdEstadoAct = :ccbIdEstadoAct"), @NamedQuery(name = "M4ccbCvActInves.findByStdIdCountry", query = "SELECT m FROM M4ccbCvActInves m WHERE m.stdIdCountry = :stdIdCountry"), @NamedQuery(name = "M4ccbCvActInves.findByStdIdGeoDiv", query = "SELECT m FROM M4ccbCvActInves m WHERE m.stdIdGeoDiv = :stdIdGeoDiv"), @NamedQuery(name = "M4ccbCvActInves.findByStdIdSubGeoDiv", query = "SELECT m FROM M4ccbCvActInves m WHERE m.stdIdSubGeoDiv = :stdIdSubGeoDiv"), @NamedQuery(name = "M4ccbCvActInves.findByStdIdGeoPlace", query = "SELECT m FROM M4ccbCvActInves m WHERE m.stdIdGeoPlace = :stdIdGeoPlace"), @NamedQuery(name = "M4ccbCvActInves.findByCcbCargueAct", query = "SELECT m FROM M4ccbCvActInves m WHERE m.ccbCargueAct = :ccbCargueAct"), @NamedQuery(name = "M4ccbCvActInves.findByIdApprole", query = "SELECT m FROM M4ccbCvActInves m WHERE m.idApprole = :idApprole"), @NamedQuery(name = "M4ccbCvActInves.findByIdSecuser", query = "SELECT m FROM M4ccbCvActInves m WHERE m.idSecuser = :idSecuser"), @NamedQuery(name = "M4ccbCvActInves.findByDtLastUpdate", query = "SELECT m FROM M4ccbCvActInves m WHERE m.dtLastUpdate = :dtLastUpdate")}) public class M4ccbCvActInves implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected M4ccbCvActInvesPK m4ccbCvActInvesPK; @Column(name = "CCB_DT_START") @Temporal(TemporalType.DATE) private Date ccbDtStart; @Column(name = "CCB_DT_END") @Temporal(TemporalType.DATE) private Date ccbDtEnd; @Column(name = "CCB_OTRA_ACT") private String ccbOtraAct; @Column(name = "CCB_OTRA_REA") private String ccbOtraRea; @Column(name = "CCB_TITULO_PROY") private String ccbTituloProy; @Column(name = "CCB_INSTITUCION") private String ccbInstitucion; @Column(name = "CCB_FACULTAD") private String ccbFacultad; @Column(name = "CCB_DEPTO") private String ccbDepto; @Column(name = "CCB_OTR_ORG") private String ccbOtrOrg; @Column(name = "CCB_OTR_PART") private String ccbOtrPart; @Column(name = "CCB_ROL_ACT") private String ccbRolAct; @Column(name = "CCB_VALOR_PROY") private Integer ccbValorProy; @Column(name = "CCB_OTR_EST") private String ccbOtrEst; @Column(name = "CCB_DT_ENVIO") @Temporal(TemporalType.DATE) private Date ccbDtEnvio; @Column(name = "CCB_DT_PROP") @Temporal(TemporalType.DATE) private Date ccbDtProp; @Column(name = "CCB_RESUM_INV") private String ccbResumInv; @Column(name = "CCB_URL") private String ccbUrl; @Column(name = "CCB_ID_ACT_INV") private String ccbIdActInv; @Column(name = "CCB_ID_AREA_ESTRAT") private String ccbIdAreaEstrat; @Column(name = "CCB_ID_ORGANIZ") private String ccbIdOrganiz; @Column(name = "CCB_ID_EST_INVES") private String ccbIdEstInves; @Column(name = "CCB_ID_ESTADO_ACT") private String ccbIdEstadoAct; @Column(name = "STD_ID_COUNTRY") private String stdIdCountry; @Column(name = "STD_ID_GEO_DIV") private String stdIdGeoDiv; @Column(name = "STD_ID_SUB_GEO_DIV") private String stdIdSubGeoDiv; @Column(name = "STD_ID_GEO_PLACE") private String stdIdGeoPlace; @Column(name = "CCB_CARGUE_ACT") private String ccbCargueAct; @Column(name = "ID_APPROLE") private String idApprole; @Column(name = "ID_SECUSER") private String idSecuser; @Column(name = "DT_LAST_UPDATE") @Temporal(TemporalType.DATE) private Date dtLastUpdate; public M4ccbCvActInves() { } public M4ccbCvActInves(M4ccbCvActInvesPK m4ccbCvActInvesPK) { this.m4ccbCvActInvesPK = m4ccbCvActInvesPK; } public M4ccbCvActInves(String idOrganization, short ccbOrActInv, String stdIdHr) { this.m4ccbCvActInvesPK = new M4ccbCvActInvesPK(idOrganization, ccbOrActInv, stdIdHr); } public M4ccbCvActInvesPK getM4ccbCvActInvesPK() { return m4ccbCvActInvesPK; } public void setM4ccbCvActInvesPK(M4ccbCvActInvesPK m4ccbCvActInvesPK) { this.m4ccbCvActInvesPK = m4ccbCvActInvesPK; } public Date getCcbDtStart() { return ccbDtStart; } public void setCcbDtStart(Date ccbDtStart) { this.ccbDtStart = ccbDtStart; } public Date getCcbDtEnd() { return ccbDtEnd; } public void setCcbDtEnd(Date ccbDtEnd) { this.ccbDtEnd = ccbDtEnd; } public String getCcbOtraAct() { return ccbOtraAct; } public void setCcbOtraAct(String ccbOtraAct) { this.ccbOtraAct = ccbOtraAct; } public String getCcbOtraRea() { return ccbOtraRea; } public void setCcbOtraRea(String ccbOtraRea) { this.ccbOtraRea = ccbOtraRea; } public String getCcbTituloProy() { return ccbTituloProy; } public void setCcbTituloProy(String ccbTituloProy) { this.ccbTituloProy = ccbTituloProy; } public String getCcbInstitucion() { return ccbInstitucion; } public void setCcbInstitucion(String ccbInstitucion) { this.ccbInstitucion = ccbInstitucion; } public String getCcbFacultad() { return ccbFacultad; } public void setCcbFacultad(String ccbFacultad) { this.ccbFacultad = ccbFacultad; } public String getCcbDepto() { return ccbDepto; } public void setCcbDepto(String ccbDepto) { this.ccbDepto = ccbDepto; } public String getCcbOtrOrg() { return ccbOtrOrg; } public void setCcbOtrOrg(String ccbOtrOrg) { this.ccbOtrOrg = ccbOtrOrg; } public String getCcbOtrPart() { return ccbOtrPart; } public void setCcbOtrPart(String ccbOtrPart) { this.ccbOtrPart = ccbOtrPart; } public String getCcbRolAct() { return ccbRolAct; } public void setCcbRolAct(String ccbRolAct) { this.ccbRolAct = ccbRolAct; } public Integer getCcbValorProy() { return ccbValorProy; } public void setCcbValorProy(Integer ccbValorProy) { this.ccbValorProy = ccbValorProy; } public String getCcbOtrEst() { return ccbOtrEst; } public void setCcbOtrEst(String ccbOtrEst) { this.ccbOtrEst = ccbOtrEst; } public Date getCcbDtEnvio() { return ccbDtEnvio; } public void setCcbDtEnvio(Date ccbDtEnvio) { this.ccbDtEnvio = ccbDtEnvio; } public Date getCcbDtProp() { return ccbDtProp; } public void setCcbDtProp(Date ccbDtProp) { this.ccbDtProp = ccbDtProp; } public String getCcbResumInv() { return ccbResumInv; } public void setCcbResumInv(String ccbResumInv) { this.ccbResumInv = ccbResumInv; } public String getCcbUrl() { return ccbUrl; } public void setCcbUrl(String ccbUrl) { this.ccbUrl = ccbUrl; } public String getCcbIdActInv() { return ccbIdActInv; } public void setCcbIdActInv(String ccbIdActInv) { this.ccbIdActInv = ccbIdActInv; } public String getCcbIdAreaEstrat() { return ccbIdAreaEstrat; } public void setCcbIdAreaEstrat(String ccbIdAreaEstrat) { this.ccbIdAreaEstrat = ccbIdAreaEstrat; } public String getCcbIdOrganiz() { return ccbIdOrganiz; } public void setCcbIdOrganiz(String ccbIdOrganiz) { this.ccbIdOrganiz = ccbIdOrganiz; } public String getCcbIdEstInves() { return ccbIdEstInves; } public void setCcbIdEstInves(String ccbIdEstInves) { this.ccbIdEstInves = ccbIdEstInves; } public String getCcbIdEstadoAct() { return ccbIdEstadoAct; } public void setCcbIdEstadoAct(String ccbIdEstadoAct) { this.ccbIdEstadoAct = ccbIdEstadoAct; } public String getStdIdCountry() { return stdIdCountry; } public void setStdIdCountry(String stdIdCountry) { this.stdIdCountry = stdIdCountry; } public String getStdIdGeoDiv() { return stdIdGeoDiv; } public void setStdIdGeoDiv(String stdIdGeoDiv) { this.stdIdGeoDiv = stdIdGeoDiv; } public String getStdIdSubGeoDiv() { return stdIdSubGeoDiv; } public void setStdIdSubGeoDiv(String stdIdSubGeoDiv) { this.stdIdSubGeoDiv = stdIdSubGeoDiv; } public String getStdIdGeoPlace() { return stdIdGeoPlace; } public void setStdIdGeoPlace(String stdIdGeoPlace) { this.stdIdGeoPlace = stdIdGeoPlace; } public String getCcbCargueAct() { return ccbCargueAct; } public void setCcbCargueAct(String ccbCargueAct) { this.ccbCargueAct = ccbCargueAct; } public String getIdApprole() { return idApprole; } public void setIdApprole(String idApprole) { this.idApprole = idApprole; } public String getIdSecuser() { return idSecuser; } public void setIdSecuser(String idSecuser) { this.idSecuser = idSecuser; } public Date getDtLastUpdate() { return dtLastUpdate; } public void setDtLastUpdate(Date dtLastUpdate) { this.dtLastUpdate = dtLastUpdate; } @Override public int hashCode() { int hash = 0; hash += (m4ccbCvActInvesPK != null ? m4ccbCvActInvesPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof M4ccbCvActInves)) { return false; } M4ccbCvActInves other = (M4ccbCvActInves) object; if ((this.m4ccbCvActInvesPK == null && other.m4ccbCvActInvesPK != null) || (this.m4ccbCvActInvesPK != null && !this.m4ccbCvActInvesPK.equals(other.m4ccbCvActInvesPK))) { return false; } return true; } @Override public String toString() { return "co.edu.icesi.activitytopeopleupdater.peoplenet.model.M4ccbCvActInves[ m4ccbCvActInvesPK=" + m4ccbCvActInvesPK + " ]"; } }
true
bde0e8cf2595414d95374228fa1df5f535ba490f
Java
alberts/fullung
/sre2008/src/main/java/net/lunglet/gridgain/DefaultGrid.java
UTF-8
2,940
2.015625
2
[]
no_license
package net.lunglet.gridgain; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.gridgain.grid.Grid; import org.gridgain.grid.GridConfigurationAdapter; import org.gridgain.grid.GridFactory; import org.gridgain.grid.GridTask; import org.gridgain.grid.spi.collision.jobstealing.GridJobStealingCollisionSpi; import org.gridgain.grid.spi.communication.tcp.GridTcpCommunicationSpi; import org.gridgain.grid.spi.discovery.multicast.GridMulticastDiscoverySpi; import org.gridgain.grid.spi.failover.jobstealing.GridJobStealingFailoverSpi; import org.gridgain.grid.spi.topology.basic.GridBasicTopologySpi; public final class DefaultGrid<R> extends AbstractGrid<R> { // XXX use remote jrockit and local = false for 2048 component GMM-SVM // probably related to some direct buffers allocated somewhere private static final boolean LOCAL = true; public DefaultGrid(final Iterable<? extends GridTask<?, R>> tasks, final ResultListener<R> resultListener) { super(tasks, resultListener); } public void run() throws Exception { System.setProperty("GRIDGAIN_HOME", System.getProperty("user.dir")); System.setProperty("gridgain.update.notifier", "false"); ExecutorService executorService = Executors.newFixedThreadPool(20); GridConfigurationAdapter cfg = new GridConfigurationAdapter(); cfg.setGridName("grid"); GridBasicTopologySpi topologySpi = new GridBasicTopologySpi(); topologySpi.setLocalNode(true); topologySpi.setRemoteNodes(true); cfg.setTopologySpi(topologySpi); cfg.setPeerClassLoadingEnabled(true); cfg.setExecutorService(executorService); GridJobStealingCollisionSpi collisionSpi = new GridJobStealingCollisionSpi(); if (LOCAL) { collisionSpi.setActiveJobsThreshold(2); collisionSpi.setWaitJobsThreshold(4); collisionSpi.setStealingEnabled(true); collisionSpi.setMaximumStealingAttempts(5); } else { collisionSpi.setActiveJobsThreshold(0); collisionSpi.setWaitJobsThreshold(0); collisionSpi.setStealingEnabled(false); collisionSpi.setMaximumStealingAttempts(5); } cfg.setCollisionSpi(collisionSpi); GridJobStealingFailoverSpi failoverSpi = new GridJobStealingFailoverSpi(); failoverSpi.setMaximumFailoverAttempts(5); cfg.setFailoverSpi(failoverSpi); cfg.setCommunicationSpi(new GridTcpCommunicationSpi()); cfg.setDiscoverySpi(new GridMulticastDiscoverySpi()); try { final Grid grid = GridFactory.start(cfg); execute(grid); } finally { GridFactory.stop(cfg.getGridName(), false); executorService.shutdown(); executorService.awaitTermination(0L, TimeUnit.MILLISECONDS); } } }
true
f3388d880dced9044e63e09559035c40fe347d99
Java
BarryPro/JavaEE_Eclipse
/LGcode/project_codes/book/src/org/crazyit/book/ui/SalePanel.java
UTF-8
18,819
2.0625
2
[]
no_license
package org.crazyit.book.ui; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * ���۽��� * * @author yangenxiong yangenxiong2009@gmail.com * @version 1.0 * <br/>��վ: <a href="http://www.crazyit.org">���Java����</a> * <br>Copyright (C), 2009-2010, yangenxiong * <br>This program is protected by copyright laws. */ public class SalePanel extends CommonPanel { BookService bookService; //���ۼ�¼�� Vector columns; //������ۼ�¼�� Vector bookSaleRecordColumns; //���ۼ�¼��ҵ��ӿ� SaleRecordService saleRecordService; //��Ľ��׼�¼�б� JTable bookSaleRecordTable; //�鱾ѡ��������� JComboBox bookComboBox; //������ۼ�¼���� Vector<BookSaleRecord> bookSaleRecordDatas; //���ۼ�¼��id�ı��� JTextField saleRecordId; //���ۼ�¼�ܼ� JTextField totalPrice; //�������� JTextField recordDate; //���������� JTextField amount; //��հ�ť JButton clearButton; //��ĵ��� JLabel singlePrice; //����������� JTextField bookAmount; //���Ӧ�Ŀ�� JLabel repertorySize; //�����İ�ť JButton addBookButton; //ɾ����İ�ť JButton deleteBookButton; //�ɽ���ť JButton confirmButton; //��ѯ��ť JButton queyrButton; //��ѯ��������� JTextField queryDate; //���ڸ�ʽ private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //ʱ���ʽ private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); private void initColumns() { //��ʼ�����ۼ�¼�б���� this.columns = new Vector(); this.columns.add("id"); this.columns.add("�����鱾"); this.columns.add("�ܼ�"); this.columns.add("��������"); this.columns.add("������"); //��ʼ�����ۼ�¼�����б���� this.bookSaleRecordColumns = new Vector(); this.bookSaleRecordColumns.add("id"); this.bookSaleRecordColumns.add("����"); this.bookSaleRecordColumns.add("����"); this.bookSaleRecordColumns.add("����"); this.bookSaleRecordColumns.add("bookId"); } public SalePanel(BookService bookService, SaleRecordService saleRecordService) { this.bookService = bookService; this.saleRecordService = saleRecordService; //�����б����� setViewDatas(); //��ʼ���� initColumns(); //�����б� DefaultTableModel model = new DefaultTableModel(datas, columns); JTable table = new CommonJTable(model); setJTable(table); JScrollPane upPane = new JScrollPane(table); upPane.setPreferredSize(new Dimension(1000, 350)); //�������, �޸ĵĽ��� JPanel downPane = new JPanel(); downPane.setLayout(new BoxLayout(downPane, BoxLayout.Y_AXIS)); /*******************************************************/ Box downBox1 = new Box(BoxLayout.X_AXIS); this.saleRecordId = new JTextField(10); downBox1.add(this.saleRecordId); this.saleRecordId.setVisible(false); //�б������box downBox1.add(new JLabel("�ܼۣ�")); this.totalPrice = new JTextField(10); this.totalPrice.setEditable(false); downBox1.add(this.totalPrice); downBox1.add(new JLabel(" ")); downBox1.add(new JLabel("�������ڣ�")); this.recordDate = new JTextField(10); this.recordDate.setEditable(false); //���õ�ǰ����ʱ�� setRecordDate(); downBox1.add(this.recordDate); downBox1.add(new JLabel(" ")); downBox1.add(new JLabel("��������")); this.amount = new JTextField(10); this.amount.setEditable(false); downBox1.add(this.amount); downBox1.add(new JLabel(" ")); /*******************************************************/ //���б� Box downBox2 = new Box(BoxLayout.X_AXIS); this.bookSaleRecordDatas = new Vector(); DefaultTableModel bookModel = new DefaultTableModel(this.bookSaleRecordDatas, this.bookSaleRecordColumns); this.bookSaleRecordTable = new CommonJTable(bookModel); //�����鱾���׼�¼�б����ʽ setBookSaleRecordTableFace(); JScrollPane bookScrollPane = new JScrollPane(this.bookSaleRecordTable); bookScrollPane.setPreferredSize(new Dimension(1000, 120)); downBox2.add(bookScrollPane); /*******************************************************/ Box downBox3 = new Box(BoxLayout.X_AXIS); downBox3.add(Box.createHorizontalStrut(100)); downBox3.add(new JLabel("�鱾��")); downBox3.add(Box.createHorizontalStrut(20)); //������������������� this.bookComboBox = new JComboBox(); //Ϊ������������� buildBooksComboBox(); downBox3.add(this.bookComboBox); downBox3.add(Box.createHorizontalStrut(50)); downBox3.add(new JLabel("������")); downBox3.add(Box.createHorizontalStrut(20)); this.bookAmount = new JTextField(10); downBox3.add(this.bookAmount); downBox3.add(Box.createHorizontalStrut(50)); downBox3.add(new JLabel("���ۣ�")); downBox3.add(Box.createHorizontalStrut(20)); this.singlePrice = new JLabel(); downBox3.add(this.singlePrice); downBox3.add(Box.createHorizontalStrut(100)); downBox3.add(new JLabel("��棺")); downBox3.add(Box.createHorizontalStrut(20)); this.repertorySize = new JLabel(); downBox3.add(this.repertorySize); downBox3.add(Box.createHorizontalStrut(80)); this.addBookButton = new JButton("���"); downBox3.add(this.addBookButton); downBox3.add(Box.createHorizontalStrut(30)); this.deleteBookButton = new JButton("ɾ��"); downBox3.add(this.deleteBookButton); /*******************************************************/ Box downBox4 = new Box(BoxLayout.X_AXIS); this.confirmButton = new JButton("�ɽ�"); downBox4.add(this.confirmButton); downBox4.add(Box.createHorizontalStrut(120)); clearButton = new JButton("���"); downBox4.add(clearButton); /*******************************************************/ downPane.add(getSplitBox()); downPane.add(downBox1); downPane.add(getSplitBox()); downPane.add(downBox2); downPane.add(getSplitBox()); downPane.add(downBox3); downPane.add(getSplitBox()); downPane.add(downBox4); /*******************��ѯ******************/ JPanel queryPanel = new JPanel(); Box queryBox = new Box(BoxLayout.X_AXIS); queryBox.add(new JLabel("���ڣ�")); queryBox.add(Box.createHorizontalStrut(30)); this.queryDate = new JTextField(20); queryBox.add(this.queryDate); queryBox.add(Box.createHorizontalStrut(30)); this.queyrButton = new JButton("��ѯ"); queryBox.add(this.queyrButton); queryPanel.add(queryBox); this.add(queryPanel); //�б�Ϊ��ӽ��� JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upPane, downPane); split.setDividerSize(5); this.add(split); //��ʼ�������� initListeners(); } //��ʼ�������� private void initListeners() { //���ѡ������� getJTable().getSelectionModel().addListSelectionListener(new ListSelectionListener(){ public void valueChanged(ListSelectionEvent event) { //��ѡ����ʱ����ͷ�ʱ��ִ�� if (!event.getValueIsAdjusting()) { //���û��ѡ���κ�һ��, �򷵻� if (getJTable().getSelectedRowCount() != 1) return; view(); } } }); //��հ�ť������ this.clearButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { clear(); } }); //�鱾ѡ������������ this.bookComboBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { changeBook(); } }); //������ʾ��ĵ��� changeBook(); //���б����һ��������ۼ�¼�İ�ť this.addBookButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { appendBook(); } }); //ɾ����Ľ��׼�¼��ť this.deleteBookButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { removeBook(); } }); //�ɽ���ť this.confirmButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { sale(); } }); //��ѯ this.queyrButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { query(); } }); } private void query() { String date = this.queryDate.getText(); Date d = null; try { d = dateFormat.parse(date); } catch (ParseException e) { showWarn("������yyyy-MM-dd�ĸ�ʽ����"); return; } //����ִ�в�ѯ Vector<SaleRecord> records = (Vector<SaleRecord>)saleRecordService.getAll(d); Vector<Vector> datas = changeDatas(records); setDatas(datas); //ˢ���б� refreshTable(); } //�ɽ��ķ��� private void sale() { if (!this.saleRecordId.getText().equals("")) { showWarn("������ٽ��в���"); return; } //���û�гɽ��κ���, ���� if (this.bookSaleRecordDatas.size() == 0) { showWarn("û�г����κε���, ���óɽ�"); return; } SaleRecord r = new SaleRecord(); r.setRECORD_DATE(this.recordDate.getText()); r.setBookSaleRecords(this.bookSaleRecordDatas); try { saleRecordService.saveRecord(r); } catch (BusinessException e) {//�˴����쳣��ҵ���쳣 showWarn(e.getMessage()); return; } //���¶�ȡ���� setViewDatas(); //��ս��� clear(); } //���б����һ��������ۼ�¼ private void appendBook() { if (!this.saleRecordId.getText().equals("")) { showWarn("������ٽ��в���"); return; } if (this.bookAmount.getText().equals("")) { showWarn("�������������"); return; } //���ѡ�еĶ��� Book book = (Book)bookComboBox.getSelectedItem(); String amount = this.bookAmount.getText(); appendOrUpdate(book, amount); //ˢ���б� refreshBookSaleRecordTableData(); //�����ܼ� countTotalPrice(); //���������� setTotalAmount(); } //��ӻ����޸��鱾���׼�¼�еĶ��� private void appendOrUpdate(Book book, String amount) { BookSaleRecord r = getBookSaleRecordFromView(book); //���Ϊ��, ��Ϊ����ӵ���, �ǿ�, ������Ѿ����б��� if (r == null) { //����BookSaleRecord������ӵ����ݼ����� BookSaleRecord record = new BookSaleRecord(); record.setBook(book); record.setTRADE_SUM(amount); this.bookSaleRecordDatas.add(record); } else { int newAmount = Integer.valueOf(amount) + Integer.valueOf(r.getTRADE_SUM()); r.setTRADE_SUM(String.valueOf(newAmount)); } } //��ȡ���б����Ƿ��Ѿ�������ͬ���� private BookSaleRecord getBookSaleRecordFromView(Book book) { for (BookSaleRecord r : this.bookSaleRecordDatas) { if (r.getBook().getID().equals(book.getID())) { return r; } } return null; } //���������� private void setTotalAmount() { int amount = 0; for (BookSaleRecord r : this.bookSaleRecordDatas) { amount += Integer.valueOf(r.getTRADE_SUM()); } this.amount.setText(String.valueOf(amount)); } //�����ܼ� private void countTotalPrice() { double totalPrice = 0; for (BookSaleRecord r : this.bookSaleRecordDatas) { totalPrice += (Integer.valueOf(r.getTRADE_SUM()) * Double.valueOf(r.getBook().getBOOK_PRICE())); } this.totalPrice.setText(String.valueOf(totalPrice)); } //���б����Ƴ�һ��������ۼ�¼ private void removeBook() { if (!this.saleRecordId.getText().equals("")) { showWarn("������ٽ��в���"); return; } if (bookSaleRecordTable.getSelectedRow() == -1) { showWarn("��ѡ����Ҫɾ������"); return; } //�ڼ�����ɾ����Ӧ������������ this.bookSaleRecordDatas.remove(bookSaleRecordTable.getSelectedRow()); //ˢ���б� refreshBookSaleRecordTableData(); //���¼����ܼۺ������� setTotalAmount(); countTotalPrice(); } //���鱾ѡ�����������ı�ʱ, ִ�и÷��� private void changeBook() { //���ѡ���Book���� Book book = (Book)bookComboBox.getSelectedItem(); if (book == null) return; //������ʾ����ļ۸� this.singlePrice.setText(book.getBOOK_PRICE()); this.repertorySize.setText(book.getREPERTORY_SIZE()); } //��� public void clear() { //ˢ�����б� refreshTable(); this.saleRecordId.setText(""); this.totalPrice.setText(""); //���ý���Ľ���ʱ��Ϊ��ǰʱ�� setRecordDate(); this.amount.setText(""); this.bookSaleRecordDatas.removeAll(this.bookSaleRecordDatas); refreshBookSaleRecordTableData(); //ˢ������ this.bookComboBox.removeAllItems(); buildBooksComboBox(); } //������ͼ���� public void setViewDatas() { Vector<SaleRecord> records = (Vector<SaleRecord>)saleRecordService.getAll(new Date()); Vector<Vector> datas = changeDatas(records); setDatas(datas); } //������ת�������б�����ݸ�ʽ private Vector<Vector> changeDatas(Vector<SaleRecord> records) { Vector<Vector> view = new Vector<Vector>(); for (SaleRecord record : records) { Vector v = new Vector(); v.add(record.getID()); v.add(record.getBookNames()); v.add(record.getTotalPrice()); v.add(record.getRECORD_DATE()); v.add(record.getAmount()); view.add(v); } return view; } //����������ѡ����������� private void buildBooksComboBox() { Collection<Book> books = bookService.getAll(); for (Book book : books) { this.bookComboBox.addItem(makeBook(book)); } } //����Book����, ������ӵ���������, ��д��equals��toString���� private Book makeBook(final Book source) { Book book = new Book(){ public boolean equals(Object obj) { if (obj instanceof Book) { Book b = (Book)obj; if (getID().equals(b.getID())) return true; } return false; } public String toString() { return getBOOK_NAME(); } }; book.setBOOK_NAME(source.getBOOK_NAME()); book.setBOOK_PRICE(source.getBOOK_PRICE()); book.setREPERTORY_SIZE(source.getREPERTORY_SIZE()); book.setID(source.getID()); return book; } //�鿴һ�����ۼ�¼ private void view() { String saleRecordId = getSelectId(getJTable()); //�õ���Ľ��׼�¼ SaleRecord record = saleRecordService.get(saleRecordId); //���õ�ǰ�鱾�������� this.bookSaleRecordDatas = record.getBookSaleRecords(); //ˢ���鱾�����б� refreshBookSaleRecordTableData(); this.saleRecordId.setText(record.getID()); this.totalPrice.setText(String.valueOf(record.getTotalPrice())); this.recordDate.setText(record.getRECORD_DATE()); this.amount.setText(String.valueOf(record.getAmount())); } //��������ۼ�¼ת�����б��ʽ private Vector<Vector> changeBookSaleRecordDate(Vector<BookSaleRecord> records) { Vector<Vector> view = new Vector<Vector>(); for (BookSaleRecord r : records) { Vector v = new Vector(); v.add(r.getID()); v.add(r.getBook().getBOOK_NAME()); v.add(r.getBook().getBOOK_PRICE()); v.add(r.getTRADE_SUM()); v.add(r.getBook().getID()); view.add(v); } return view; } //ˢ���鱾���ۼ�¼���б� private void refreshBookSaleRecordTableData() { Vector<Vector> view = changeBookSaleRecordDate(this.bookSaleRecordDatas); DefaultTableModel tableModel = (DefaultTableModel)this.bookSaleRecordTable.getModel(); //������������Model�� tableModel.setDataVector(view, this.bookSaleRecordColumns); //���ñ����ʽ setBookSaleRecordTableFace(); } //�����鱾���ۼ�¼����ʽ private void setBookSaleRecordTableFace() { this.bookSaleRecordTable.setRowHeight(30); //�������ۼ�¼id�� this.bookSaleRecordTable.getColumn("id").setMinWidth(-1); this.bookSaleRecordTable.getColumn("id").setMaxWidth(-1); //���ض�Ӧ����id�� this.bookSaleRecordTable.getColumn("bookId").setMinWidth(-1); this.bookSaleRecordTable.getColumn("bookId").setMaxWidth(-1); } @Override public Vector<String> getColumns() { return this.columns; } @Override public void setTableFace() { getJTable().getColumn("id").setMinWidth(-1); getJTable().getColumn("id").setMaxWidth(-1); getJTable().getColumn("�����鱾").setMinWidth(350); getJTable().setRowHeight(30); } //���ý�����ʾ�Ľ���ʱ�� private void setRecordDate() { //���óɽ�����Ϊ��ǰʱ�� Date now = new Date(); timeFormat.format(now); this.recordDate.setText(timeFormat.format(now)); } }
true
aaa42c6d5147fb38f4d69862f90bb9d57d6cd22b
Java
Game-Designing/Custom-Football-Game
/sources/p005cm/aptoide/p006pt/dataprovider/model/p009v7/TimelineStats.java
UTF-8
3,274
2.375
2
[ "MIT" ]
permissive
package p005cm.aptoide.p006pt.dataprovider.model.p009v7; /* renamed from: cm.aptoide.pt.dataprovider.model.v7.TimelineStats */ public class TimelineStats extends BaseV7Response { private StatusData data; /* renamed from: cm.aptoide.pt.dataprovider.model.v7.TimelineStats$StatusData */ public static class StatusData { private long followers; private long following; public long getFollowers() { return this.followers; } public void setFollowers(long followers2) { this.followers = followers2; } public long getFollowing() { return this.following; } public void setFollowing(long following2) { this.following = following2; } public int hashCode() { long $followers = getFollowers(); int result = (1 * 59) + ((int) (($followers >>> 32) ^ $followers)); long $following = getFollowing(); return (result * 59) + ((int) (($following >>> 32) ^ $following)); } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof StatusData)) { return false; } StatusData other = (StatusData) o; if (other.canEqual(this) && getFollowers() == other.getFollowers() && getFollowing() == other.getFollowing()) { return true; } return false; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("TimelineStats.StatusData(followers="); sb.append(getFollowers()); sb.append(", following="); sb.append(getFollowing()); sb.append(")"); return sb.toString(); } /* access modifiers changed from: protected */ public boolean canEqual(Object other) { return other instanceof StatusData; } } public StatusData getData() { return this.data; } public void setData(StatusData data2) { this.data = data2; } public int hashCode() { int result = (1 * 59) + super.hashCode(); StatusData data2 = getData(); return (result * 59) + (data2 == null ? 43 : data2.hashCode()); } /* access modifiers changed from: protected */ public boolean canEqual(Object other) { return other instanceof TimelineStats; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof TimelineStats)) { return false; } TimelineStats other = (TimelineStats) o; if (!other.canEqual(this) || !super.equals(o)) { return false; } StatusData data2 = getData(); Object other$data = other.getData(); if (data2 != null ? data2.equals(other$data) : other$data == null) { return true; } return false; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("TimelineStats(data="); sb.append(getData()); sb.append(")"); return sb.toString(); } }
true
169020f3c7050c719c5176f1525d3dc4b1087be9
Java
Minnaldo/JAVA
/Programming_Plus/src/day03/Programmar.java
UTF-8
502
3.09375
3
[]
no_license
package day03; public class Programmar extends Employee{ public Programmar(int num) { super(num); this.num = num; this.addtime = 3; this.worktime = super.worktime + this.addtime; } @Override public String whoami() { // TODO Auto-generated method stub return "개발자"; } @Override public String work() { // TODO Auto-generated method stub return "개발자가 " + this.worktime + " 시간동안 일을 합니다"; } public void goodIdea() { this.addtime--; } }
true
2e48ceaf2b0c34edb4be1f1c572268c931e4b031
Java
marcoshung/mhungAUG2017
/Explore Spilt/src/Split.java
UTF-8
3,251
4
4
[]
no_license
import java.util.Arrays; //Marcos Hung, Period 2 public class Split { public static void main(String[] args) { // Your task Part 0 //String.split(); //It's a method that acts on a string, <StringName>.split(<String sp>); //Where sp is the string where the string splits //And it returns an array //it will split at spaces and return an array of ["I","like","apples!"] // Example 2: "I really like really red apples".split("really") //it will split at the word "really" and return an array of ["I "," like "," red apples!"] //play around with String.split! //What happens if you "I reallyreally likeapples".split("really") ? System.out.println(Arrays.toString("applespineapplesbreadlettustomatobaconmayohambreadcheese".split("bread"))); System.out.println(Arrays.toString("apple bread ham bread apple bread".split(" "))); System.out.println(getFilling("hamapplebread")); System.out.println(getFilling("bread")); System.out.println(getFilling("applebreadhambreadapplebread")); System.out.println(getFilling("breadbread")); System.out.println(getFilling("applebreadhamcheesebread")); System.out.println(getFilling("breadhambread")); System.out.println(getFillingSpaces("bread")); System.out.println(getFillingSpaces("apple bread ham bread apple bread cheese")); System.out.println(getFillingSpaces("bread bread")); System.out.println(getFillingSpaces("bread ham bread")); System.out.println(getFillingSpaces("apple bread ham cheese bread")); } //Your task Part 1: /*Write a method that take in a string like "applespineapplesbreadlettustomatobaconmayohambreadcheese" describing a sandwich * use String.split to split up the sandwich by the word "bread" and return what's in the middle of the sandwich and ignores what's on the outside * What if it's a fancy sandwich with multiple pieces of bread? */ public static String getFilling(String sandwich) { String[] array = sandwich.split("bread"); String filling = ""; if(sandwich.indexOf("bread") == -1 || array.length < 2) { filling = "not a sandwich"; } if(sandwich.indexOf("bread") == 0) { for(int i = 0; i <array.length; i++){ filling += array[i]; } }else { for(int i = 1; i <array.length; i++) { filling += array[i]; } } if(filling.equals("")) { filling = "nothing"; } return filling; } //Your task Part 2: /*Write a method that take in a string like "apples pineapples bread lettus tomato bacon mayo ham bread cheese" describing a sandwich * use String.split to split up the sandwich at the spaces, " ", and return what's in the middle of the sandwich and ignores what's on the outside * Again, what if it's a fancy sandwich with multiple pieces of bread? */ public static String getFillingSpaces(String sandwich) { String filling = ""; String[] array = sandwich.split(" "); Boolean seenBread = false; String temp = ""; for(int i = 0;i<array.length;i++) { if(array[i].equals ("bread")) { seenBread = true; filling += temp; temp = ""; }else if(seenBread) { temp += array[i] + " "; } } if(filling.equals("")) { filling = "not a sandwich"; } return filling; } }
true
9f22c317e5390e9be495be4d37964c421f1e621b
Java
AksyonovaKaterina/bad_java_202107
/src/com/bad_java/homework/hyperskill/coffee_machine/part_5/ingredients/Water.java
UTF-8
611
3.140625
3
[]
no_license
package com.bad_java.homework.hyperskill.coffee_machine.part_5.ingredients; import com.bad_java.homework.hyperskill.coffee_machine.part_5.ingredients.Ingredient; public class Water implements Ingredient { private int amount; private final String unit = "ml"; public Water(int amount) { this.amount = amount; } public int getAmount() { return amount; } public String getUnit() { return unit; } public void setAmount(int amount) { this.amount = amount; } public void addAmount(int amount) { this.amount += amount; } }
true
5c7c56446f4dd2585dac19d396ac7e87335f2309
Java
SiteView/ECC8.13
/trunk/java.prj/myajaxgui/src/de/ajaxgui/test/GridLayout.java
UTF-8
238
1.679688
2
[]
no_license
package de.ajaxgui.test; import de.ajaxgui.Application; public class GridLayout extends Application { public void run() { this.init(); GridLayoutMainForm glmf = new GridLayoutMainForm(); this.setMainForm(glmf); } }
true
0eba2b8d7fd58ba8335337e39888ade4bc99951a
Java
RonaldoFaustino/CursoJava8
/1Disciplina/src/unidade2/VetorAB.java
ISO-8859-1
414
3.3125
3
[]
no_license
package unidade2; public class VetorAB { public static void main(String[] args) { int A[] = new int[50]; int B[] = new int[50]; for(int i=0;i<50;i++) { A[i] = i ; if(i%2 == 0) // resto da diviso por 2 par B[i] = 2*A[i]; else // impar B[i] = A[i]/2; } for(int a:A) System.out.print(a+","); System.out.println(""); for(int b: B) System.out.print(b+","); } }
true
0386c84d8fb14f88cd4310d5fe645383782d7d25
Java
litliang/ms
/code/app/src/main/java/com/yzb/card/king/http/common/AppTransferForFastpaymentRequest.java
UTF-8
2,417
1.90625
2
[]
no_license
package com.yzb.card.king.http.common; import android.text.TextUtils; import com.yzb.card.king.http.BaseRequest; import com.yzb.card.king.http.HttpCallBackData; import com.yzb.card.king.sys.AppConstant; import com.yzb.card.king.sys.CardConstant; import com.yzb.card.king.sys.GlobalApp; import com.yzb.card.king.util.AppUtils; import java.util.HashMap; import java.util.Map; /** * 类 名: * 作 者:Li Yubing * 日 期:2017/2/8 * 描 述: */ public class AppTransferForFastpaymentRequest extends BaseRequest { Map<String, Object> param = new HashMap<String, Object>(); /** * 接口名 */ private String serverName = CardConstant.CARD_HILIFE_APPTRANSFERFORFASTPAYMENT; private String paySessionId ; /** * * @param debitSessionId 付款方sessionId * @param creditSessionId 收款方sessionId * @param orderNo 订单号 * @param amount 订单金额 * @param status 非浦发银行卡状态 * @param debitType 付款方式 * @param debitSortCode 付款银行关联码 * @param token 他行消费鉴权返回 * @param identifyingCode 验证码 */ public AppTransferForFastpaymentRequest(String debitSessionId,String creditSessionId,String orderNo,String amount,String status,String debitType,String debitSortCode,String token,String customerId,String identifyingCode,String flag,String url){ paySessionId = debitSessionId; param.put("debitSessionId", debitSessionId); param.put("creditSessionId", creditSessionId); param.put("transIp", AppUtils.getLocalIpAddress(GlobalApp.getInstance().getContext())); param.put("orderNo", orderNo); param.put("amount", amount); param.put("status", status); param.put("debitType", debitType); param.put("debitSortCode", debitSortCode); param.put("token", TextUtils.isEmpty(token)?"":token); param.put("customerId",TextUtils.isEmpty(customerId)?"":customerId); param.put("identifyingCode", identifyingCode); param.put("flag", flag); param.put("notifyUrl", url); } @Override public void sendRequest(HttpCallBackData callBack) { isIfSaveSessionId(false);//无需更新sessionId //发送post请求 sendPostRequest(setParams(paySessionId, serverName, AppConstant.UUID, param), callBack); } }
true
75955b3346603734c4d8df54b969336576c5d783
Java
fedega/projetofinalsuprema
/Partes/Fisico/Programacao/SupremaImoveis/CCSBuild/src/com/codecharge/util/LocaleChooser.java
UTF-8
11,372
2.0625
2
[]
no_license
//LocaleChooser class @0-5BBB4C16 package com.codecharge.util; import com.codecharge.Names; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Cookie; import java.util.*; public class LocaleChooser { public static CCSLocale getCCSLocale(HttpServletRequest request) { CCLogger log = CCLogger.getInstance(); String localeName = getCurrentLocaleName(request); log.debug("LocaleChooser.getCCSLocale => localeName: "+localeName); if (StringUtils.isEmpty(localeName)) { localeName = StringUtils.getSiteProperty("defaultLocale"); log.debug("LocaleChooser.getCCSLocale => use default localeName: "+localeName); } Map supportedLocales = (Map) ContextStorage.getInstance().getAttribute(Names.LOCALES_POOL); CCSLocale ccsLocale = null; if (supportedLocales != null) { ccsLocale = (CCSLocale) supportedLocales.get(localeName); if (ccsLocale == null) { ccsLocale = (CCSLocale) supportedLocales.get(localeName.substring(0,2)); if (ccsLocale == null) { log.debug("LocaleChooser.getCCSLocale => use default site locale"); ccsLocale = (CCSLocale) supportedLocales.get(StringUtils.getSiteProperty("defaultLocale")); } } } else { throw new IllegalStateException("Supported locales are not defined."); } return ccsLocale; } public static String getLocaleParameter(HttpServletRequest request) { String paramName = "locale"; if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableQueryString"))) { paramName = StringUtils.getSiteProperty("queryStringName"); } CCSLocale ccsLocale = getCCSLocale(request); return paramName + "=" + (ccsLocale == null ? "" : ccsLocale.getLocaleName()); } private static String getCurrentLocaleName(HttpServletRequest request) { if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableQueryString"))) { String paramName = StringUtils.getSiteProperty("queryStringName"); if (! StringUtils.isEmpty(paramName)) { String qStr = request.getQueryString(); if (! StringUtils.isEmpty(qStr)) { String value = null; int pos = qStr.indexOf(paramName+"="); int length = (paramName+"=").length(); if (pos != -1) { int pos1 = qStr.indexOf("&", pos); if (pos1 == -1) { value = qStr.substring(pos + length); } else { value = qStr.substring(pos + length, pos1); } } if (! StringUtils.isEmpty(value)) { value = clarifyLocaleName(value); return normalizeLanguage(value); } } } } if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableSession"))) { String paramName = StringUtils.getSiteProperty("sessionName"); if (! StringUtils.isEmpty(paramName)) { String value = ((SimpleSessionStorage) SessionStorage .getInstance(request)).getAttributeAsString(paramName); if (! StringUtils.isEmpty(value)) { value = clarifyLocaleName(value); return normalizeLanguage(value); } } } if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableSession"))) { String paramName = StringUtils.getSiteProperty("languageSessionName"); if (! StringUtils.isEmpty(paramName)) { String value = ((SimpleSessionStorage) SessionStorage .getInstance(request)).getAttributeAsString(paramName); if (! StringUtils.isEmpty(value)) { value = clarifyLocaleName(value); return normalizeLanguage(value); } } } if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableCookie"))) { String paramName = StringUtils.getSiteProperty("cookieName"); if (! StringUtils.isEmpty(paramName)) { String value = StringUtils.getCookie(paramName, request.getCookies()); if (! StringUtils.isEmpty(value)) { value = clarifyLocaleName(value); return normalizeLanguage(value); } } } if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableHTTPHeader"))) { String paramName = StringUtils.getSiteProperty("httpHeaderName"); if (! StringUtils.isEmpty(paramName)) { String value = getHeaderLocaleName(request.getHeader(paramName)); if (! StringUtils.isEmpty(value)) { value = clarifyLocaleName(value); return normalizeLanguage(value); } } } return null; } private static String getHeaderLocaleName(String content) { String[] languages = getAcceptedLanguages(content); if (languages == null || languages.length == 0) { return null; } Map supportedLocales = (Map) ContextStorage.getInstance().getAttribute(Names.LOCALES_POOL); for (int i = 0; i < languages.length; i++) { String lang = normalizeLanguage(languages[i]); if (lang != null) { if (supportedLocales.get(lang) != null) { return lang; } } } return null; } private static String[] getAcceptedLanguages(String content) { if (StringUtils.isEmpty(content)) { return null; } String header = content.trim(); float maxPriority = 0; String[] languages = StringUtils.splitToArray(content, ',', '\\'); for (int i = 0; i < languages.length; i++) { languages[i] = languages[i].trim(); } TreeMap acceptedLanguages = new TreeMap(); for (int i = 0; i < languages.length; i++) { int pos = languages[i].indexOf(";"); float priority = 1; String language = languages[i]; if (pos > -1) { if (pos < languages[i].length() - 1) { try { priority = Float.parseFloat(language.substring(pos+1)); } catch (NumberFormatException nfe) { //skip language if it has incorrect quality continue; } } language = language.substring(0, pos); } Float langPriority = new Float(priority); ArrayList langs = (ArrayList) acceptedLanguages.get(langPriority); if (langs == null) { langs = new ArrayList(); acceptedLanguages.put(langPriority, langs); } langs.add(language); } ArrayList resultList = new ArrayList(); for (Iterator keys = acceptedLanguages.keySet().iterator(); keys.hasNext(); ) { ArrayList langs = (ArrayList) acceptedLanguages.get(keys.next()); int langsSize = langs.size(); for (int i = 0; i < langsSize; i++) { resultList.add(langs.get(i)); } } String[] result = new String[resultList.size()]; result = (String[]) resultList.toArray(result); return result; } private static String clarifyLocaleName(String localeName) { if (localeName.indexOf("-") == -1) { Properties localesInfo = (Properties) ContextStorage.getInstance().getAttribute(Names.LOCALES_INFO); String country = localesInfo.getProperty(localeName+".country"); String fullLocaleName = localeName + (StringUtils.isEmpty(country)? "" : "_"+country); Map supportedLocales = (Map) ContextStorage.getInstance().getAttribute(Names.LOCALES_POOL); CCSLocale ccsLocale = null; if (supportedLocales != null) { ccsLocale = (CCSLocale) supportedLocales.get(fullLocaleName); if (ccsLocale != null) { return fullLocaleName; } } } return localeName; } /* * Converts string like "en-us" to "en_US" */ private static String normalizeLanguage(String language) { if (language == null) { return null; } int pos = language.indexOf("-"); if (pos == -1) { pos = language.indexOf("_"); } if (pos == -1) { return language.toLowerCase(); } else if (pos == 0) { return null; } else if (pos == language.length() - 1) { return language.substring(0, pos).toLowerCase(); } return language.substring(0, pos).toLowerCase()+"_"+language.substring(pos+1).toUpperCase(); } public static void setLocaleName(String localeName, HttpServletRequest request) { if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableSession"))) { String paramName = StringUtils.getSiteProperty("sessionName"); if (! StringUtils.isEmpty(paramName)) { ((SimpleSessionStorage) SessionStorage .getInstance(request)).setAttribute(paramName, localeName); } paramName = StringUtils.getSiteProperty("languageSessionName"); if (! StringUtils.isEmpty(paramName)) { if (localeName.length() > 2) { ((SimpleSessionStorage) SessionStorage .getInstance(request)).setAttribute(paramName, localeName.substring(0,2)); } else { ((SimpleSessionStorage) SessionStorage .getInstance(request)).setAttribute(paramName, localeName); } } } if ("true".equalsIgnoreCase(StringUtils.getSiteProperty("enableCookie"))) { String paramName = StringUtils.getSiteProperty("cookieName"); if (! StringUtils.isEmpty(paramName)) { int maxAge = 0; try { maxAge = Integer.parseInt(StringUtils.getSiteProperty("cookieExpired")) * 24 * 3600; } catch (NumberFormatException nfe_ignore) {} Cookie lang = new Cookie(paramName, localeName); if (maxAge > 0) { lang.setMaxAge(maxAge); } ((SimpleSessionStorage) SessionStorage.getInstance(request)) .setAttribute(Names.LOCALE_COOKIE, lang); } } } } //End LocaleChooser class
true
f2e7475fcd7f736c10856dfe4ff14fdff5888471
Java
tranhung9349/2608_MyProject001
/src/main/java/com/personal/management/controller/CategoryAPIController.java
UTF-8
1,853
2.3125
2
[]
no_license
package com.personal.management.controller; import com.personal.management.model.Category; import com.personal.management.repository.CategoryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @RequestMapping("/api") @CrossOrigin("*") public class CategoryAPIController { @Autowired CategoryRepository categoryRepository; @GetMapping("/categories") ResponseEntity<Iterable<Category>> findAll() { return new ResponseEntity<>(categoryRepository.findAll(), HttpStatus.OK); } @PostMapping("/categories") ResponseEntity<Category> save(@RequestBody Category category) { categoryRepository.save(category); return new ResponseEntity<>(HttpStatus.CREATED); } @DeleteMapping("/categories/{id}") ResponseEntity<Void> delete(@PathVariable long id) { categoryRepository.deleteById(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @PutMapping("/categories/{id}") ResponseEntity<Optional<Category>> edit (@PathVariable long id, Category category) { Optional<Category> selected = categoryRepository.findById(id); if(selected.isPresent()) { category.setId(id); categoryRepository.save(category); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @GetMapping("/categories/filter") ResponseEntity<Iterable<Category>> filterList (@RequestParam String typeName) { Iterable<Category> iterable = categoryRepository.findNameByNameType(typeName); return new ResponseEntity<>(iterable,HttpStatus.OK); } }
true
6e0269078b75916e608ad59657c4006399402d5f
Java
kuali/rice
/rice-middleware/core/api/src/main/java/org/kuali/rice/core/api/util/jaxb/KualiDecimalAdapter.java
UTF-8
1,236
2.125
2
[ "Artistic-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "EPL-1.0", "CPL-1.0", "LGPL-2.1-or-later", "BSD-3-Clause", "LGPL-3.0-only", "ECL-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-jdom", "LicenseRef-scancode-freemarker", "LicenseRef-scancode-unk...
permissive
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.core.api.util.jaxb; import org.kuali.rice.core.api.util.type.KualiDecimal; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * Marshall/unmarshall a joda-time DateTime object. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class KualiDecimalAdapter extends XmlAdapter<String, KualiDecimal> { @Override public String marshal(KualiDecimal decimal) throws Exception { return decimal == null ? null : decimal.toString(); } @Override public KualiDecimal unmarshal(String decimal) throws Exception { return decimal == null ? null : new KualiDecimal(decimal); } }
true
144096106d3f5d434a59a0869bc4cbac827414cd
Java
smarthi/textdigester
/src/main/java/edu/upf/taln/textdigester/importer/TDXMLimporter.java
UTF-8
3,840
2.25
2
[]
no_license
/** * TextDigester: Document Summarization Framework */ package edu.upf.taln.textdigester.importer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import edu.upf.taln.textdigester.model.TDDocument; import edu.upf.taln.textdigester.resource.gate.GtUtils; import gate.Factory; /** * Importing documents in TDXML format.<br/> * Example of XML document in TDXML: http://backingdata.org/textdigester/documetTEXTDIGESTER.xml * * * @author Francesco Ronzano * */ public class TDXMLimporter { private static final Logger logger = LoggerFactory.getLogger(HTMLimporter.class); private static Random rnd = new Random(); public static List<TDDocument> extractDocuments(String TDXMLpath) { List<TDDocument> retList = new ArrayList<TDDocument>(); if(TDXMLpath == null || TDXMLpath.length() == 0) { return retList; } File TDXMLfile = new File(TDXMLpath); if(TDXMLfile == null || !TDXMLfile.exists() || !TDXMLfile.isFile()) { return retList; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(TDXMLfile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("doc"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String docName = eElement.getAttribute("name"); String docContent = eElement.getTextContent(); String docContentXML = node2String(nNode); try{ File dirOrInputTDXMLfile = TDXMLfile.getParentFile(); //create a temp file File appoFile = new File(dirOrInputTDXMLfile + File.separator + "toDel_" + rnd.nextInt() + ".xml"); //write it BufferedWriter bw = new BufferedWriter(new FileWriter(appoFile)); bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" + "\n<root>\n" + docContentXML + "\n</root>"); bw.close(); GtUtils.initGate(); URL documentUrl = appoFile.toURI().toURL(); gate.Document gateDoc = Factory.newDocument(documentUrl); appoFile.delete(); retList.add(new TDDocument(docContent, gateDoc, docName)); } catch(IOException e){ e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } return retList; } static String node2String(Node node) throws TransformerFactoryConfigurationError, TransformerException { // you may prefer to use single instances of Transformer, and // StringWriter rather than create each time. That would be up to your // judgement and whether your app is single threaded etc StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), xmlOutput); return xmlOutput.getWriter().toString(); } }
true
9aeba10ae2a986093bf3a973031f2b0e7bb05896
Java
auxor/android-wear-decompile
/decompiled/java/lang/reflect/InvocationTargetException.java
UTF-8
736
2.453125
2
[]
no_license
package java.lang.reflect; public class InvocationTargetException extends ReflectiveOperationException { private static final long serialVersionUID = 4085088731926701167L; private Throwable target; protected InvocationTargetException() { super((Throwable) null); } public InvocationTargetException(Throwable exception) { super(null, exception); this.target = exception; } public InvocationTargetException(Throwable exception, String detailMessage) { super(detailMessage, exception); this.target = exception; } public Throwable getTargetException() { return this.target; } public Throwable getCause() { return this.target; } }
true
fbb94e9c54ba9411157ddb8e2223055a5440be7b
Java
AKBang/javaProject
/DateApi/src/XingZuoServlet.java
GB18030
1,817
2.40625
2
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; /** * ѯ */ @WebServlet("/XingZuoServlet") public class XingZuoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String consName = request.getParameter("consName");// String type = request.getParameter("type");//ʱ䷶Χ System.out.println(consName); System.out.println(type); consName = URLEncoder.encode(consName, "utf-8"); System.out.println("consName=" + consName); System.out.println("type=" + type); HttpClient httpClient = new HttpClient(); String url = "http://api.avatardata.cn/Constellation/Query?key=df810f5f01d048cd9f893b6b02fc4411&consName=" + consName + "&type=" + type; GetMethod getMethod = new GetMethod(url); int status = httpClient.executeMethod(getMethod); if (status != 200) { System.out.println("," + status); return; } String result = getMethod.getResponseBodyAsString(); System.out.println(result); out.print(result); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
24eba73d4298088536f11de5bc4328e98e5b6dd5
Java
kafilamedia/kafila-catalog-app
/app/src/main/java/id/sch/kafila/catalog/activities/fragments/FasilitasFragment.java
UTF-8
2,372
2.0625
2
[]
no_license
package id.sch.kafila.catalog.activities.fragments; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import java.util.ArrayList; import java.util.List; import id.sch.kafila.catalog.R; import id.sch.kafila.catalog.components.ImageLabel; import id.sch.kafila.catalog.components.adapters.CustomExpandableListAdapter; import id.sch.kafila.catalog.contents.Dimension; import id.sch.kafila.catalog.models.ListChildInfo; import id.sch.kafila.catalog.models.ListGroupInfo; public class FasilitasFragment extends BaseFragment { private View view; private List<ImageLabel> imageLabels = new ArrayList<>(); public FasilitasFragment(){ } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_fasilitas, container, false); // listViewUmum.getLayoutParams().width = Dimension.getScreenHeight(view.getContext()); // listViewUmum.requestLayout(); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { initComponents(); adjustComponent(); super.onViewCreated(view, savedInstanceState); } private void adjustComponent() { for (ImageLabel imageLabel : imageLabels) { imageLabel.setParentActivity(getActivity()); imageLabel.initEvents(); } } private void initComponents() { addImageLabel(R.id.fasilitas_1); addImageLabel(R.id.fasilitas_2); addImageLabel(R.id.fasilitas_3); addImageLabel(R.id.fasilitas_4); addImageLabel(R.id.fasilitas_5); addImageLabel(R.id.fasilitas_6); } private void addImageLabel(int id) { imageLabels.add(view.findViewById(id)); } private static void setListViewAdapters(Context context, ExpandableListView listView, ArrayList<ListGroupInfo> list){ CustomExpandableListAdapter adapter = new CustomExpandableListAdapter(context, list, listView); listView.setAdapter(adapter); } }
true
5e3ef20b2af7decc1b27a67c469e842c8f865de1
Java
michaloles/FXTrading
/src/main/java/com/olesm/trading/fxtrading/model/Option.java
UTF-8
816
1.984375
2
[]
no_license
package com.olesm.trading.fxtrading.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.math.BigDecimal; import java.util.Date; @Data public class Option extends Trade{ private OptionStyle style; private OptionStrategy strategy; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") private Date deliveryDate; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") private Date expiryDate; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") private Date excerciseStartDate; private String payCcy; private BigDecimal premium; private String premiumCcy; private String premiumType; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") private Date premiumDate; }
true
d8f82a7684b7a47e9699276ec1cd81bde836b97c
Java
joon3007/web_practice
/day11/src/com/koreait/jsons/JSON_test.java
UTF-8
1,279
2.859375
3
[]
no_license
package com.koreait.jsons; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JSON_test { public String json; public void jsonAdd() { JSONObject jObj_in = new JSONObject(); JSONObject jObj_out = new JSONObject(); jObj_in.put("name", "김휘준"); jObj_in.put("gender", "남자"); jObj_in.put("nation", "Republic of Korea"); jObj_out.put("in", jObj_in); json = jObj_out.toJSONString(); System.out.println(json); } public static void main(String[] args) { JSON_test j_test = new JSON_test(); JSONParser p = new JSONParser(); j_test.jsonAdd(); JSONObject json_obj = null; JSONObject result_obj = null; String name = null; String gender = null; String nation = null; try { json_obj = (JSONObject)p.parse(j_test.json); result_obj = (JSONObject)json_obj.get("in"); name = (String)result_obj.get("name"); gender = (String)result_obj.get("gender"); nation = (String)result_obj.get("nation"); System.out.println("이름 : "+ name); System.out.println("성별 : "+ gender); System.out.println("나라 : "+ nation); } catch (ParseException e) { e.printStackTrace(); System.out.println("파싱 오류"); } } }
true
327bc9ed05dc8fb7087d5c547a5bb6824973828e
Java
jorgenfalk/kvsrv
/src/main/java/com/jorgen/Server.java
UTF-8
1,822
2.34375
2
[]
no_license
package com.jorgen; import com.jorgen.cmd.CommandDecoder; import com.jorgen.cmd.CommandHandler; import com.jorgen.store.KvStore; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * */ public class Server { private final KvStore kvStore; public Server(KvStore kvStore) { this.kvStore = kvStore; } void run(final int port, int threads) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(threads); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new CommandDecoder(), // Hard coded => hard to test, but only part of server setup. new CommandHandler(kvStore) ); } }); b.bind(port).sync().channel().closeFuture().await(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); kvStore.close(); } } }
true
2b46bdeb4d718174cea279099a9dfcd31df94b23
Java
azureblue/lichess-bot
/src/kk/lichess/net/pojo/Player.java
UTF-8
927
2.0625
2
[]
no_license
package kk.lichess.net.pojo; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class Player { @JsonProperty("id") private String id; @JsonProperty("name") private String name; @JsonProperty("provisional") private Boolean provisional; @JsonProperty("rating") private Integer rating; @JsonProperty("title") private String title; @JsonProperty("id") public String getId() { return id; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("provisional") public Boolean getProvisional() { return provisional; } @JsonProperty("rating") public Integer getRating() { return rating; } @JsonProperty("title") public String getTitle() { return title; } }
true
be9192ff73dd619d1daadf87207f8904a370b41a
Java
igbopie/project-mark-android
/app/src/main/java/as/mark/android/LocationSubscriptionManager.java
UTF-8
314
1.6875
2
[]
no_license
package as.mark.android; import com.google.android.gms.location.LocationListener; /** * Created by igbopie on 10/10/14. */ public interface LocationSubscriptionManager { public void subscribeLocationUpdates(LocationListener ll); public void removeSubscriptionLocationUpdates(LocationListener ll); }
true
304ca5bfc30057be1a1e288ffcb2be9eb01eb749
Java
K1ng9/SampleTwitterObserveTags
/app/src/main/java/com/example/vladkliuchak/sampleapp/data/DataBaseUsageManager.java
UTF-8
3,309
2.265625
2
[]
no_license
package com.example.vladkliuchak.sampleapp.data; import com.example.vladkliuchak.sampleapp.data.data_tables.TweetDBTable; import com.example.vladkliuchak.sampleapp.data.data_tables.UserDBTable; import com.example.vladkliuchak.sampleapp.data.model.TweetUiModel; import com.example.vladkliuchak.sampleapp.data.model.UserUiModel; import com.pushtorefresh.storio.sqlite.StorIOSQLite; import com.pushtorefresh.storio.sqlite.operations.put.PutResult; import com.pushtorefresh.storio.sqlite.queries.Query; import java.util.List; import javax.inject.Inject; import rx.Observable; /** * Created by Vlad Kliuchak on 01.10.17. */ public class DataBaseUsageManager { private final StorIOSQLite storIOSQLite; @Inject DataBaseUsageManager(StorIOSQLite storIOSQLite) { this.storIOSQLite = storIOSQLite; } public Observable<List<TweetUiModel>> getTweets() { return storIOSQLite .get() .listOfObjects(TweetUiModel.class) .withQuery( Query.builder() .table(TweetDBTable.Entry.TABLE_NAME) .orderBy(TweetDBTable.Entry.COLUMN_CREATED_AT) .build()) .prepare() .asRxObservable(); } public Observable<List<TweetUiModel>> getNotSyncTweets() { return storIOSQLite .get() .listOfObjects(TweetUiModel.class) .withQuery(Query.builder().table(TweetDBTable.Entry.TABLE_NAME) .where(TweetDBTable.Entry.COLUMN_IS_TWEET_SYNC +" = ?") .whereArgs(0) // 0 it's false .build()) .prepare() .asRxObservable(); } public UserUiModel getUserById(String userId) { return storIOSQLite .get() .object(UserUiModel.class) .withQuery( Query.builder() .table(UserDBTable.Entry.TABLE_NAME) .orderBy(UserDBTable.Entry.COLUMN_USER_ID) .where(UserDBTable.Entry.COLUMN_USER_ID + " = ?") .whereArgs(userId) .build()) .prepare() .executeAsBlocking(); } public void addOrUpdateTweets(List<TweetUiModel> tweetUiModels) { storIOSQLite .put() .objects(tweetUiModels) .prepare() .executeAsBlocking(); } public void addOrUpdateUsers(List<UserUiModel> userUiModels) { storIOSQLite .put() .objects(userUiModels) .prepare() .executeAsBlocking(); } public Observable<PutResult> addOrUpdateTweetObservable(TweetUiModel tweetUiModel) { return storIOSQLite .put() .object(tweetUiModel) .prepare() .asRxObservable(); } public void addOrUpdateTweetBlock(TweetUiModel tweetUiModel) { storIOSQLite .put() .object(tweetUiModel) .prepare() .executeAsBlocking(); } }
true
0373f7d7ade402ff6d531d25ec491a019e84e693
Java
rizikra/TugasAkhirCSR
/app/src/main/java/com/rizik/training/instamate/Model/UserData.java
UTF-8
1,231
2.53125
3
[]
no_license
package com.rizik.training.instamate.Model; public class UserData { private String userId; private String username; private String fullname; private String bio; private String imageUrl; public UserData(){ } public UserData(String userId, String username, String fullname, String bio, String imageUrl) { this.userId = userId; this.username = username; this.fullname = fullname; this.bio = bio; this.imageUrl = imageUrl; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
true
5d097b9750070f96e659ba24d92c5e6d75ce7b21
Java
MetalTurtle18/PeriodicTableApp
/src/main/java/io/github/metalturtle18/periodictableapp/listeners/SongButtonListener.java
UTF-8
1,901
3.078125
3
[]
no_license
package io.github.metalturtle18.periodictableapp.listeners; import javax.sound.sampled.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; /** * This class is a listener for the button to play the periodic table of elements song */ public class SongButtonListener implements ActionListener, LineListener { private boolean isPlaying = false; private Clip clip; public SongButtonListener() { initializeAudioPlayer(); } /** * This method creates the audio player from scratch without starting it */ private void initializeAudioPlayer() { try { @SuppressWarnings("ConstantConditions") AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(getClass().getResource("/song.wav").getFile()).getAbsoluteFile()); clip = AudioSystem.getClip(); clip.open(inputStream); clip.addLineListener(this); // Add a listener for when the track finishes playing } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { e.printStackTrace(); } } /** * When the button is pressed on the main page, call this method * * @param ae action event */ @Override public void actionPerformed(ActionEvent ae) { // If it is playing, stop playing; if not, start playing if (isPlaying) { clip.close(); initializeAudioPlayer(); isPlaying = false; } else { clip.start(); isPlaying = true; } } /** * This makes the button play the music again after it ends even if it hadn't been stopped */ @Override public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP && isPlaying) actionPerformed(null); } }
true
1cee5fbdc4aec8b245c9b2c2262388cd27fd5f5d
Java
kangdizhang/WMS
/WMS-MVN/src/main/java/com/ectrip/dao/system/menu/MenuDao.java
UTF-8
1,157
1.9375
2
[]
no_license
package com.ectrip.dao.system.menu; import com.ectrip.entity.system.Menu; import com.ectrip.util.PageData; import org.springframework.stereotype.Repository; import java.util.List; /**说明:MenuService 菜单处理接口 * @author ectrip 313596790 */ @Repository("MenuMapper") public interface MenuDao { /** * 获取所有子菜单 * @param parentId * @return * @throws Exception */ public List<Menu> listSubMenuByParentId(String parentId)throws Exception; /** * @param pd * @return * @throws Exception */ public PageData getMenuById(PageData pd) throws Exception; /** * @param menu * @throws Exception */ public void insertMenu(Menu menu) throws Exception; /** * @param pd * @return * @throws Exception */ public PageData findMaxId(PageData pd) throws Exception; /** * @param MENU_ID * @throws Exception */ public void deleteMenuById(String MENU_ID) throws Exception; /** * @param menu * @throws Exception */ public void updateMenu(Menu menu) throws Exception; /** * @param pd * @return * @throws Exception */ public PageData editicon(PageData pd) throws Exception; }
true
fc09aa036ce1af7ef6787d07db00cbf7fd9e8f1b
Java
haoyu-liu/crack_WeMo
/wemo_apk/java_code/net/lingala/zip4j/util/InternalZipConstants.java
UTF-8
4,331
1.539063
2
[]
no_license
package net.lingala.zip4j.util; public abstract interface InternalZipConstants { public static final int AESSIG = 39169; public static final int AES_AUTH_LENGTH = 10; public static final int AES_BLOCK_SIZE = 16; public static final long ARCEXTDATREC = 134630224L; public static final int BUFF_SIZE = 4096; public static final int CENATT = 36; public static final int CENATX = 38; public static final int CENCOM = 32; public static final int CENCRC = 16; public static final int CENDSK = 34; public static final int CENEXT = 30; public static final int CENFLG = 8; public static final int CENHDR = 46; public static final int CENHOW = 10; public static final int CENLEN = 24; public static final int CENNAM = 28; public static final int CENOFF = 42; public static final long CENSIG = 33639248L; public static final int CENSIZ = 20; public static final int CENTIM = 12; public static final int CENVEM = 4; public static final int CENVER = 6; public static final String CHARSET_COMMENTS_DEFAULT = "windows-1254"; public static final String CHARSET_CP850 = "Cp850"; public static final String CHARSET_DEFAULT = System.getProperty("file.encoding"); public static final String CHARSET_UTF8 = "UTF8"; public static final long DIGSIG = 84233040L; public static final int ENDCOM = 20; public static final int ENDHDR = 22; public static final int ENDOFF = 16; public static final long ENDSIG = 101010256L; public static final int ENDSIZ = 12; public static final int ENDSUB = 8; public static final int ENDTOT = 10; public static final int EXTCRC = 4; public static final int EXTHDR = 16; public static final int EXTLEN = 12; public static final int EXTRAFIELDZIP64LENGTH = 1; public static final long EXTSIG = 134695760L; public static final int EXTSIZ = 8; public static final int FILE_MODE_ARCHIVE = 32; public static final int FILE_MODE_HIDDEN = 2; public static final int FILE_MODE_HIDDEN_ARCHIVE = 34; public static final int FILE_MODE_NONE = 0; public static final int FILE_MODE_READ_ONLY = 1; public static final int FILE_MODE_READ_ONLY_ARCHIVE = 33; public static final int FILE_MODE_READ_ONLY_HIDDEN = 3; public static final int FILE_MODE_READ_ONLY_HIDDEN_ARCHIVE = 35; public static final int FILE_MODE_SYSTEM = 38; public static final String FILE_SEPARATOR = System.getProperty("file.separator"); public static final int FOLDER_MODE_ARCHIVE = 48; public static final int FOLDER_MODE_HIDDEN = 18; public static final int FOLDER_MODE_HIDDEN_ARCHIVE = 50; public static final int FOLDER_MODE_NONE = 16; public static final int LIST_TYPE_FILE = 1; public static final int LIST_TYPE_STRING = 2; public static final int LOCCRC = 14; public static final int LOCEXT = 28; public static final int LOCFLG = 6; public static final int LOCHDR = 30; public static final int LOCHOW = 8; public static final int LOCLEN = 22; public static final int LOCNAM = 26; public static final long LOCSIG = 67324752L; public static final int LOCSIZ = 18; public static final int LOCTIM = 10; public static final int LOCVER = 4; public static final int MAX_ALLOWED_ZIP_COMMENT_LENGTH = 65535; public static final int MIN_SPLIT_LENGTH = 65536; public static final int MODE_UNZIP = 2; public static final int MODE_ZIP = 1; public static final String OFFSET_CENTRAL_DIR = "offsetCentralDir"; public static final String READ_MODE = "r"; public static final long SPLITSIG = 134695760L; public static final int STD_DEC_HDR_SIZE = 12; public static final String THREAD_NAME = "Zip4j"; public static final int UFT8_NAMES_FLAG = 2048; public static final int UPDATE_LFH_COMP_SIZE = 18; public static final int UPDATE_LFH_CRC = 14; public static final int UPDATE_LFH_UNCOMP_SIZE = 22; public static final String VERSION = "1.3.2"; public static final String WRITE_MODE = "rw"; public static final long ZIP64ENDCENDIRLOC = 117853008L; public static final long ZIP64ENDCENDIRREC = 101075792L; public static final long ZIP_64_LIMIT = 4294967295L; public static final String ZIP_FILE_SEPARATOR = "/"; } /* Location: /root/Documents/wemo_apk/classes-dex2jar.jar!/net/lingala/zip4j/util/InternalZipConstants.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
811dfd5e239ab4e2e7d71a35191428b8eb4c44de
Java
SupriseMF/algo
/prac/src/pac1/uniquePaths.java
UTF-8
2,543
4.15625
4
[ "Apache-2.0" ]
permissive
package pac1; public class uniquePaths { /** * 一个机器人位于一个 m x n网格的左上角 (起始点在下图中标记为 “Start” )。 * * 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。 * * 问总共有多少条不同的路径? * * 输入:m = 3, n = 2 * 输出:3 * 解释: * 从左上角开始,总共有 3 条路径可以到达右下角。 * 1. 向右 -> 向下 -> 向下 * 2. 向下 -> 向下 -> 向右 * 3. 向下 -> 向右 -> 向下 * * @param m * @param n * @return */ public static int uniquePaths(int m, int n) { /** * 1、递归实现 * 时间、空间复杂度高 * */ // 结束条件 if (m == 1 || n == 1) { return 1; } return uniquePaths(m - 1, n) + uniquePaths(m, n - 1); } public static int uniquePaths1(int m, int n) { /** * 2、动态规划,重复利用较小的结果 * 时间复杂度O(N*M) * 空间复杂度O(N*M) * 当i = 0,或j = 0不符合题意,忽略 */ int[][] f = new int[m][n]; for (int i = 0; i < m; i++) { f[i][0] = 1; } for (int j = 0; j < n; j++) { f[0][j] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { f[i][j] = f[i - 1][j] + f[i][j - 1]; } } // 最终位置即ans return f[m - 1][n - 1]; } public static int uniquePaths2(int m, int n) { /** * 3、组合数学 * 从起点到终点,其中移动行数为(m -1)次,移动列数为(n -1)次,一共要移动(m - 1 + n - 1)次 * 因此,组合数学: * (m - 1) (m + n − 2)(m + n − 3) ... n (m + n − 2)! * C = ———————————————————————————— = ———————————————— * ( m + n - 2) (m - 1)! (m - 1)!(n - 1)! */ long ans = 1; // 计算次数:1 ... (m - 1) for (int x = n, y = 1; y < m; x++, y++) { ans = ans * x / y; } return (int) ans; } public static void main(String[] args) { System.out.println(uniquePaths(50, 100)); } }
true
7ef6e30841e00702270e761a5edaa6f1efe79a3e
Java
juan-ruiz/sudokuARResolver
/ARSudokuSolver/src/com/sudoku/AboutInfo.java
UTF-8
265
1.835938
2
[]
no_license
package com.sudoku; import android.app.Activity; import android.os.Bundle; public class AboutInfo extends Activity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.menu_about); } }
true
d6c62ee76949f394c7cea9ed5cb55f0e0b75dfe7
Java
STAMP-project/dspot-experiments
/benchmark/test/org/apache/kafka/connect/data/ValuesTest.java
UTF-8
17,673
2.375
2
[]
no_license
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.data; import Schema.BOOLEAN_SCHEMA; import Schema.INT16_SCHEMA; import Schema.INT32_SCHEMA; import Schema.OPTIONAL_STRING_SCHEMA; import Schema.STRING_SCHEMA; import Time.SCHEMA; import Type.STRING; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.kafka.connect.errors.DataException; import org.junit.Assert; import org.junit.Test; public class ValuesTest { private static final long MILLIS_PER_DAY = ((24 * 60) * 60) * 1000; private static final Map<String, String> STRING_MAP = new LinkedHashMap<>(); private static final Schema STRING_MAP_SCHEMA = SchemaBuilder.map(STRING_SCHEMA, STRING_SCHEMA).schema(); private static final Map<String, Short> STRING_SHORT_MAP = new LinkedHashMap<>(); private static final Schema STRING_SHORT_MAP_SCHEMA = SchemaBuilder.map(STRING_SCHEMA, INT16_SCHEMA).schema(); private static final Map<String, Integer> STRING_INT_MAP = new LinkedHashMap<>(); private static final Schema STRING_INT_MAP_SCHEMA = SchemaBuilder.map(STRING_SCHEMA, INT32_SCHEMA).schema(); private static final List<Integer> INT_LIST = new ArrayList<>(); private static final Schema INT_LIST_SCHEMA = SchemaBuilder.array(INT32_SCHEMA).schema(); private static final List<String> STRING_LIST = new ArrayList<>(); private static final Schema STRING_LIST_SCHEMA = SchemaBuilder.array(STRING_SCHEMA).schema(); static { ValuesTest.STRING_MAP.put("foo", "123"); ValuesTest.STRING_MAP.put("bar", "baz"); ValuesTest.STRING_SHORT_MAP.put("foo", ((short) (12345))); ValuesTest.STRING_SHORT_MAP.put("bar", ((short) (0))); ValuesTest.STRING_SHORT_MAP.put("baz", ((short) (-4321))); ValuesTest.STRING_INT_MAP.put("foo", 1234567890); ValuesTest.STRING_INT_MAP.put("bar", 0); ValuesTest.STRING_INT_MAP.put("baz", (-987654321)); ValuesTest.STRING_LIST.add("foo"); ValuesTest.STRING_LIST.add("bar"); ValuesTest.INT_LIST.add(1234567890); ValuesTest.INT_LIST.add((-987654321)); } @Test public void shouldEscapeStringsWithEmbeddedQuotesAndBackslashes() { String original = "three\"blind\\\"mice"; String expected = "three\\\"blind\\\\\\\"mice"; Assert.assertEquals(expected, Values.escape(original)); } @Test public void shouldConvertNullValue() { assertRoundTrip(STRING_SCHEMA, STRING_SCHEMA, null); assertRoundTrip(OPTIONAL_STRING_SCHEMA, STRING_SCHEMA, null); } @Test public void shouldConvertBooleanValues() { assertRoundTrip(BOOLEAN_SCHEMA, BOOLEAN_SCHEMA, Boolean.FALSE); SchemaAndValue resultFalse = roundTrip(BOOLEAN_SCHEMA, "false"); Assert.assertEquals(BOOLEAN_SCHEMA, resultFalse.schema()); Assert.assertEquals(Boolean.FALSE, resultFalse.value()); assertRoundTrip(BOOLEAN_SCHEMA, BOOLEAN_SCHEMA, Boolean.TRUE); SchemaAndValue resultTrue = roundTrip(BOOLEAN_SCHEMA, "true"); Assert.assertEquals(BOOLEAN_SCHEMA, resultTrue.schema()); Assert.assertEquals(Boolean.TRUE, resultTrue.value()); } @Test(expected = DataException.class) public void shouldFailToParseInvalidBooleanValueString() { Values.convertToBoolean(STRING_SCHEMA, "\"green\""); } @Test public void shouldConvertSimpleString() { assertRoundTrip(STRING_SCHEMA, "simple"); } @Test public void shouldConvertEmptyString() { assertRoundTrip(STRING_SCHEMA, ""); } @Test public void shouldConvertStringWithQuotesAndOtherDelimiterCharacters() { assertRoundTrip(STRING_SCHEMA, STRING_SCHEMA, "three\"blind\\\"mice"); assertRoundTrip(STRING_SCHEMA, STRING_SCHEMA, "string with delimiters: <>?,./\\=+-!@#$%^&*(){}[]|;\':"); } @Test public void shouldConvertMapWithStringKeys() { assertRoundTrip(ValuesTest.STRING_MAP_SCHEMA, ValuesTest.STRING_MAP_SCHEMA, ValuesTest.STRING_MAP); } @Test public void shouldParseStringOfMapWithStringValuesWithoutWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_MAP_SCHEMA, "{\"foo\":\"123\",\"bar\":\"baz\"}"); Assert.assertEquals(ValuesTest.STRING_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_MAP, result.value()); } @Test public void shouldParseStringOfMapWithStringValuesWithWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_MAP_SCHEMA, "{ \"foo\" : \"123\", \n\"bar\" : \"baz\" } "); Assert.assertEquals(ValuesTest.STRING_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_MAP, result.value()); } @Test public void shouldConvertMapWithStringKeysAndShortValues() { assertRoundTrip(ValuesTest.STRING_SHORT_MAP_SCHEMA, ValuesTest.STRING_SHORT_MAP_SCHEMA, ValuesTest.STRING_SHORT_MAP); } @Test public void shouldParseStringOfMapWithShortValuesWithoutWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_SHORT_MAP_SCHEMA, "{\"foo\":12345,\"bar\":0,\"baz\":-4321}"); Assert.assertEquals(ValuesTest.STRING_SHORT_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_SHORT_MAP, result.value()); } @Test public void shouldParseStringOfMapWithShortValuesWithWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_SHORT_MAP_SCHEMA, " { \"foo\" : 12345 , \"bar\" : 0, \"baz\" : -4321 } "); Assert.assertEquals(ValuesTest.STRING_SHORT_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_SHORT_MAP, result.value()); } @Test public void shouldConvertMapWithStringKeysAndIntegerValues() { assertRoundTrip(ValuesTest.STRING_INT_MAP_SCHEMA, ValuesTest.STRING_INT_MAP_SCHEMA, ValuesTest.STRING_INT_MAP); } @Test public void shouldParseStringOfMapWithIntValuesWithoutWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_INT_MAP_SCHEMA, "{\"foo\":1234567890,\"bar\":0,\"baz\":-987654321}"); Assert.assertEquals(ValuesTest.STRING_INT_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_INT_MAP, result.value()); } @Test public void shouldParseStringOfMapWithIntValuesWithWhitespaceAsMap() { SchemaAndValue result = roundTrip(ValuesTest.STRING_INT_MAP_SCHEMA, " { \"foo\" : 1234567890 , \"bar\" : 0, \"baz\" : -987654321 } "); Assert.assertEquals(ValuesTest.STRING_INT_MAP_SCHEMA, result.schema()); Assert.assertEquals(ValuesTest.STRING_INT_MAP, result.value()); } @Test public void shouldConvertListWithStringValues() { assertRoundTrip(ValuesTest.STRING_LIST_SCHEMA, ValuesTest.STRING_LIST_SCHEMA, ValuesTest.STRING_LIST); } @Test public void shouldConvertListWithIntegerValues() { assertRoundTrip(ValuesTest.INT_LIST_SCHEMA, ValuesTest.INT_LIST_SCHEMA, ValuesTest.INT_LIST); } /** * The parsed array has byte values and one int value, so we should return list with single unified type of integers. */ @Test public void shouldConvertStringOfListWithOnlyNumericElementTypesIntoListOfLargestNumericType() { int thirdValue = (Short.MAX_VALUE) + 1; List<?> list = Values.convertToList(STRING_SCHEMA, (("[1, 2, " + thirdValue) + "]")); Assert.assertEquals(3, list.size()); Assert.assertEquals(1, ((Number) (list.get(0))).intValue()); Assert.assertEquals(2, ((Number) (list.get(1))).intValue()); Assert.assertEquals(thirdValue, ((Number) (list.get(2))).intValue()); } /** * The parsed array has byte values and one int value, so we should return list with single unified type of integers. */ @Test public void shouldConvertStringOfListWithMixedElementTypesIntoListWithDifferentElementTypes() { String str = "[1, 2, \"three\"]"; List<?> list = Values.convertToList(STRING_SCHEMA, str); Assert.assertEquals(3, list.size()); Assert.assertEquals(1, ((Number) (list.get(0))).intValue()); Assert.assertEquals(2, ((Number) (list.get(1))).intValue()); Assert.assertEquals("three", list.get(2)); } /** * We parse into different element types, but cannot infer a common element schema. */ @Test public void shouldParseStringListWithMultipleElementTypesAndReturnListWithNoSchema() { String str = "[1, 2, 3, \"four\"]"; SchemaAndValue result = Values.parseString(str); Assert.assertNull(result.schema()); List<?> list = ((List<?>) (result.value())); Assert.assertEquals(4, list.size()); Assert.assertEquals(1, ((Number) (list.get(0))).intValue()); Assert.assertEquals(2, ((Number) (list.get(1))).intValue()); Assert.assertEquals(3, ((Number) (list.get(2))).intValue()); Assert.assertEquals("four", list.get(3)); } /** * We can't infer or successfully parse into a different type, so this returns the same string. */ @Test public void shouldParseStringListWithExtraDelimitersAndReturnString() { String str = "[1, 2, 3,,,]"; SchemaAndValue result = Values.parseString(str); Assert.assertEquals(STRING, result.schema().type()); Assert.assertEquals(str, result.value()); } /** * This is technically invalid JSON, and we don't want to simply ignore the blank elements. */ @Test(expected = DataException.class) public void shouldFailToConvertToListFromStringWithExtraDelimiters() { Values.convertToList(STRING_SCHEMA, "[1, 2, 3,,,]"); } /** * Schema of type ARRAY requires a schema for the values, but Connect has no union or "any" schema type. * Therefore, we can't represent this. */ @Test(expected = DataException.class) public void shouldFailToConvertToListFromStringWithNonCommonElementTypeAndBlankElement() { Values.convertToList(STRING_SCHEMA, "[1, 2, 3, \"four\",,,]"); } /** * This is technically invalid JSON, and we don't want to simply ignore the blank entry. */ @Test(expected = DataException.class) public void shouldFailToParseStringOfMapWithIntValuesWithBlankEntry() { Values.convertToList(STRING_SCHEMA, " { \"foo\" : 1234567890 ,, \"bar\" : 0, \"baz\" : -987654321 } "); } /** * This is technically invalid JSON, and we don't want to simply ignore the malformed entry. */ @Test(expected = DataException.class) public void shouldFailToParseStringOfMalformedMap() { Values.convertToList(STRING_SCHEMA, " { \"foo\" : 1234567890 , \"a\", \"bar\" : 0, \"baz\" : -987654321 } "); } /** * This is technically invalid JSON, and we don't want to simply ignore the blank entries. */ @Test(expected = DataException.class) public void shouldFailToParseStringOfMapWithIntValuesWithOnlyBlankEntries() { Values.convertToList(STRING_SCHEMA, " { ,, , , } "); } /** * This is technically invalid JSON, and we don't want to simply ignore the blank entry. */ @Test(expected = DataException.class) public void shouldFailToParseStringOfMapWithIntValuesWithBlankEntries() { Values.convertToList(STRING_SCHEMA, " { \"foo\" : \"1234567890\" ,, \"bar\" : \"0\", \"baz\" : \"boz\" } "); } /** * Schema for Map requires a schema for key and value, but we have no key or value and Connect has no "any" type */ @Test(expected = DataException.class) public void shouldFailToParseStringOfEmptyMap() { Values.convertToList(STRING_SCHEMA, " { } "); } @Test public void shouldParseStringsWithoutDelimiters() { // assertParsed(""); assertParsed(" "); assertParsed("simple"); assertParsed("simple string"); assertParsed("simple \n\t\bstring"); assertParsed("'simple' string"); assertParsed("si\\mple"); assertParsed("si\\\\mple"); } @Test public void shouldParseStringsWithEscapedDelimiters() { assertParsed("si\\\"mple"); assertParsed("si\\{mple"); assertParsed("si\\}mple"); assertParsed("si\\]mple"); assertParsed("si\\[mple"); assertParsed("si\\:mple"); assertParsed("si\\,mple"); } @Test public void shouldParseStringsWithSingleDelimiter() { assertParsed("a{b", "a", "{", "b"); assertParsed("a}b", "a", "}", "b"); assertParsed("a[b", "a", "[", "b"); assertParsed("a]b", "a", "]", "b"); assertParsed("a:b", "a", ":", "b"); assertParsed("a,b", "a", ",", "b"); assertParsed("a\"b", "a", "\"", "b"); assertParsed("{b", "{", "b"); assertParsed("}b", "}", "b"); assertParsed("[b", "[", "b"); assertParsed("]b", "]", "b"); assertParsed(":b", ":", "b"); assertParsed(",b", ",", "b"); assertParsed("\"b", "\"", "b"); assertParsed("{", "{"); assertParsed("}", "}"); assertParsed("[", "["); assertParsed("]", "]"); assertParsed(":", ":"); assertParsed(",", ","); assertParsed("\"", "\""); } @Test public void shouldParseStringsWithMultipleDelimiters() { assertParsed("\"simple\" string", "\"", "simple", "\"", " string"); assertParsed("a{bc}d", "a", "{", "bc", "}", "d"); assertParsed("a { b c } d", "a ", "{", " b c ", "}", " d"); assertParsed("a { b c } d", "a ", "{", " b c ", "}", " d"); } @Test public void shouldConvertTimeValues() { Date current = new Date(); long currentMillis = (current.getTime()) % (ValuesTest.MILLIS_PER_DAY); // java.util.Date - just copy Date t1 = Values.convertToTime(SCHEMA, current); Assert.assertEquals(current, t1); // java.util.Date as a Timestamp - discard the date and keep just day's milliseconds t1 = Values.convertToTime(Timestamp.SCHEMA, current); Assert.assertEquals(new Date(currentMillis), t1); // ISO8601 strings - currently broken because tokenization breaks at colon // Millis as string Date t3 = Values.convertToTime(SCHEMA, Long.toString(currentMillis)); Assert.assertEquals(currentMillis, t3.getTime()); // Millis as long Date t4 = Values.convertToTime(SCHEMA, currentMillis); Assert.assertEquals(currentMillis, t4.getTime()); } @Test public void shouldConvertDateValues() { Date current = new Date(); long currentMillis = (current.getTime()) % (ValuesTest.MILLIS_PER_DAY); long days = (current.getTime()) / (ValuesTest.MILLIS_PER_DAY); // java.util.Date - just copy Date d1 = Values.convertToDate(Date.SCHEMA, current); Assert.assertEquals(current, d1); // java.util.Date as a Timestamp - discard the day's milliseconds and keep the date Date currentDate = new Date(((current.getTime()) - currentMillis)); d1 = Values.convertToDate(Timestamp.SCHEMA, currentDate); Assert.assertEquals(currentDate, d1); // ISO8601 strings - currently broken because tokenization breaks at colon // Days as string Date d3 = Values.convertToDate(Date.SCHEMA, Long.toString(days)); Assert.assertEquals(currentDate, d3); // Days as long Date d4 = Values.convertToDate(Date.SCHEMA, days); Assert.assertEquals(currentDate, d4); } @Test public void shouldConvertTimestampValues() { Date current = new Date(); long currentMillis = (current.getTime()) % (ValuesTest.MILLIS_PER_DAY); // java.util.Date - just copy Date ts1 = Values.convertToTimestamp(Timestamp.SCHEMA, current); Assert.assertEquals(current, ts1); // java.util.Date as a Timestamp - discard the day's milliseconds and keep the date Date currentDate = new Date(((current.getTime()) - currentMillis)); ts1 = Values.convertToTimestamp(Date.SCHEMA, currentDate); Assert.assertEquals(currentDate, ts1); // java.util.Date as a Time - discard the date and keep the day's milliseconds ts1 = Values.convertToTimestamp(SCHEMA, currentMillis); Assert.assertEquals(new Date(currentMillis), ts1); // ISO8601 strings - currently broken because tokenization breaks at colon // Millis as string Date ts3 = Values.convertToTimestamp(Timestamp.SCHEMA, Long.toString(current.getTime())); Assert.assertEquals(current, ts3); // Millis as long Date ts4 = Values.convertToTimestamp(Timestamp.SCHEMA, current.getTime()); Assert.assertEquals(current, ts4); } }
true
b2e3304d93bf8895cfa595e940ec66bd82b1c53d
Java
igouss/aggress
/storage/src/main/java/com/naxsoft/storage/redis/RedisDatabase.java
UTF-8
5,111
2.25
2
[]
no_license
package com.naxsoft.storage.redis; import com.lambdaworks.redis.RedisClient; import com.lambdaworks.redis.RedisURI; import com.lambdaworks.redis.api.StatefulRedisConnection; import com.lambdaworks.redis.event.metrics.CommandLatencyEvent; import com.lambdaworks.redis.metrics.DefaultCommandLatencyCollectorOptions; import com.lambdaworks.redis.resource.ClientResources; import com.lambdaworks.redis.resource.DefaultClientResources; import com.naxsoft.encoders.Encoder; import com.naxsoft.encoders.ProductEntityEncoder; import com.naxsoft.encoders.WebPageEntityEncoder; import com.naxsoft.entity.ProductEntity; import com.naxsoft.entity.WebPageEntity; import com.naxsoft.storage.Persistent; import com.naxsoft.utils.AppProperties; import com.naxsoft.utils.PropertyNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.schedulers.Schedulers; import javax.inject.Singleton; import java.util.Objects; @Singleton public class RedisDatabase implements Persistent { private final static Logger LOGGER = LoggerFactory.getLogger(RedisDatabase.class); private static final int BATCH_SIZE = 20; private final ClientResources res; private final RedisClient redisClient; // private StatefulRedisPubSubConnection<String, String> pubSub; // private RedisConnectionPool<RedisAsyncCommands<String, String>> pool; private final StatefulRedisConnection<String, String> connection; public RedisDatabase() throws PropertyNotFoundException { this(AppProperties.getProperty("redisHost"), Integer.parseInt(AppProperties.getProperty("redisPort"))); } private RedisDatabase(String host, int port) { res = DefaultClientResources .builder() .commandLatencyCollectorOptions(DefaultCommandLatencyCollectorOptions.create()) .build(); redisClient = RedisClient.create(res, RedisURI.Builder.redis(host, port).build()); redisClient.getResources().eventBus().get() .filter(redisEvent -> redisEvent instanceof CommandLatencyEvent) .cast(CommandLatencyEvent.class) .subscribeOn(Schedulers.computation()) .subscribe( e -> LOGGER.info(e.getLatencies().toString()), err -> LOGGER.error("Failed to get command latency", err), () -> LOGGER.info("Command latency complete") ); // pubSub = redisClient.connectPubSub(); // pool = redisClient.asyncPool(); connection = redisClient.connect(); } @Override public void close() { redisClient.shutdown(); res.shutdown(); } @Override public Observable<Long> markWebPageAsParsed(WebPageEntity webPageEntity) { // if (webPageEntity == null) { // return Observable.error(new Exception("Trying to mark null WebPageEntity as parsed")); // } String source = "WebPageEntity." + webPageEntity.getType(); String destination = "WebPageEntity." + webPageEntity.getType() + ".parsed"; String member = Encoder.encode(webPageEntity); return connection.reactive().sadd(destination, member); //.doOnNext(res -> LOGGER.info("Moved rc={} from {} to {} element {}...", res, source, destination, member.substring(0, 50))); } @Override public Observable<Integer> markAllProductPagesAsIndexed() { return null; } @Override public Observable<Long> addProductPageEntry(ProductEntity productEntity) { String key = "ProductEntity"; String member = Encoder.encode(productEntity); return connection.reactive().sadd(key, member); } @Override public Observable<Long> addWebPageEntry(WebPageEntity webPageEntity) { String key = "WebPageEntity" + "." + webPageEntity.getType(); String member = Encoder.encode(webPageEntity); LOGGER.trace("adding key {} val {}", key, webPageEntity.getUrl()); return connection.reactive().sadd(key, member); } @Override public Observable<ProductEntity> getProducts() { return connection.reactive() .smembers("ProductEntity") .map(ProductEntityEncoder::decode) .filter(Objects::nonNull); } @Override public Observable<Long> getUnparsedCount(String type) { return connection.reactive().scard("WebPageEntity." + type); } @Override public Observable<WebPageEntity> getUnparsedByType(String type, Long count) { LOGGER.info("getUnparsedByType {} {}", type, count); return connection.reactive() .spop("WebPageEntity." + type, Math.min(count, BATCH_SIZE)) .map(WebPageEntityEncoder::decode) .doOnNext(val -> LOGGER.info("SPOP'ed {} {} {}", val.getType(), val.getUrl(), val.getCategory())) .filter(Objects::nonNull); } @Override public Observable<String> cleanUp(String[] tables) { return connection.reactive().flushall(); } }
true
2bd1cbf2dba24e609ce2b2b105f2c34bcbe86e89
Java
Justxyx/JavaSourceLearn
/src/test/p3/Test01.java
UTF-8
193
1.765625
2
[]
no_license
package test.p3; /** * @author xm * @version 1.0 * @date 2021/9/13 20:42 */ public class Test01 { public static void main(String[] args) { B b = new B(11, "xx","cc"); } }
true
271ae395e5417f38f235bd7d3a8f1ed8eaa847d4
Java
xiefalei0316/SpellSys
/SpellSys_Common/src/main/java/com/qfedu/common/dto/WorkOrderDto.java
UTF-8
772
1.71875
2
[]
no_license
package com.qfedu.common.dto; import lombok.Data; import java.util.Date; /** * @Description TODO * @Name WorkOrderDto * @Author Yama * @Date 2019/9/20 9:35 * @Version V1.0 */ @Data public class WorkOrderDto { private Integer wid; /** * 工单编号 */ private Integer num; /** * 店铺Id */ private Integer sid; /** * 订单状态 */ private Integer status; /** * 工单等级 */ private Integer workOrderRank; /** * 工单内容 */ private String content; /** * 问题分类 */ private Integer issueClass; /** * 操作人Id */ private Integer userId; /** * 工单状态 */ private Integer workStatus; }
true
dd66e0c4236c9a5f99d7818c96b1a024e4e8d81b
Java
msalinasicsni/first-laboratorio-v2
/laboratorio/src/main/java/ni/gob/minsa/laboratorio/web/controllers/EditarSolicitudesMxController.java
ISO-8859-1
37,344
1.8125
2
[]
no_license
package ni.gob.minsa.laboratorio.web.controllers; import com.google.gson.Gson; import com.google.gson.JsonObject; import ni.gob.minsa.laboratorio.domain.concepto.Catalogo_Lista; import ni.gob.minsa.laboratorio.domain.muestra.*; import ni.gob.minsa.laboratorio.domain.muestra.traslado.TrasladoMx; import ni.gob.minsa.laboratorio.domain.resultados.DetalleResultado; import ni.gob.minsa.laboratorio.domain.resultados.DetalleResultadoFinal; import ni.gob.minsa.laboratorio.restServices.CallRestServices; import ni.gob.minsa.laboratorio.restServices.constantes.CatalogConstants; import ni.gob.minsa.laboratorio.restServices.entidades.Catalogo; import ni.gob.minsa.laboratorio.restServices.entidades.EntidadesAdtvas; import ni.gob.minsa.laboratorio.restServices.entidades.Unidades; import ni.gob.minsa.laboratorio.service.*; import ni.gob.minsa.laboratorio.utilities.ConstantsSecurity; import ni.gob.minsa.laboratorio.utilities.DateUtil; import ni.gob.minsa.laboratorio.utilities.enumeration.HealthUnitType; import org.apache.commons.lang3.text.translate.UnicodeEscaper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.util.*; /** * Created by Miguel Salinas on 7/26/2017. * V1.0 */ @Controller @RequestMapping("editarMx") public class EditarSolicitudesMxController { private static final Logger logger = LoggerFactory.getLogger(RecepcionMxController.class); @Resource(name = "seguridadService") private SeguridadService seguridadService; @Resource(name = "catalogosService") private CatalogoService catalogosService; @Resource(name = "recepcionMxService") private RecepcionMxService recepcionMxService; @Resource(name = "trasladosService") private TrasladosService trasladosService; @Resource(name = "tomaMxService") private TomaMxService tomaMxService; @Resource(name = "ordenExamenMxService") private OrdenExamenMxService ordenExamenMxService; @Resource(name = "unidadesService") private UnidadesService unidadesService; @Resource(name = "datosSolicitudService") private DatosSolicitudService datosSolicitudService; @Resource(name = "resultadoFinalService") private ResultadoFinalService resultadoFinalService; @Resource(name = "resultadosService") private ResultadosService resultadosService; @Autowired MessageSource messageSource; /** * Mtodo que se llama al entrar a la opcin de menu "Recepcin Mx Laboratorio". Se encarga de inicializar las listas para realizar la bsqueda de envios de Mx * @param request para obtener informacin de la peticin del cliente * @return ModelAndView * @throws Exception */ @RequestMapping(value = "init", method = RequestMethod.GET) public ModelAndView initSearchLabForm(HttpServletRequest request) throws Exception { logger.debug("buscar ordenes para ordenExamen"); String urlValidacion; try { urlValidacion = seguridadService.validarLogin(request); //si la url esta vacia significa que la validacin del login fue exitosa if (urlValidacion.isEmpty()) urlValidacion = seguridadService.validarAutorizacionUsuario(request, ConstantsSecurity.SYSTEM_CODE, false); }catch (Exception e){ e.printStackTrace(); urlValidacion = "404"; } ModelAndView mav = new ModelAndView(); if (urlValidacion.isEmpty()) { List<EntidadesAdtvas> entidadesAdtvases = CallRestServices.getEntidadesAdtvas(); List<TipoMx> tipoMxList = catalogosService.getTipoMuestra(); mav.addObject("nivelCentral", true);//q todos puedan editar //seguridadService.esUsuarioNivelCentral(seguridadService.obtenerNombreUsuario())); mav.addObject("entidades",entidadesAdtvases); mav.addObject("tipoMuestra", tipoMxList); mav.setViewName("laboratorio/editarMx/searchMxLab"); }else mav.setViewName(urlValidacion); return mav; } /** * Mtodo para realizar la bsqueda de Recepcion Mx para recepcionar en laboratorio * @param filtro JSon con los datos de los filtros a aplicar en la bsqueda(Nombre Apellido, Rango Fec Toma Mx, Tipo Mx, SILAIS, unidad salud) * @return String con las Recepciones encontradas * @throws Exception */ @RequestMapping(value = "searchMxLab", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String fetchOrdersLabJson(@RequestParam(value = "strFilter", required = true) String filtro) throws Exception{ logger.info("Obteniendo las ordenes de examen pendienetes segn filtros en JSON"); FiltroMx filtroMx = jsonToFiltroMx(filtro); List<RecepcionMx> recepcionMxList = recepcionMxService.getRecepcionesByFiltro(filtroMx); return RecepcionMxToJson(recepcionMxList); } @RequestMapping(value = "override", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) protected void anularMuestra(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json; String resultado = ""; String codigoMx=null; String causaAnulacion = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF8")); json = br.readLine(); //Recuperando Json enviado desde el cliente JsonObject jsonpObject = new Gson().fromJson(json, JsonObject.class); codigoMx = jsonpObject.get("codigoMx").getAsString(); causaAnulacion = jsonpObject.get("causaAnulacion").getAsString(); DaTomaMx tomaMx = tomaMxService.getTomaMxByCodLab(codigoMx); if (tomaMx!=null) { tomaMx.setAnulada(true); tomaMx.setFechaAnulacion(new Timestamp(new Date().getTime())); tomaMxService.updateTomaMx(tomaMx); List<DaSolicitudDx> solicitudDxList = tomaMxService.getSolicitudesDxPrioridadByIdToma(tomaMx.getIdTomaMx()); for(DaSolicitudDx solicitudDx:solicitudDxList){ tomaMxService.bajaSolicitudDx(seguridadService.obtenerNombreUsuario(), solicitudDx.getIdSolicitudDx(), causaAnulacion); } }else{ throw new Exception(messageSource.getMessage("msg.tomamx.notfound",null,null)); } } catch (Exception ex) { logger.error(ex.getMessage(),ex); ex.printStackTrace(); resultado = messageSource.getMessage("msg.override.tomamx.error",null,null); resultado=resultado+". \n "+ex.getMessage(); }finally { Map<String, String> map = new HashMap<String, String>(); map.put("codigoMx",String.valueOf(codigoMx)); map.put("mensaje",resultado); String jsonResponse = new Gson().toJson(map); response.getOutputStream().write(jsonResponse.getBytes()); response.getOutputStream().close(); } } /** * Mtodo para convertir estructura Json que se recibe desde el cliente a FiltroMx para realizar bsqueda de Mx(Vigilancia) y Recepcin Mx(Laboratorio) * @param strJson String con la informacin de los filtros * @return FiltroMx * @throws Exception */ private FiltroMx jsonToFiltroMx(String strJson) throws Exception { JsonObject jObjectFiltro = new Gson().fromJson(strJson, JsonObject.class); FiltroMx filtroMx = new FiltroMx(); String nombreApellido = null; Date fechaInicioRecep = null; Date fechaFinRecep = null; String codSilais = null; String codUnidadSalud = null; String codTipoMx = null; String codigoUnicoMx = null; String codTipoSolicitud = null; String nombreSolicitud = null; if (jObjectFiltro.get("nombreApellido") != null && !jObjectFiltro.get("nombreApellido").getAsString().isEmpty()) nombreApellido = jObjectFiltro.get("nombreApellido").getAsString(); if (jObjectFiltro.get("fechaInicioRecep") != null && !jObjectFiltro.get("fechaInicioRecep").getAsString().isEmpty()) fechaInicioRecep = DateUtil.StringToDate(jObjectFiltro.get("fechaInicioRecep").getAsString() + " 00:00:00"); if (jObjectFiltro.get("fechaFinRecepcion") != null && !jObjectFiltro.get("fechaFinRecepcion").getAsString().isEmpty()) fechaFinRecep =DateUtil. StringToDate(jObjectFiltro.get("fechaFinRecepcion").getAsString() + " 23:59:59"); if (jObjectFiltro.get("codSilais") != null && !jObjectFiltro.get("codSilais").getAsString().isEmpty()) codSilais = jObjectFiltro.get("codSilais").getAsString(); if (jObjectFiltro.get("codUnidadSalud") != null && !jObjectFiltro.get("codUnidadSalud").getAsString().isEmpty()) codUnidadSalud = jObjectFiltro.get("codUnidadSalud").getAsString(); if (jObjectFiltro.get("codTipoMx") != null && !jObjectFiltro.get("codTipoMx").getAsString().isEmpty()) codTipoMx = jObjectFiltro.get("codTipoMx").getAsString(); if (jObjectFiltro.get("codigoUnicoMx") != null && !jObjectFiltro.get("codigoUnicoMx").getAsString().isEmpty()) codigoUnicoMx = jObjectFiltro.get("codigoUnicoMx").getAsString(); if (jObjectFiltro.get("codTipoSolicitud") != null && !jObjectFiltro.get("codTipoSolicitud").getAsString().isEmpty()) codTipoSolicitud = jObjectFiltro.get("codTipoSolicitud").getAsString(); if (jObjectFiltro.get("nombreSolicitud") != null && !jObjectFiltro.get("nombreSolicitud").getAsString().isEmpty()) nombreSolicitud = jObjectFiltro.get("nombreSolicitud").getAsString(); filtroMx.setCodSilais(codSilais); filtroMx.setCodUnidadSalud(codUnidadSalud); filtroMx.setFechaInicioRecep(fechaInicioRecep); filtroMx.setFechaFinRecep(fechaFinRecep); filtroMx.setNombreApellido(nombreApellido); filtroMx.setCodTipoMx(codTipoMx); filtroMx.setCodTipoSolicitud(codTipoSolicitud); filtroMx.setNombreSolicitud(nombreSolicitud); filtroMx.setCodEstado("ESTDMX|RCLAB"); // slo las recepcionadas en laboratorio filtroMx.setCodigoUnicoMx(codigoUnicoMx); filtroMx.setNombreUsuario(seguridadService.obtenerNombreUsuario()); filtroMx.setIncluirTraslados(true); return filtroMx; } /** * Mtodo para convertir una lista de RecepcionMx a un string con estructura Json * @param recepcionMxList lista con las Recepciones a convertir * @return String */ private String RecepcionMxToJson(List<RecepcionMx> recepcionMxList) throws Exception { String jsonResponse=""; Map<Integer, Object> mapResponse = new HashMap<Integer, Object>(); Integer indice=0; List<Catalogo> tiposNotificacion = CallRestServices.getCatalogos(CatalogConstants.TipoNotificacion); for(RecepcionMx recepcion : recepcionMxList){ boolean mostrar = true; String traslado = messageSource.getMessage("lbl.no",null,null); String areaOrigen = ""; TrasladoMx trasladoMxActivo = trasladosService.getTrasladoActivoMxRecepcion(recepcion.getTomaMx().getIdTomaMx(),false); if (trasladoMxActivo!=null) { if (trasladoMxActivo.isTrasladoExterno()) { if (!seguridadService.usuarioAutorizadoLaboratorio(seguridadService.obtenerNombreUsuario(),trasladoMxActivo.getLaboratorioDestino().getCodigo())){ mostrar = false; }else{ traslado = messageSource.getMessage("lbl.yes",null,null); areaOrigen = trasladoMxActivo.getAreaOrigen().getNombre(); } }else if (trasladoMxActivo.isTrasladoInterno()) { /*if (!seguridadService.usuarioAutorizadoArea(seguridadService.obtenerNombreUsuario(), trasladoMxActivo.getAreaDestino().getIdArea())){ mostrar = false; }else{*/ traslado = messageSource.getMessage("lbl.yes",null,null); areaOrigen = trasladoMxActivo.getAreaOrigen().getNombre(); //} } }/*else { //se si no hay traslado, pero tiene mas de un dx validar si el usuario tiene acceso al de mayor prioridad. Si slo hay uno siempre se muestra List<DaSolicitudDx> solicitudDxList = tomaMxService.getSolicitudesDxPrioridadByIdToma(recepcion.getTomaMx().getIdTomaMx()); if (solicitudDxList.size() > 1) { if (!seguridadService.usuarioAutorizadoArea(seguridadService.obtenerNombreUsuario(), solicitudDxList.get(0).getCodDx().getArea().getIdArea())) { mostrar = false; } } }*/ if (mostrar) { boolean esEstudio = tomaMxService.getSolicitudesEstudioByIdTomaMx( recepcion.getTomaMx().getIdTomaMx()).size() > 0; Map<String, String> map = new HashMap<String, String>(); map.put("idRecepcion", recepcion.getIdRecepcion()); map.put("idTomaMx", recepcion.getTomaMx().getIdTomaMx()); map.put("codigoUnicoMx", esEstudio?recepcion.getTomaMx().getCodigoUnicoMx():recepcion.getTomaMx().getCodigoLab()); map.put("fechaTomaMx", DateUtil.DateToString(recepcion.getTomaMx().getFechaHTomaMx(), "dd/MM/yyyy")+ (recepcion.getTomaMx().getHoraTomaMx()!=null?" "+recepcion.getTomaMx().getHoraTomaMx():"")); map.put("fechaRecepcion", DateUtil.DateToString(recepcion.getFechaHoraRecepcion(), "dd/MM/yyyy hh:mm:ss a")); if (recepcion.getTomaMx().getIdNotificacion().getCodSilaisAtencion() != null) { map.put("codSilais", recepcion.getTomaMx().getIdNotificacion().getNombreSilaisAtencion());//ABRIL2019 } else { map.put("codSilais", ""); } //notificacion urgente if(recepcion.getTomaMx().getIdNotificacion().getUrgente()!= null){ map.put("urgente", catalogosService.buscarValorCatalogo(tiposNotificacion, recepcion.getTomaMx().getIdNotificacion().getUrgente())); }else{ map.put("urgente", "--"); } if (recepcion.getTomaMx().getIdNotificacion().getCodUnidadAtencion() != null) { map.put("codUnidadSalud", recepcion.getTomaMx().getIdNotificacion().getNombreUnidadAtencion()); //ABRIL2019 } else { map.put("codUnidadSalud", ""); } //Si hay fecha de inicio de sintomas se muestra Date fechaInicioSintomas = recepcion.getTomaMx().getIdNotificacion().getFechaInicioSintomas(); if (fechaInicioSintomas != null) { map.put("fechaInicioSintomas", DateUtil.DateToString(fechaInicioSintomas, "dd/MM/yyyy")); map.put("dias",String.valueOf(DateUtil.CalcularDiferenciaDiasFechas(fechaInicioSintomas, recepcion.getTomaMx().getFechaHTomaMx())+1)); } else { map.put("fechaInicioSintomas", " "); map.put("dias",""); } //Si hay persona if (recepcion.getTomaMx().getIdNotificacion().getPersona() != null) { /// se obtiene el nombre de la persona asociada a la ficha String nombreCompleto = ""; nombreCompleto = recepcion.getTomaMx().getIdNotificacion().getPersona().getPrimerNombre(); if (recepcion.getTomaMx().getIdNotificacion().getPersona().getSegundoNombre() != null) nombreCompleto = nombreCompleto + " " + recepcion.getTomaMx().getIdNotificacion().getPersona().getSegundoNombre(); nombreCompleto = nombreCompleto + " " + recepcion.getTomaMx().getIdNotificacion().getPersona().getPrimerApellido(); if (recepcion.getTomaMx().getIdNotificacion().getPersona().getSegundoApellido() != null) nombreCompleto = nombreCompleto + " " + recepcion.getTomaMx().getIdNotificacion().getPersona().getSegundoApellido(); map.put("persona", nombreCompleto); //Se calcula la edad int edad = DateUtil.calcularEdadAnios(recepcion.getTomaMx().getIdNotificacion().getPersona().getFechaNacimiento()); if(edad > 12 && recepcion.getTomaMx().getIdNotificacion().getPersona().isSexoFemenino()){ if (recepcion.getTomaMx().getIdNotificacion().getEmbarazada()!=null) map.put("embarazada",(recepcion.getTomaMx().getIdNotificacion().getEmbarazada().equalsIgnoreCase("RESP|S")? messageSource.getMessage("lbl.yes",null,null):messageSource.getMessage("lbl.no",null,null))); else map.put("embarazada",messageSource.getMessage("lbl.no",null,null)); }else map.put("embarazada","--"); } else if (recepcion.getTomaMx().getIdNotificacion().getSolicitante() != null) { map.put("persona", recepcion.getTomaMx().getIdNotificacion().getSolicitante().getNombre()); map.put("embarazada","--"); }else if (recepcion.getTomaMx().getIdNotificacion().getCodigoPacienteVIH() != null) { map.put("persona", recepcion.getTomaMx().getIdNotificacion().getCodigoPacienteVIH()); if (recepcion.getTomaMx().getIdNotificacion().getEmbarazada()!=null) map.put("embarazada",(recepcion.getTomaMx().getIdNotificacion().getEmbarazada().equalsIgnoreCase("RESP|S")? messageSource.getMessage("lbl.yes",null,null):messageSource.getMessage("lbl.no",null,null))); else map.put("embarazada",messageSource.getMessage("lbl.no",null,null)); }else { map.put("persona", " "); map.put("embarazada","--"); } map.put("traslado",traslado); map.put("origen",areaOrigen); //se arma estructura de diagnsticos o estudios Laboratorio labUser = seguridadService.getLaboratorioUsuario(seguridadService.obtenerNombreUsuario()); List<DaSolicitudDx> solicitudDxList = tomaMxService.getSolicitudesDxByIdToma(recepcion.getTomaMx().getIdTomaMx(), labUser.getCodigo()); DaSolicitudEstudio solicitudE = tomaMxService.getSoliEstByCodigo(recepcion.getTomaMx().getCodigoUnicoMx()); String dxs = ""; if (!solicitudDxList.isEmpty()) { int cont = 0; for (DaSolicitudDx solicitudDx : solicitudDxList) { cont++; if (cont == solicitudDxList.size()) { dxs += solicitudDx.getCodDx().getNombre(); } else { dxs += solicitudDx.getCodDx().getNombre() + ", "; } } map.put("solicitudes", dxs); } if(solicitudE != null){ map.put("solicitudes",(dxs.isEmpty()?solicitudE.getTipoEstudio().getNombre():dxs+", "+solicitudE.getTipoEstudio().getNombre())); }else{ map.put("solicitudes", dxs); } mapResponse.put(indice, map); indice++; } } jsonResponse = new Gson().toJson(mapResponse); //escapar caracteres especiales, escape de los caracteres con valor numrico mayor a 127 UnicodeEscaper escaper = UnicodeEscaper.above(127); return escaper.translate(jsonResponse); } /** * Mtodo que se llama para crear una Recepcin Mx en el Laboratorio. Setea los datos de la recepcin e inicializa listas y demas controles. * Adems si es la primera vez que se carga el registro se registran ordenes de examen para los examenes configurados por defecto en la tabla * de parmetros segn el tipo de notificacin, tipo de mx, tipo dx * @param request para obtener informacin de la peticin del cliente * @param strIdMuestra Id de la muestra a editar * @return ModelAndView * @throws Exception */ @RequestMapping(value = "editLab/{strIdRecepcion}", method = RequestMethod.GET) public ModelAndView createReceiptLabForm(HttpServletRequest request, @PathVariable("strIdRecepcion") String strIdMuestra) throws Exception { logger.debug("buscar ordenes para ordenExamen"); String urlValidacion; try { urlValidacion = seguridadService.validarLogin(request); //si la url esta vacia significa que la validacin del login fue exitosa if (urlValidacion.isEmpty()) urlValidacion = seguridadService.validarAutorizacionUsuario(request, ConstantsSecurity.SYSTEM_CODE, false); }catch (Exception e){ e.printStackTrace(); urlValidacion = "404"; } ModelAndView mav = new ModelAndView(); if (urlValidacion.isEmpty()) { //RecepcionMx recepcionMx = recepcionMxService.getRecepcionMx(strIdRecepcion); DaTomaMx tomaMx = tomaMxService.getTomaMxById(strIdMuestra); List<EntidadesAdtvas> entidadesAdtvases = CallRestServices.getEntidadesAdtvas(); List<TipoMx> tipoMxList = catalogosService.getTipoMuestra(); List<Unidades> unidades = null; Date fechaInicioSintomas = null; boolean esEstudio = false; if (tomaMx!=null) { //se determina si es una muestra para estudio o para vigilancia rutinaria(Dx) List<DaSolicitudEstudio> solicitudEstudioList = tomaMxService.getSolicitudesEstudioByIdTomaMx(tomaMx.getIdTomaMx()); esEstudio = solicitudEstudioList.size()>0; if(tomaMx.getIdNotificacion().getCodSilaisAtencion()!=null) { //ABRIL2019 unidades = CallRestServices.getUnidadesByEntidadMunicipioTipo(tomaMx.getIdNotificacion().getIdSilaisAtencion(), 0, HealthUnitType.UnidadesPrimHosp.getDiscriminator().split(",")); //ABRIL2019 } fechaInicioSintomas = tomaMx.getIdNotificacion().getFechaInicioSintomas(); TrasladoMx trasladoActivo = trasladosService.getTrasladoActivoMx(tomaMx.getIdTomaMx()); List<DaSolicitudDx> solicitudDxList = tomaMxService.getSolicitudesDxByIdTomaAreaLabUser(tomaMx.getIdTomaMx(), seguridadService.obtenerNombreUsuario()); List<DaSolicitudEstudio> solicitudEstudios = tomaMxService.getSolicitudesEstudioByIdMxUser(tomaMx.getIdTomaMx(), seguridadService.obtenerNombreUsuario()); List<DaSolicitudDx> dxMostrar = new ArrayList<DaSolicitudDx>(); if (trasladoActivo!=null && trasladoActivo.isTrasladoInterno()){ for (DaSolicitudDx solicitudDx : solicitudDxList) { if (trasladoActivo.getAreaDestino().getIdArea().equals(solicitudDx.getCodDx().getArea().getIdArea())){ dxMostrar.add(solicitudDx); } } }else{ dxMostrar = solicitudDxList; } List<DatoSolicitudDetalle> datoSolicitudDetalles = new ArrayList<DatoSolicitudDetalle>(); for(DaSolicitudDx solicitudDx : dxMostrar){ datoSolicitudDetalles.addAll(datosSolicitudService.getDatosSolicitudDetalleBySolicitud(solicitudDx.getIdSolicitudDx())); } for(DaSolicitudEstudio solicitudEstudio : solicitudEstudios){ datoSolicitudDetalles.addAll(datosSolicitudService.getDatosSolicitudDetalleBySolicitud(solicitudEstudio.getIdSolicitudEstudio())); } mav.addObject("datosList",datoSolicitudDetalles); if (esEstudio) { List<Catalogo_Estudio> catalogoEstudios = tomaMxService.getEstudiosByTipoMxTipoNoti(tomaMx.getCodTipoMx().getIdTipoMx().toString(), tomaMx.getIdNotificacion().getCodTipoNotificacion()); mav.addObject("catEst", catalogoEstudios); } List<Catalogo_Dx> catalogoDxs = tomaMxService.getDxByTipoMxTipoNoti(tomaMx.getCodTipoMx().getIdTipoMx().toString(), tomaMx.getIdNotificacion().getCodTipoNotificacion(),seguridadService.obtenerNombreUsuario()); mav.addObject("catDx", catalogoDxs); } mav.addObject("esEstudio",esEstudio); mav.addObject("tomaMx",tomaMx); mav.addObject("entidades",entidadesAdtvases); mav.addObject("unidades",unidades); mav.addObject("tipoMuestra", tipoMxList); mav.addObject("fechaInicioSintomas",fechaInicioSintomas); mav.setViewName("laboratorio/editarMx/editarMxLab"); }else mav.setViewName(urlValidacion); return mav; } /*** * Mtodo para recuperar las ordenes de examen registradas para la mx en la recepcin. * @param idTomaMx id de la toma mx a obtener ordenes * @return String con las ordenes en formato Json * @throws Exception */ @RequestMapping(value = "getOrdenesExamen", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String getOrdenesExamen(@RequestParam(value = "idTomaMx", required = true) String idTomaMx) throws Exception { logger.info("antes getOrdenesExamen"); List<OrdenExamen> ordenExamenList = ordenExamenMxService.getOrdenesExamenNoAnuladasByIdMxAndUser(idTomaMx, seguridadService.obtenerNombreUsuario()); logger.info("despues getOrdenesExamen"); return OrdenesExamenToJson(ordenExamenList); } /** * Mtodo para convertir una lista de Ordenes Examen a un string con estructura Json * @param ordenesExamenList lista con las ordenes de examen a convertir * @return String * @throws java.io.UnsupportedEncodingException */ private String OrdenesExamenToJson(List<OrdenExamen> ordenesExamenList) throws UnsupportedEncodingException { String jsonResponse=""; Map<Integer, Object> mapResponse = new HashMap<Integer, Object>(); Integer indice=0; boolean agregarExamenDx = true; for(OrdenExamen ordenExamen : ordenesExamenList){ Map<String, String> map = new HashMap<String, String>(); if (ordenExamen.getSolicitudDx()!=null) { map.put("idTomaMx", ordenExamen.getSolicitudDx().getIdTomaMx().getIdTomaMx()); map.put("idOrdenExamen", ordenExamen.getIdOrdenExamen()); map.put("idExamen", ordenExamen.getCodExamen().getIdExamen().toString()); map.put("nombreExamen", ordenExamen.getCodExamen().getNombre()); map.put("nombreSolic", ordenExamen.getSolicitudDx().getCodDx().getNombre()); map.put("nombreAreaPrc", ordenExamen.getSolicitudDx().getCodDx().getArea().getNombre()); map.put("fechaSolicitud", DateUtil.DateToString(ordenExamen.getFechaHOrden(), "dd/MM/yyyy hh:mm:ss a")); map.put("tipo", "Rutina"); if (ordenExamen.getSolicitudDx().getControlCalidad()) map.put("cc", messageSource.getMessage("lbl.yes", null, null)); else map.put("cc", messageSource.getMessage("lbl.no", null, null)); if (!ordenExamen.getLabProcesa().getCodigo().equals(ordenExamen.getSolicitudDx().getLabProcesa().getCodigo())) map.put("externo", messageSource.getMessage("lbl.yes", null, null)); else map.put("externo", messageSource.getMessage("lbl.no", null, null)); map.put("resultado", parseResultDetails(ordenExamen.getIdOrdenExamen())); mapResponse.put(indice, map); indice ++; }else{ map.put("idTomaMx", ordenExamen.getSolicitudEstudio().getIdTomaMx().getIdTomaMx()); map.put("idOrdenExamen", ordenExamen.getIdOrdenExamen()); map.put("idExamen", ordenExamen.getCodExamen().getIdExamen().toString()); map.put("nombreExamen", ordenExamen.getCodExamen().getNombre()); map.put("nombreSolic", ordenExamen.getSolicitudEstudio().getTipoEstudio().getNombre()); map.put("nombreAreaPrc", ordenExamen.getSolicitudEstudio().getTipoEstudio().getArea().getNombre()); map.put("fechaSolicitud", DateUtil.DateToString(ordenExamen.getFechaHOrden(), "dd/MM/yyyy hh:mm:ss a")); map.put("tipo","Estudio"); map.put("cc",messageSource.getMessage("lbl.no",null,null)); map.put("externo",messageSource.getMessage("lbl.no",null,null)); map.put("resultado", parseResultDetails(ordenExamen.getIdOrdenExamen())); mapResponse.put(indice, map); indice ++; } } jsonResponse = new Gson().toJson(mapResponse); //escapar caracteres especiales, escape de los caracteres con valor numrico mayor a 127 UnicodeEscaper escaper = UnicodeEscaper.above(127); return escaper.translate(jsonResponse); } @RequestMapping(value = "getSolicitudes", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String getSolicitudes(@RequestParam(value = "idTomaMx", required = true) String idTomaMx) throws Exception { logger.info("antes getSolicitudes"); List<DaSolicitudDx> solicitudDxList = tomaMxService.getSolicitudesDxByIdTomaAreaLabUser(idTomaMx, seguridadService.obtenerNombreUsuario()); List<DaSolicitudEstudio> solicitudEstudios = tomaMxService.getSolicitudesEstudioByIdMxUser(idTomaMx, seguridadService.obtenerNombreUsuario()); logger.info("despues getSolicitudes"); return SolicutudesToJson(solicitudDxList,solicitudEstudios); } /** * Mtodo para convertir una lista de Solicitudes dx y estudios a un string con estructura Json * @param dxList lista con las solicitudes de diagnsticos a convertir * @param estudioList lista con las solicitudes de estudio a convertir * @return String * @throws UnsupportedEncodingException */ private String SolicutudesToJson(List<DaSolicitudDx> dxList, List<DaSolicitudEstudio> estudioList) throws UnsupportedEncodingException { String jsonResponse=""; Map<Integer, Object> mapResponse = new HashMap<Integer, Object>(); Integer indice=0; boolean agregarExamenDx = true; for(DaSolicitudDx dx : dxList){ Map<String, String> map = new HashMap<String, String>(); map.put("idTomaMx", dx.getIdTomaMx().getIdTomaMx()); map.put("idSolicitud", dx.getIdSolicitudDx()); map.put("nombre", dx.getCodDx().getNombre()); map.put("nombreAreaPrc", dx.getCodDx().getArea().getNombre()); map.put("fechaSolicitud", DateUtil.DateToString(dx.getFechaHSolicitud(), "dd/MM/yyyy hh:mm:ss a")); map.put("tipo", messageSource.getMessage("lbl.routine",null,null)); if (dx.getControlCalidad()) map.put("cc", messageSource.getMessage("lbl.yes", null, null)); else map.put("cc", messageSource.getMessage("lbl.no", null, null)); //map.put("aprobada", (dx.getAprobada()?messageSource.getMessage("lbl.yes", null, null):messageSource.getMessage("lbl.no", null, null))); map.put("aprobada", String.valueOf(dx.getAprobada())); map.put("resultados", parseFinalResultDetails(dx.getIdSolicitudDx())); mapResponse.put(indice, map); indice ++; } for(DaSolicitudEstudio estudio : estudioList) { Map<String, String> map = new HashMap<String, String>(); map.put("idTomaMx", estudio.getIdTomaMx().getIdTomaMx()); map.put("idSolicitud", estudio.getIdSolicitudEstudio() ); map.put("nombre", estudio.getTipoEstudio().getNombre()); map.put("nombreAreaPrc", estudio.getTipoEstudio().getArea().getNombre()); map.put("fechaSolicitud", DateUtil.DateToString(estudio.getFechaHSolicitud(), "dd/MM/yyyy hh:mm:ss a")); map.put("tipo",messageSource.getMessage("lbl.study",null,null)); map.put("cc",messageSource.getMessage("lbl.no",null,null)); map.put("aprobada", (estudio.getAprobada()?messageSource.getMessage("lbl.yes", null, null):messageSource.getMessage("lbl.no", null, null))); map.put("resultados", parseFinalResultDetails(estudio.getIdSolicitudEstudio())); mapResponse.put(indice, map); indice ++; } jsonResponse = new Gson().toJson(mapResponse); //escapar caracteres especiales, escape de los caracteres con valor numrico mayor a 127 UnicodeEscaper escaper = UnicodeEscaper.above(127); return escaper.translate(jsonResponse); } private String parseFinalResultDetails(String idSolicitud){ List<DetalleResultadoFinal> resFinalList = resultadoFinalService.getDetResActivosBySolicitud(idSolicitud); String resultados=""; for(DetalleResultadoFinal res: resFinalList){ if (res.getRespuesta()!=null) { resultados+=(resultados.isEmpty()?res.getRespuesta().getNombre():", "+res.getRespuesta().getNombre()); if (res.getRespuesta().getConcepto().getTipo().equals("TPDATO|LIST")) { Catalogo_Lista cat_lista = resultadoFinalService.getCatalogoLista(res.getValor()); resultados+=": "+cat_lista.getValor(); }else if (res.getRespuesta().getConcepto().getTipo().equals("TPDATO|LOG")) { String valorBoleano = (Boolean.valueOf(res.getValor())?"lbl.yes":"lbl.no"); resultados+=": "+valorBoleano; } else { resultados+=": "+res.getValor(); } }else if (res.getRespuestaExamen()!=null){ resultados+=(resultados.isEmpty()?res.getRespuestaExamen().getNombre():", "+res.getRespuestaExamen().getNombre()); if (res.getRespuestaExamen().getConcepto().getTipo().equals("TPDATO|LIST")) { Catalogo_Lista cat_lista = resultadoFinalService.getCatalogoLista(res.getValor()); resultados+=": "+cat_lista.getValor(); } else if (res.getRespuestaExamen().getConcepto().getTipo().equals("TPDATO|LOG")) { String valorBoleano = (Boolean.valueOf(res.getValor())?"lbl.yes":"lbl.no"); resultados+=": "+valorBoleano; }else { resultados+=": "+res.getValor(); } } } return resultados; } private String parseResultDetails(String idOrdenExamen){ List<DetalleResultado> resFinalList = resultadosService.getDetallesResultadoActivosByExamen(idOrdenExamen); String resultados=""; for(DetalleResultado res: resFinalList){ if (res.getRespuesta()!=null) { resultados+=(resultados.isEmpty()?res.getRespuesta().getNombre():", "+res.getRespuesta().getNombre()); if (res.getRespuesta().getConcepto().getTipo().equals("TPDATO|LIST")) { Catalogo_Lista cat_lista = resultadoFinalService.getCatalogoLista(res.getValor()); resultados+=": "+cat_lista.getValor(); }else if (res.getRespuesta().getConcepto().getTipo().equals("TPDATO|LOG")) { String valorBoleano = (Boolean.valueOf(res.getValor())?"lbl.yes":"lbl.no"); resultados+=": "+valorBoleano; } else { resultados+=": "+res.getValor(); } } } return resultados; } }
true
f8cf38b40b1a80afb21efb54f02bdad87e143907
Java
fcremo/lorenzo-il-magnifico
/common/src/model/board/Tower.java
UTF-8
1,850
3.21875
3
[]
no_license
package model.board; import model.board.actionspace.Floor; import model.card.development.DevelopmentCard; import model.player.Player; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * This class represents the state of one tower */ public class Tower<T extends DevelopmentCard> implements Serializable { private List<Floor<T>> floors = new ArrayList<>(); /** * Returns the card on the specified floor * * @param floor the floor * @returns the card */ public T getCard(int floor) { return floors.get(floor).getCard(); } public void setCards(List<T> developmentCards) { for(int i=0; i<developmentCards.size(); i++){ floors.get(i).setCard(developmentCards.get(i)); } } /** * @param player the player you want to check * @return true if the player is occupying the tower with any of his family members */ public boolean isOccupiedBy(Player player) { return floors.stream().anyMatch( floor -> floor.getOccupants().stream().map(occupation -> occupation.first).equals(player) ); } /** * @return true if no players are occupying any floor */ public boolean isOccupied() { return floors.stream().noneMatch( floor -> floor.getOccupants().isEmpty() ); } public void setFloors(List<Floor<T>> floors) { this.floors = new ArrayList<>(floors); } public List<Floor<T>> getFloors() { return floors; } public List<DevelopmentCard> getCards() { return floors.stream() .map(Floor::getCard) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
true
523b24df600c1d6a981a8243593ec6dcbe8ec3e9
Java
hawk1234/WMH
/WMHProj/src/wmh/project/graph/model/GraphUtil.java
UTF-8
4,320
2.421875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package wmh.project.graph.model; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author MAREK */ public class GraphUtil { public static final String GRAPH_TAG="graph"; public static final String NODE_TAG="node"; public static final String NODE_LABEL_ATT="label"; public static final String RELATION_TAG="realtion"; public static final String RELATION_N1_ATT="node1"; public static final String RELATION_N2_ATT="node2"; private GraphUtil(){} public static void saveGraph(Graph graph, String destination){ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // save Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(GRAPH_TAG); doc.appendChild(rootElement); for(Node n : graph.getNodes()){ Element nodeEl = doc.createElement(NODE_TAG); nodeEl.setAttribute(NODE_LABEL_ATT, n.getLabel()); rootElement.appendChild(nodeEl); } for(Relation r : graph.getRelations()){ Element relEl = doc.createElement(RELATION_TAG); relEl.setAttribute(RELATION_N1_ATT, r.getNode1().getLabel()); relEl.setAttribute(RELATION_N2_ATT, r.getNode2().getLabel()); rootElement.appendChild(relEl); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(destination)); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); } catch (TransformerException ex) { throw new GraphException("Unable to write: "+destination, ex); } catch (ParserConfigurationException ex) { throw new GraphException("Unable to write: "+destination, ex); } } public static Graph loadGraph(String location){ Graph ret = new Graph(location); try { File fXmlFile = new File(location); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); //load Element el = doc.getDocumentElement(); NodeList nodes = el.getElementsByTagName(NODE_TAG); for(int i=0; i<nodes.getLength(); ++i){ Element n = (Element) nodes.item(i); String label = n.getAttribute(NODE_LABEL_ATT); ret.addNode(new Node(label)); } NodeList relations = el.getElementsByTagName(RELATION_TAG); for(int i=0; i<relations.getLength(); ++i){ Element r = (Element) relations.item(i); String label1 = r.getAttribute(RELATION_N1_ATT); String label2 = r.getAttribute(RELATION_N2_ATT); ret.createRelation(label1, label2); } } catch (SAXException ex) { throw new GraphException("Unable to load: "+location, ex); } catch (IOException ex) { throw new GraphException("Unable to load: "+location, ex); } catch (ParserConfigurationException ex) { throw new GraphException("Unable to load: "+location, ex); } return ret; } }
true
2b035c8250e507c39dc761749f857da165457671
Java
17602937887/Leetcode
/src/code2020/Mar3th/maxSubArray.java
UTF-8
602
3.125
3
[]
no_license
package code2020.Mar3th; public class maxSubArray { public int maxSubArray(int[] nums) { final int INF = Integer.MAX_VALUE; int max = 0, tmp_max = 0; for(int i = 0; i < nums.length; i++){ tmp_max += nums[i]; if(tmp_max > max){ max = tmp_max; } if (tmp_max < 0){ tmp_max = 0; } } if(max == 0){ max = -INF; for(int i = 0; i < nums.length; i++){ max = Math.max(max, nums[i]); } } return max; } }
true
66c7fd8259203df9a4c8c23e70503c2f95cf16af
Java
lushihao180616/qrcode-business
/src/main/java/com/lushihao/qrcodebusiness/dao/QRCodeRecordMapper.java
UTF-8
469
1.773438
2
[]
no_license
package com.lushihao.qrcodebusiness.dao; import com.lushihao.qrcodebusiness.entity.qrcode.QRCodeRecord; import com.lushihao.qrcodebusiness.entity.temple.TempleAnalysis; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface QRCodeRecordMapper { void create(QRCodeRecord qrCodeRecord); List<QRCodeRecord> select(QRCodeRecord qrCodeRecord); List<TempleAnalysis> selectTempleAnalysis(String date1, String date2); }
true
0ff40bba1f7aae8cce1865b0545c7251fa6fbcd9
Java
nazrinibrahimli/library_comment
/src/main/java/edu/ada/service/library/model/mapper/PickupMapper.java
UTF-8
846
2.5
2
[]
no_license
package edu.ada.service.library.model.mapper; import edu.ada.service.library.model.entity.PickupEntity; import edu.ada.service.library.model.requestAndResponse.PickupDto; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class PickupMapper { public static PickupDto mapEntityToDto(PickupEntity pickupEntity) { return PickupDto.builder().id(pickupEntity.getId()).dropOff(pickupEntity.isDropOff()).book(BookMapper.mapEntityToDto(pickupEntity.getBookEntity())).createdAt(pickupEntity.getCreatedAt()).updatedAt(pickupEntity.getUpdatedAt()).build(); } public static List<PickupDto> mapEntitiesToDtos(Iterable<PickupEntity> pickups) { return StreamSupport.stream(pickups.spliterator(), false).map(PickupMapper::mapEntityToDto).collect(Collectors.toList()); } }
true
8fa2ba08e23fa0eeebe2a580e5094ee8285183d8
Java
vsshakuntala/TFOctober26
/src/main/java/com/tf/usermanagement/domain/CustomerOrganizationMap.java
UTF-8
2,370
2.09375
2
[]
no_license
package com.tf.usermanagement.domain; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * The persistent class for the ORGANIZATION_ADDRESS database table. * * @author Lakhan Jain * */ @Entity @Table(name="CUSTOMER_ORGANIZATION_MAP") public class CustomerOrganizationMap implements Serializable { private static final long serialVersionUID = 1L; private CustomerOrganizationMapPK id; private Boolean active = true; private Long createdBy; private Timestamp createdDate; private Long modifiedBy; private Timestamp modifiedDate; private Customer customer; @EmbeddedId public CustomerOrganizationMapPK getId() { return id; } public void setId(CustomerOrganizationMapPK id) { this.id = id; } @Column(name = "ACTIVE") public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } @Column(name = "CREATED_BY") public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } @Column(name = "CREATED_DATE") public Timestamp getCreatedDate() { return createdDate; } public void setCreatedDate(Timestamp createdDate) { this.createdDate = createdDate; } @Column(name = "MODIFIED_BY") public Long getModifiedBy() { return modifiedBy; } public void setModifiedBy(Long modifiedBy) { this.modifiedBy = modifiedBy; } @Column(name = "MODIFIED_DATE") public Timestamp getModifiedDate() { return modifiedDate; } public void setModifiedDate(Timestamp modifiedDate) { this.modifiedDate = modifiedDate; } @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "CUSTOMER_ID", insertable=false, updatable=false) public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } /* @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "ORGANIZATION_ID", insertable=false, updatable=false) public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } */ }
true
d80841e6831da645e4d1c50bad5321d4ad85dc73
Java
xiaolaoshu9696/letto-offer
/src/letto/offer/Q09_JumpFloorII.java
UTF-8
922
3.703125
4
[]
no_license
package letto.offer; /** * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。 * 求该青蛙跳上一个n级的台阶总共有多少种跳法。 */ public class Q09_JumpFloorII { public int JumpFloorII(int target) { if (target ==1) return 1; if (target ==2) return 2; //链接:https://www.nowcoder.com/questionTerminal/22243d016f6b47f2a6928b4313c85387?f=discussion //来源:牛客网 // //每个台阶可以看作一块木板,让青蛙跳上去,n个台阶就有n块木板,最后一块木板是青蛙到达的位子必须存在, // 其他 (n-1) 块木板可以任意选择是否存在, // 则每个木板有存在和不存在两种选择,(n-1) 块木板 就有 [2^(n-1)] 种跳法,可以直接得到结果。 if (target>2) return 2*JumpFloorII(target-1); return 0; } }
true
2101424787b3d692286f1d3f7cde42ae71e4fedd
Java
weijx-xa/hsx01
/src/hsx/com/controller/UnionController.java
GB18030
1,128
2.125
2
[]
no_license
package hsx.com.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import hsx.com.entity.Union; import hsx.com.service.UnionService; @Controller @RequestMapping("/union") public class UnionController { @Resource private UnionService unionService; @RequestMapping("/unionlogin") public String unionlogin(Union union,HttpServletRequest request){ Union resultunion=unionService.unionlogin(union); if(resultunion==null){ request.setAttribute("union", union); request.setAttribute("errorMsg", "û"); System.out.println("error"); return "redirect:/union/unionlogin.jsp?error=error2"; }else{ //ȡSession HttpSession session=request.getSession(); //ûݴ洢Session session.setAttribute("currentunion", resultunion); System.out.println("success"); return "forward:/unionshow/adminshow.do"; } } }
true
a1e8fb41e2a00ded89a681e06f72c678a594da63
Java
GimZoom/miaosha
/src/main/java/com/yyj/service/UserService.java
UTF-8
390
1.867188
2
[]
no_license
package com.yyj.service; import com.yyj.pojo.User; import com.yyj.vo.LoginVO; import javax.servlet.http.HttpServletResponse; public interface UserService { User findById(Long id); Boolean updatePassword(String token, Long id, String formPass); String login(HttpServletResponse response, LoginVO loginVO); User getByToken(HttpServletResponse response, String token); }
true
e2b5c021b9b8feec11739c1ef335676dfa2b502e
Java
raghu-achukola/quidditch-notebook
/src/com/example/quidditchnotebook/ViewTeamActivity.java
UTF-8
5,563
2.09375
2
[]
no_license
package com.example.quidditchnotebook; import java.util.ArrayList; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.os.Build; public class ViewTeamActivity extends ActionBarActivity { Spinner spinner1; ListView listView1; ArrayList<Team> teams; ArrayList<Game> games; ArrayList<Tournament> tournaments; ArrayList<Team> modified; TeamAdapter ta; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_team); Bundle b = getIntent().getExtras(); games = (ArrayList<Game>)b.get("games"); teams = (ArrayList<Team>)b.get("teams"); tournaments = (ArrayList<Tournament>)b.get("tournaments"); ((TextView)findViewById(R.id.textView1)).setText("View Team"); listView1 = (ListView) findViewById(R.id.listView1); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } spinner1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<String> adapterRS = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.regions_plus_all)); spinner1.setAdapter(adapterRS); modified= teams; ta = new TeamAdapter(ViewTeamActivity.this,R.layout.team_list_item,modified); listView1.setAdapter(ta); /* spinner1.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if(position!=Spinner.INVALID_POSITION) { if(position==0) { modified.clear(); modified.addAll(teams); ta.notifyDataSetChanged(); } else { ArrayList<Team> modifiedList = ViewTeamActivity.sortTeams(position, teams); modified.clear(); modified.addAll(modifiedList); ta.notifyDataSetChanged(); } } } public void onNothingSelected(AdapterView<?> parentView){} });*/ listView1.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { Team t = (Team)arg0.getAdapter().getItem(position); Intent i = new Intent (ViewTeamActivity.this,ViewSpecificTeamActivity.class); i.putExtra("team", t ); i.putExtra("teams",teams); i.putExtra("games", games); i.putExtra("tournaments",tournaments); startActivity(i); } }); } public static ArrayList<Team> sortTeams(int region, ArrayList<Team> teamList) { ArrayList<Team> newTeam = teamList; ArrayList<Team> regionTeams = new ArrayList<Team>(); for(Team t:newTeam) { if(t.getRegion()==region) {regionTeams.add(t);} } for(int i=0;i<regionTeams.size();i++) {Team first = regionTeams.get(i); Team holder = regionTeams.get(i); for(int j=i+1;j<regionTeams.size();j++) { if(first.getName().compareToIgnoreCase(regionTeams.get(j).getName())>0) { first = regionTeams.get(j); } } regionTeams.set(regionTeams.indexOf(first), holder); regionTeams.set(i,first); } return regionTeams; } public void refresh(View v) { int position = spinner1.getSelectedItemPosition(); if(position!=Spinner.INVALID_POSITION) { if(position==0) { modified=teams; ta = new TeamAdapter(ViewTeamActivity.this,R.layout.team_list_item,modified); listView1.setAdapter(ta); } else { modified = ViewTeamActivity.sortTeams(position, teams); ta = new TeamAdapter(ViewTeamActivity.this,R.layout.team_list_item,modified); listView1.setAdapter(ta); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.view_team, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_view_team, container, false); return rootView; } } }
true
ea5c22e6d7929846231529da711a2d233df86338
Java
thomasaudren/tp3
/Serveur/ServeurTCP.java
UTF-8
3,971
2.75
3
[]
no_license
package Serveur; import java.net.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.*; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import API.Api; public class ServeurTCP extends Thread { private Socket socket; /**/ private Api apiXML = new Api("Utilisateurs.xml"); public static void main(String[] args) { } public ServeurTCP(Socket socket) { this.socket = socket; } public void run() { traitements(); } public String receive(BufferedReader input){ String message = ""; try { boolean test = true; while (test) { String ligne = input.readLine(); if(!ligne.equals("")){ message += ligne; } else{ test = false; } } } catch(Exception e) { return "-1"; } return message; } public boolean authorize(String connection){ System.out.println("debut"); boolean res = false; SAXBuilder builder = new SAXBuilder(); Document anotherDocument = null; Element racine = new Element("vide"); try { InputStream stream = new ByteArrayInputStream(connection.getBytes("UTF-8")); anotherDocument = builder.build(stream); racine = anotherDocument.getRootElement(); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String id = racine.getAttributeValue("id"); String psw = racine.getAttributeValue("psw"); if(!this.apiXML.isUser(id, psw)){ System.out.println(id+" ne peut pas se loger"); } else{ System.out.println(id+" est loguer"); res = true; } System.out.println("fin"); return res; } public void ajouterFichier(String msg){ SAXBuilder builder = new SAXBuilder(); Document anotherDocument = null; Element racine = new Element("vide"); try { Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher( msg.trim() ); msg = junkMatcher.replaceFirst("<"); InputStream stream = new ByteArrayInputStream(msg.getBytes("UTF-8")); anotherDocument = builder.build(stream); racine = anotherDocument.getRootElement(); String id = racine.getAttributeValue("id"); String path = racine.getAttributeValue("path"); Element etmp = (Element)racine.getChildren("byteString").toArray()[0]; String tmp = etmp.getText(); System.out.println("serveur_"+path+" "+tmp); File file = new File("serveur_"+path); file.createNewFile(); FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter ( fw ) ; //bw.newLine(); PrintWriter pw = new PrintWriter ( bw ) ; pw. print ( tmp ) ; pw. close ( ) ; } catch (JDOMException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } public void traitements() { try { String message = ""; System.out.println("Connexion avec le client : " + socket.getInetAddress()+" "+ socket.getLocalPort()+" "+socket.getPort()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); message = this.receive(in); Boolean res = authorize(message); if(res){ out.println("<- Vous este login\n"); } else{ System.out.println("false"); out.println("-1\n"); } while(res){ String messageClient = receive(in); if(messageClient.equals("logout")){ res = false; System.out.println(""); } else{ this.ajouterFichier(messageClient); } } in.close(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
24e605afd7b1fde46cd326d91f209e913978998a
Java
microspeed2018/project
/yuanlinjinguan/biz/core-model/src/main/java/com/zjzmjr/core/model/admin/BusinessQuery.java
UTF-8
2,427
2.03125
2
[]
no_license
package com.zjzmjr.core.model.admin; import com.zjzmjr.core.base.page.BasePageQuery; /** * 事物查询 query * * @author Administrator * @version $Id: BusinessQuery.java, v 0.1 2016-7-12 上午10:30:28 Administrator * Exp $ */ public class BusinessQuery extends BasePageQuery { private static final long serialVersionUID = 5641695471164259959L; /** * userId 用户编号 userName 用户名 businessType 事物类型 result 处理结果 */ private Integer userId; private String userName; private Integer businessType; private String businessName; private Integer result; private String resultName; /** 查本月的 */ private Integer checkInstant; /** 扩展字段 */ private String extendedMsg; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getBusinessType() { return businessType; } public void setBusinessType(Integer businessType) { this.businessType = businessType; } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public Integer getResult() { return result; } public void setResult(Integer result) { this.result = result; } public String getResultName() { return resultName; } public void setResultName(String resultName) { this.resultName = resultName; } public Integer getCheckInstant() { return checkInstant; } public void setCheckInstant(Integer checkInstant) { this.checkInstant = checkInstant; } public String getExtendedMsg() { return extendedMsg; } public void setExtendedMsg(String extendedMsg) { this.extendedMsg = extendedMsg; } @Override public String toString() { return "BusinessQuery [userId=" + userId + ", userName=" + userName + ", businessType=" + businessType + ", businessName=" + businessName + ", result=" + result + ", resultName=" + resultName + ", checkInstant=" + checkInstant + ", extendedMsg=" + extendedMsg + "]"; } }
true
3c75bed3fec4a809bff92dadba04d923143a1a1e
Java
apache/avro
/lang/java/ipc/src/test/java/org/apache/avro/ipc/TestRpcPluginOrdering.java
UTF-8
3,046
1.984375
2
[ "BSD-3-Clause", "Zlib", "GPL-1.0-or-later", "FSFAP", "MIT", "LicenseRef-scancode-other-permissive", "zlib-acknowledgement", "GPL-2.0-only", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.avro.ipc; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.atomic.AtomicInteger; import org.apache.avro.ipc.specific.SpecificRequestor; import org.apache.avro.ipc.specific.SpecificResponder; import org.apache.avro.test.Mail; import org.apache.avro.test.Message; import org.junit.jupiter.api.Test; public class TestRpcPluginOrdering { private static AtomicInteger orderCounter = new AtomicInteger(); public class OrderPlugin extends RPCPlugin { public void clientStartConnect(RPCContext context) { assertEquals(0, orderCounter.getAndIncrement()); } public void clientSendRequest(RPCContext context) { assertEquals(1, orderCounter.getAndIncrement()); } public void clientReceiveResponse(RPCContext context) { assertEquals(6, orderCounter.getAndIncrement()); } public void clientFinishConnect(RPCContext context) { assertEquals(5, orderCounter.getAndIncrement()); } public void serverConnecting(RPCContext context) { assertEquals(2, orderCounter.getAndIncrement()); } public void serverReceiveRequest(RPCContext context) { assertEquals(3, orderCounter.getAndIncrement()); } public void serverSendResponse(RPCContext context) { assertEquals(4, orderCounter.getAndIncrement()); } } @Test void rpcPluginOrdering() throws Exception { OrderPlugin plugin = new OrderPlugin(); SpecificResponder responder = new SpecificResponder(Mail.class, new TestMailImpl()); SpecificRequestor requestor = new SpecificRequestor(Mail.class, new LocalTransceiver(responder)); responder.addRPCPlugin(plugin); requestor.addRPCPlugin(plugin); Mail client = SpecificRequestor.getClient(Mail.class, requestor); Message message = createTestMessage(); client.send(message); } private Message createTestMessage() { Message message = Message.newBuilder().setTo("me@test.com").setFrom("you@test.com").setBody("plugin testing") .build(); return message; } private static class TestMailImpl implements Mail { public String send(Message message) { return "Received"; } public void fireandforget(Message message) { } } }
true
ce43c61bbee341d7e70036ae52bbeb1aa7dc6f15
Java
bellmit/omf
/rap-business-dom/src/main/java/rap/api/object/pp/model/ProdPlanSpecSheetVO.java
UTF-8
3,903
1.820313
2
[]
no_license
/* * =================================================================== * System Name : PLM Project * Program ID : ProdPlanSpecSheetVO.java * =================================================================== * Modification Date Modifier Description * 2017.04.?? DS Shin Initial * =================================================================== */ package rap.api.object.pp.model; import com.rap.omc.api.object.model.BusinessObjectVO; import java.util.Date; import java.util.List; import java.text.ParseException; import java.text.SimpleDateFormat; import java.math.BigDecimal; @SuppressWarnings("serial") public class ProdPlanSpecSheetVO extends BusinessObjectVO { private String specSheetId ; private String specSheetGroupId ; private String scope ; private String regionCode ; private String countryCode ; private Integer globalVersion ; private Integer regionVersion ; private Integer countryVersion ; private String finalExcelFileId ; private Integer subVersion ; private String checkoutedSpecSheetId ; private String distributedSpecSheetId ; public void setSpecSheetId(String specSheetId){ this.specSheetId = specSheetId; } public void setSpecSheetGroupId(String specSheetGroupId){ this.specSheetGroupId = specSheetGroupId; } public void setScope(String scope){ this.scope = scope; } public void setRegionCode(String regionCode){ this.regionCode = regionCode; } public void setCountryCode(String countryCode){ this.countryCode = countryCode; } public void setGlobalVersion(Integer globalVersion){ this.globalVersion = globalVersion; } public void setRegionVersion(Integer regionVersion){ this.regionVersion = regionVersion; } public void setCountryVersion(Integer countryVersion){ this.countryVersion = countryVersion; } public void setFinalExcelFileId(String finalExcelFileId){ this.finalExcelFileId = finalExcelFileId; } public void setSubVersion(Integer subVersion){ this.subVersion = subVersion; } public void setCheckoutedSpecSheetId(String checkoutedSpecSheetId){ this.checkoutedSpecSheetId = checkoutedSpecSheetId; } public void setDistributedSpecSheetId(String distributedSpecSheetId){ this.distributedSpecSheetId = distributedSpecSheetId; } public String getSpecSheetId(){ return specSheetId; } public String getSpecSheetGroupId(){ return specSheetGroupId; } public String getScope(){ return scope; } public String getRegionCode(){ return regionCode; } public String getCountryCode(){ return countryCode; } public Integer getGlobalVersion(){ return globalVersion; } public Integer getRegionVersion(){ return regionVersion; } public Integer getCountryVersion(){ return countryVersion; } public String getFinalExcelFileId(){ return finalExcelFileId; } public Integer getSubVersion(){ return subVersion; } public String getCheckoutedSpecSheetId(){ return checkoutedSpecSheetId; } public String getDistributedSpecSheetId(){ return distributedSpecSheetId; } }
true
2803ea1f961043d08edfd38a0b5b06638ee34621
Java
hollyroberts/volcano-infiltration
/src/game_base/Mouse.java
UTF-8
3,530
2.734375
3
[]
no_license
package game_base; import game_logic.Data; import java.awt.Graphics2D; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import particles.ParticleHandler; import player.Player; public class Mouse { private static int relativeXPos; private static int relativeYPos; private static int wobbleX; private static int wobbleY; private static boolean isDown = false; private static BufferedImage cursorNormal_Down; private static BufferedImage cursorNormal_Up; private static BufferedImage cursorGunReticle; public static void init() { //Load mouse image files try { cursorNormal_Down = ImageIO.read(new File(Data.getResourceLoc() + "textures/mouse/cursor down.png")); cursorNormal_Up = ImageIO.read(new File(Data.getResourceLoc() + "textures/mouse/cursor.png")); cursorGunReticle = ImageIO.read(new File(Data.getResourceLoc() + "textures/mouse/gunReticle.png")); } catch (IOException e) { e.printStackTrace(); } } public static void render(Graphics2D g2) { //Draw the mouse to the screen BufferedImage cursor = null; if (Screen.getScreen() == 1) { cursor = cursorGunReticle; } else { if (isDown) { cursor = cursorNormal_Down; } else { cursor = cursorNormal_Up; } } g2.drawImage(cursor, (relativeXPos - 16) + wobbleX, (relativeYPos - 16) + wobbleY, 32, 32, null); } public static void setInfo(Point screenPos) { //Update where the mouse is on the screen int relativeXPosTemp; int relativeYPosTemp; Point mousePos = MouseInfo.getPointerInfo().getLocation(); relativeXPosTemp = (int) (mousePos.getX() - screenPos.getX()); relativeYPosTemp = (int) (mousePos.getY() - screenPos.getY()); if (relativeXPosTemp < 0) { relativeXPosTemp = 0; } else if (relativeXPosTemp > 640) { relativeXPosTemp = 640; } if (relativeYPosTemp < 0) { relativeYPosTemp = 0; } else if (relativeYPosTemp > 990) { relativeYPosTemp = 990; } relativeXPos = relativeXPosTemp; relativeYPos = relativeYPosTemp; } public static void tick() { if (Screen.getScreen() > 2) { if (Math.random() > 0.7) { ParticleHandler.newMagma(Mouse.getX(), Mouse.getY(), true); } if (isDown) { for (int counter = 1; counter < 10; counter++) { ParticleHandler.newMagma(Mouse.getX(), Mouse.getY(), false); } } } //Calculate mouse wobble (experimental feature) if (Math.random() > 0.3 | Screen.getScreen() > 2) { return; } double xChange = Player.getXVel(); double yChange = Player.getYVel(); double speed = Math.sqrt(xChange * xChange + yChange * yChange); wobbleX = (int) (Math.random() * speed * 3); wobbleY = (int) (Math.random() * speed * 3); //comment to enable mouse wobble wobbleX = 0; wobbleY = 0; } public static void reset() { //Reset mouse wobble (experimental feature) wobbleX = 0; wobbleY = 0; } public static int getX() { return relativeXPos; } public static int getY() { return relativeYPos; } public static int getWobbleX() { return wobbleX; } public static int getWobbleY() { return wobbleY; } public static boolean isDown() { return isDown; } public static void setIsDown(boolean newMode) { isDown = newMode; } public static void Pressed(MouseEvent e) { //Called when the mouse is pressed isDown = true; } public static void Released(MouseEvent e) { //Called when the mouse is released isDown = false; } }
true
d35e217047cf85f3f41a5d35c29a40c04ec727fa
Java
kpac3748/davidWuExample
/JavaEx_Part2/src/idv/david/additional/enumevo/PrivateShirt2.java
UTF-8
665
2.546875
3
[]
no_license
package idv.david.additional.enumevo; public class PrivateShirt2 { private int shirtID = 0; private String description = "-description required-"; // ● 顏色碼 R=紅色, B=藍色, G=綠色, U=未定 private ColorCode colorCode = ColorCode.U; private double price = 0.0; private int quantityInStock = 0; // ●getXxx public ColorCode getColorCode() { return colorCode; } // ●setXxx public void setColorCode(ColorCode newCode) { colorCode = newCode; // ※不再需要此錯誤處理了, 已由 enum 決定範圍了 } // ※ 其它對 shirtID, description, // ※ price, and quantityInStock 的 get set方法, 請仿照上述的作法 }
true
5bbe946c15e012268064b63a385b185d87f711e0
Java
andylauxugang2/invest
/ivcommons/src/main/java/com/invest/ivcommons/validate/Validateware.java
UTF-8
288
1.601563
2
[]
no_license
package com.invest.ivcommons.validate; import com.invest.ivcommons.base.result.Result; import com.invest.ivcommons.validate.model.ValidParam; /** * Created by xugang on 2017/7/28. */ public interface Validateware<R extends Result, P extends ValidParam> { R valid(P validParam); }
true
44c45948b9d1e0f25a0834d7599623997f597ca1
Java
SpandanSarkar/Java-Project
/StudentProfile.java
UTF-8
15,918
2.34375
2
[]
no_license
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; /* * 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 Spandan */ public class StudentProfile extends javax.swing.JFrame { /** * Creates new form StudentProfile */ String name; public StudentProfile(String name) { this.name = name; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jButton_Cancel = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); Text = new javax.swing.JTextField(); Pass = new javax.swing.JPasswordField(); jButton_Cancel1 = new javax.swing.JButton(); jLabelRegister = new javax.swing.JLabel(); jButton_Login = new javax.swing.JButton(); jLabelForgetpass = new javax.swing.JLabel(); jButton_Cancel2 = new javax.swing.JButton(); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Login Form"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 21)); // NOI18N jLabel5.setForeground(new java.awt.Color(204, 204, 204)); jLabel5.setText("Username:"); jButton_Cancel.setBackground(new java.awt.Color(204, 0, 0)); jButton_Cancel.setFont(new java.awt.Font("Traditional Arabic", 1, 14)); // NOI18N jButton_Cancel.setForeground(new java.awt.Color(255, 255, 255)); jButton_Cancel.setText("Cancel"); jButton_Cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_CancelActionPerformed(evt); } }); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(0, 51, 102)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Login Form for Student"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 21)); // NOI18N jLabel6.setForeground(new java.awt.Color(204, 204, 204)); jLabel6.setText("Username:"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 21)); // NOI18N jLabel4.setForeground(new java.awt.Color(204, 204, 204)); jLabel4.setText("Password:"); Text.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N Text.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { TextActionPerformed(evt); } }); Pass.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jButton_Cancel1.setBackground(new java.awt.Color(204, 0, 0)); jButton_Cancel1.setFont(new java.awt.Font("Traditional Arabic", 1, 18)); // NOI18N jButton_Cancel1.setForeground(new java.awt.Color(255, 255, 255)); jButton_Cancel1.setText("Cancel"); jButton_Cancel1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Cancel1ActionPerformed(evt); } }); jLabelRegister.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabelRegister.setForeground(new java.awt.Color(255, 255, 255)); jLabelRegister.setText("Click here to create a new account"); jLabelRegister.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabelRegister.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabelRegisterMouseClicked(evt); } }); jButton_Login.setBackground(new java.awt.Color(0, 204, 0)); jButton_Login.setFont(new java.awt.Font("Traditional Arabic", 1, 18)); // NOI18N jButton_Login.setForeground(new java.awt.Color(255, 255, 255)); jButton_Login.setText("Login"); jButton_Login.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_LoginActionPerformed(evt); } }); jLabelForgetpass.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabelForgetpass.setForeground(new java.awt.Color(255, 255, 255)); jLabelForgetpass.setText("Forget Password?"); jLabelForgetpass.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); jLabelForgetpass.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabelForgetpassMouseClicked(evt); } }); jButton_Cancel2.setBackground(new java.awt.Color(0, 0, 0)); jButton_Cancel2.setFont(new java.awt.Font("Traditional Arabic", 1, 18)); // NOI18N jButton_Cancel2.setForeground(new java.awt.Color(255, 255, 255)); jButton_Cancel2.setText("Return to Home"); jButton_Cancel2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_Cancel2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton_Cancel2) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(131, 131, 131) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel6))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(141, 141, 141) .addComponent(jButton_Cancel1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Pass) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(Text, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabelRegister) .addComponent(jLabelForgetpass)))) .addGap(146, 146, 146)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jButton_Cancel2, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(89, 89, 89) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(Text, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(Pass, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton_Cancel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabelForgetpass, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabelRegister, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(68, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelActionPerformed System.exit(0); }//GEN-LAST:event_jButton_CancelActionPerformed private void jButton_Cancel1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Cancel1ActionPerformed System.exit(0); }//GEN-LAST:event_jButton_Cancel1ActionPerformed private void jLabelRegisterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelRegisterMouseClicked StudentReg rgf = new StudentReg(name); rgf.setVisible(true); rgf.pack(); rgf.setLocationRelativeTo(null); rgf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.dispose(); }//GEN-LAST:event_jLabelRegisterMouseClicked private void jButton_LoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_LoginActionPerformed final String secretKey = "ssshhhhhhhhhhh!!!!"; PreparedStatement ps; ResultSet rs; String uname = Text.getText(); name = uname; String pass = String.valueOf(Pass.getPassword()); String originalString = pass; String encryptedString = AES.encrypt(originalString, secretKey) ; String decryptedString = AES.decrypt(encryptedString, secretKey) ; String query = "SELECT * FROM `student profile` WHERE `Uname` =? AND `Pass` =?"; try { ps = MyConnection.getConnection().prepareStatement(query); ps.setString(1, uname); ps.setString(2, encryptedString); rs = ps.executeQuery(); if(rs.next()) { HOME_Frame mf = new HOME_Frame(name); mf.setVisible(true); mf.pack(); mf.setLocationRelativeTo(null); //// mf.setExtendedState(JFrame.MAXIMIZED_BOTH); this.dispose(); } else{ JOptionPane.showMessageDialog(null, "Incorrect Username or Password", "Update failed", 2); } } catch (SQLException ex) { Logger.getLogger(StudentProfile.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton_LoginActionPerformed private void jLabelForgetpassMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelForgetpassMouseClicked ForgetPassST fp = new ForgetPassST(name); fp.setVisible(true); fp.pack(); fp.setLocationRelativeTo(null); fp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.dispose(); }//GEN-LAST:event_jLabelForgetpassMouseClicked private void jButton_Cancel2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Cancel2ActionPerformed FrontPage fp = new FrontPage(); fp.setVisible(true); fp.pack(); fp.setLocationRelativeTo(null); fp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.dispose(); }//GEN-LAST:event_jButton_Cancel2ActionPerformed private void TextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TextActionPerformed // TODO add your handling code here: }//GEN-LAST:event_TextActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPasswordField Pass; private javax.swing.JTextField Text; private javax.swing.JButton jButton_Cancel; private javax.swing.JButton jButton_Cancel1; private javax.swing.JButton jButton_Cancel2; private javax.swing.JButton jButton_Login; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabelForgetpass; private javax.swing.JLabel jLabelRegister; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
true
526a9677d98123c665bf91e154276ddddf982f6f
Java
LK-Tmac1/JavaOOD
/src/设计模式/工厂/工厂/Client.java
UTF-8
672
2.796875
3
[]
no_license
package 设计模式.工厂.工厂; import 设计模式.工厂.entity.DBRequest; import 设计模式.工厂.工厂.dbAccessFactory.InterfaceDAOFactory; import 设计模式.工厂.工厂.dbAccessFactory.OracleFactory; import 设计模式.工厂.简单工厂.dbAccessObject.InterfaceDAO; public class Client { private static void case1() { DBRequest request = new DBRequest(); // 仍旧需要在客户端创建具体的factory InterfaceDAOFactory factory = new OracleFactory(); InterfaceDAO dao = factory.createDAOProduct(); dao.insertDB(request); } public static void main(String[] args) { case1(); } }
true
55367bdd5c3ba74f77fa8b5ed892b9c8cddebab0
Java
packagewjx/brand-report-backend
/src/main/java/io/github/packagewjx/brandreportbackend/service/BaseService.java
UTF-8
2,568
2.78125
3
[]
no_license
package io.github.packagewjx.brandreportbackend.service; import java.util.Optional; /** * @author Junxian Wu * <p> * 实体访问服务 */ public interface BaseService<T, ID> { /** * 保存给定实体 * <p> * 若实体是新的实体,没有之前的ID,则是插入新的实体,且返回的实体中包含新的ID。 * 若实体拥有ID,则更新数据库中对应的实体。 * * @param val 新数据 * @return 若插入成功,则返回原val。否则返回null */ T save(T val); /** * 部分更新实体。仅仅使用updateVal中非null的部分进行更新。 * 更新使用<code>UtilFunctions.partialChange</code>函数,查看该文档了解详情 * * @param id ID * @param updateVal 新的值 * @return 更新后的实体 * @see io.github.packagewjx.brandreportbackend.utils.UtilFunctions */ T partialUpdate(ID id, T updateVal); /** * 保存所有的实体 * * @param val 实体集 * @return 保存后的实体集,若ID为空则会添加ID */ Iterable<T> saveAll(Iterable<T> val); /** * 删除val * * @param val 要删除的实体 */ void delete(T val); /** * 删除ID为id的数据 * * @param id 数据Id */ void deleteById(ID id); /** * 删除ID在ids集合中的所有实体 * * @param ids 需要删除的实体的ID集合 */ void deleteAll(Iterable<T> ids); /** * 获取ID为id的数据 * * @param id 数据ID * @return 若不存在,则返回null。否则返回数据对象 */ Optional<T> getById(ID id); /** * 获取所有ID为ids集合中的id的实体 * * @param ids ID集合 * @return 所有ID在ids集合的实体 */ Iterable<T> getAllById(Iterable<ID> ids); /** * 根据example中非null的字段,查询符合的所有实体 * * @param example 查询条件 * @return 符合example条件的所有实体 */ Iterable<T> getAllByExample(T example); /** * 查看是否存在 * * @param id ID * @return 若存在则为true,否则为false */ boolean existById(ID id); /** * 获取所有对象 * * @return 所有对象 */ Iterable<T> getAll(); /** * 查看id是否是entity的id相等 * * @param id ID * @param entity 实体 * @return true则是,否则不是 */ boolean isIdOfEntity(ID id, T entity); }
true
e6e93e9b63b59df6e49d4f4a6ec8ad9db02b85ad
Java
hallvard/jexercise
/no.hal.learning/no.hal.learning.exercise/workspace/src/no/hal/learning/exercise/workspace/impl/LaunchAnswerImpl.java
UTF-8
6,666
1.828125
2
[]
no_license
/** */ package no.hal.learning.exercise.workspace.impl; import java.util.Collection; import no.hal.learning.exercise.TaskEvent; import no.hal.learning.exercise.impl.TaskAnswerImpl; import no.hal.learning.exercise.util.Util; import no.hal.learning.exercise.workspace.LaunchAnswer; import no.hal.learning.exercise.workspace.LaunchEvent; import no.hal.learning.exercise.workspace.WorkspacePackage; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EDataTypeUniqueEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Launch Answer</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link no.hal.learning.exercise.workspace.impl.LaunchAnswerImpl#getMode <em>Mode</em>}</li> * <li>{@link no.hal.learning.exercise.workspace.impl.LaunchAnswerImpl#getLaunchAttrNames <em>Launch Attr Names</em>}</li> * <li>{@link no.hal.learning.exercise.workspace.impl.LaunchAnswerImpl#getLaunchAttrValues <em>Launch Attr Values</em>}</li> * </ul> * * @generated */ public class LaunchAnswerImpl extends TaskAnswerImpl implements LaunchAnswer { /** * The default value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated * @ordered */ protected static final String MODE_EDEFAULT = null; /** * The cached value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated * @ordered */ protected String mode = MODE_EDEFAULT; /** * The cached value of the '{@link #getLaunchAttrNames() <em>Launch Attr Names</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLaunchAttrNames() * @generated * @ordered */ protected EList<String> launchAttrNames; /** * The cached value of the '{@link #getLaunchAttrValues() <em>Launch Attr Values</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLaunchAttrValues() * @generated * @ordered */ protected EList<String> launchAttrValues; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected LaunchAnswerImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return WorkspacePackage.Literals.LAUNCH_ANSWER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getMode() { return mode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMode(String newMode) { String oldMode = mode; mode = newMode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, WorkspacePackage.LAUNCH_ANSWER__MODE, oldMode, mode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getLaunchAttrNames() { if (launchAttrNames == null) { launchAttrNames = new EDataTypeUniqueEList<String>(String.class, this, WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_NAMES); } return launchAttrNames; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getLaunchAttrValues() { if (launchAttrValues == null) { launchAttrValues = new EDataTypeUniqueEList<String>(String.class, this, WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_VALUES); } return launchAttrValues; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case WorkspacePackage.LAUNCH_ANSWER__MODE: return getMode(); case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_NAMES: return getLaunchAttrNames(); case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_VALUES: return getLaunchAttrValues(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case WorkspacePackage.LAUNCH_ANSWER__MODE: setMode((String)newValue); return; case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_NAMES: getLaunchAttrNames().clear(); getLaunchAttrNames().addAll((Collection<? extends String>)newValue); return; case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_VALUES: getLaunchAttrValues().clear(); getLaunchAttrValues().addAll((Collection<? extends String>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case WorkspacePackage.LAUNCH_ANSWER__MODE: setMode(MODE_EDEFAULT); return; case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_NAMES: getLaunchAttrNames().clear(); return; case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_VALUES: getLaunchAttrValues().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case WorkspacePackage.LAUNCH_ANSWER__MODE: return MODE_EDEFAULT == null ? mode != null : !MODE_EDEFAULT.equals(mode); case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_NAMES: return launchAttrNames != null && !launchAttrNames.isEmpty(); case WorkspacePackage.LAUNCH_ANSWER__LAUNCH_ATTR_VALUES: return launchAttrValues != null && !launchAttrValues.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (mode: "); result.append(mode); result.append(", launchAttrNames: "); result.append(launchAttrNames); result.append(", launchAttrValues: "); result.append(launchAttrValues); result.append(')'); return result.toString(); } // @Override public boolean acceptEvent(TaskEvent event) { if (! (event instanceof LaunchEvent)) { return false; } LaunchEvent launchEvent = (LaunchEvent) event; return Util.accept(getMode(), launchEvent.getMode()); } } //LaunchAnswerImpl
true
36443541e906d7abdee77f6a91a6ff6f34a94e28
Java
thelucasgarcia/Calculadora
/Calculadora/src/calculadora/AdubagemSimples.java
UTF-8
1,001
3.140625
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 calculadora; /** * * @author bruno */ public class AdubagemSimples { /* Onde: QA = Quantidade a aplicar 100 x QR QR = Quantidade recomendada QA = ----------------- TN = Teor de nutriente do adubo TN Exemplo: A recomendação para a adubação de Nitrogênio é 60 kg/ha. Se usarmos como fonte de N o Sulfato de Amônio ( 20% de N) , a quantidade necessária será: 100 x 60 6000 QA = -------------- = ----------- = 300 kg/ha 20 20 */ public float calculo(float QuantidadeRecomendada, float TeorDeNutriente) { float QuantidadeAplicar; QuantidadeAplicar = (100 * QuantidadeRecomendada) / TeorDeNutriente; return QuantidadeAplicar; } }
true
6fa1249a1adc6b754b84f7a4eb7dad702348d876
Java
moroclash/IDBI-Bank
/src/GUI/MY_Balance.java
UTF-8
870
2.40625
2
[]
no_license
package GUI; import java.awt.Color; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JPanel; public class MY_Balance extends form_one_std_filed{ protected JLabel Mybalance; public MY_Balance(String x) { super("MY Balance"); submit.setVisible(false); reset.setVisible(false); txfiled1.setVisible(false); tx1.setText("My Balance : "); tx1.setBounds(100, 150, 200 , 30); Mybalance = new JLabel(x); Mybalance.setBounds(txfiled1.getBounds().x+20,txfiled1.getBounds().y+4,txfiled1.getBounds().width , 33); Mybalance.setFont(fon); Mybalance.setForeground(Color.orange); frame.add(Mybalance); } @Override public void actionPerformed(ActionEvent e) { } }
true
b248548b47b6443bccc49ce15979f544bc4f6f01
Java
duongthuhuyen/B-i-t-p-v-nh-
/bai_tap_buoi_2/src/baitapkethua/bai8_chuabt/Test.java
UTF-8
1,498
3.03125
3
[]
no_license
package baitapkethua.bai8_chuabt; import java.util.Scanner; public class Test{ public static void main(String[] args) { ProductManager productManager = new ProductManager(3); productManager.input(); productManager.output(); boolean flag = true; Scanner sc = new Scanner(System.in); do { System.out.println("Nhập lựa chọn: "); int a = sc.nextInt(); sc.nextLine(); switch (a) { case 1: // ProgramType.products[THEM_HANG_THUC_PHAM].input(); Food food = new Food(); food.input(); productManager.add(food); break; case 2: // ProgramType.products[THEM_HANG_DIEN_TU].input(); Electric electric = new Electric(); productManager.add(electric); break; case 3: //ProgramType.products[THEM_HANG_SANH_SU].input(); Crockery crokery = new Crockery(); productManager.add(crokery); break; case 4: productManager.output(); break; default: System.out.println("The end_______________"); flag = false; break; } } while (flag) ; } }
true
e995ae776342f0cc633fd7bb70d7ab8c4a9c5af4
Java
calvinlau/algoboy
/leetcode/src/tree/BinaryTreeLevelOrderTraversalII.java
UTF-8
1,628
3.9375
4
[]
no_license
package tree; import java.util.*; /** * Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). * For example: * Given binary tree {3,9,20,#,#,15,7}, * Return: * [ * [15,7], * [9,20], * [3] * ] * * @author kevinliu * @Solution: BFS - Queue * */ public class BinaryTreeLevelOrderTraversalII { private final List<List<Integer>> ret = new ArrayList<>(); public List<List<Integer>> levelOrderBottom(TreeNode root) { preOrder(root, 0); Collections.reverse(ret); return ret; } private void preOrder(TreeNode root, int level) { if (root == null) { return; } if (ret.size() == level) { ret.add(new ArrayList<>()); } ret.get(level).add(root.val); preOrder(root.left, level + 1); preOrder(root.right, level + 1); } public static List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> level = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode head = queue.poll(); level.add(head.val); if (head.left != null) { queue.offer(head.left); } if (head.right != null) { queue.offer(head.right); } } result.add(level); } for (int i = 0, j = result.size() - 1; i < j; i++, j--) { List<Integer> tmp = result.get(i); result.set(i, result.get(j)); result.set(j, tmp); } return result; } }
true
53f0954bd0be54f670b56fd87b3968f71e3f7336
Java
TanishqBhardwaj/SplitItGo
/app/src/main/java/com/example/SplitItGo/Adapter/AllMemberAdapter.java
UTF-8
1,671
2.234375
2
[]
no_license
package com.example.SplitItGo.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.SplitItGo.Model.GroupItem; import com.example.SplitItGo.R; import java.util.ArrayList; public class AllMemberAdapter extends ArrayAdapter<GroupItem> { public AllMemberAdapter(Context context, ArrayList<GroupItem> allGroupList) { super(context, 0, allGroupList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } @Override public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { return initView(position, convertView, parent); } private View initView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.group_spinner_row, parent, false); } ImageView imageView = convertView.findViewById(R.id.imageViewGroupMemberImage); TextView textView = convertView.findViewById(R.id.textViewGroupMemberName); GroupItem groupItem = getItem(position); if(groupItem != null) { imageView.setImageResource(groupItem.getImageView()); textView.setText(groupItem.getmGroupMemberName()); } return convertView; } }
true
8f84cf08bd6ca00f7f10aec59679745cda8b0f8c
Java
tkob/yokohamaunit
/src/main/java/yokohama/unit/ast/PredicateVisitor.java
UTF-8
380
1.976563
2
[ "MIT" ]
permissive
package yokohama.unit.ast; public interface PredicateVisitor<T> { T visitIsPredicate(IsPredicate isPredicate); T visitIsNotPredicate(IsNotPredicate isNotPredicate); T visitThrowsPredicate(ThrowsPredicate throwsPredicate); T visitMatchesPredicate(MatchesPredicate matchesPredicate); T visitDoesNotMatchPredicate(DoesNotMatchPredicate doesNotMatchPredicate); }
true
60f91bbeac9ce9f0e811ad77b6f7ff1a6dfdbb97
Java
alextod/HibernateHandsOn
/src/main/java/com/home/model/Company.java
UTF-8
782
2.609375
3
[]
no_license
package com.home.model; import javax.persistence.Embeddable; /** * Created by atodorov on 1/23/2017. */ @Embeddable public class Company { private String title; private String city; public Company(){} public Company(String title, String city) { this.title = title; this.city = city; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Company{" + "title='" + title + '\'' + ", city='" + city + '\'' + '}'; } }
true
af97496c8cba673714a97ea3dc9fc580b76fe1c3
Java
AnujaKoralage/LiquorStockManagment
/LiquorStock/src/Entities/Supplier_order_confirmation.java
UTF-8
647
2.390625
2
[]
no_license
package Entities; public class Supplier_order_confirmation extends SuperEntity{ private int grnID; private String confirmation; public Supplier_order_confirmation() { } public Supplier_order_confirmation(int grnID, String confirmation) { this.grnID = grnID; this.confirmation = confirmation; } public int getGrnID() { return grnID; } public void setGrnID(int grnID) { this.grnID = grnID; } public String getConfirmation() { return confirmation; } public void setConfirmation(String confirmation) { this.confirmation = confirmation; } }
true
34ebe7efc61de0efcf36742e82041c43448d09bc
Java
radtek/ssms
/src/com/aspire/ponaadmin/common/rightmanager/RightDAO.java
GB18030
7,407
2.4375
2
[]
no_license
package com.aspire.ponaadmin.common.rightmanager ; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.aspire.common.db.DAOException; import com.aspire.common.db.DB; import com.aspire.common.log.proxy.JLogger; import com.aspire.common.log.proxy.LoggerFactory; /** * <p>ȨصDAO</p> * <p>ȨصDAO࣬Ȩڲ</p> * <p>Copyright (c) 2003-2005 ASPire TECHNOLOGIES (SHENZHEN) LTD All Rights Reserved</p> * @author zhangmin * @version 1.0.0.0 * @since 1.0.0.0 */ public class RightDAO { /** * ־ */ protected static JLogger logger = LoggerFactory.getLogger(RightDAO.class) ; /** * pageURIVOmap */ private HashMap pageURIMap = null; /** * ȨRightVOmap */ private HashMap rightMap = null; /** * singletonģʽʵ */ private static RightDAO instance = null ; /** * 췽singletonģʽ */ private RightDAO () throws DAOException { this.loadAllPageRUI(); this.loadAllRight(); } /** * ȡʵ * @return ʵ */ public static RightDAO getInstance () throws DAOException { if(instance == null) { instance = new RightDAO(); } return instance ; } /** * ȡһhttpuriӦҳڵȨ * @param pageURI httpuri * @return ҳӦȨ */ final RightVO getRightOfPageURI (String pageURI) { if (logger.isDebugEnabled()) { logger.debug("getRightOfPageURI(" + pageURI + ")") ; } RightVO right = null; PageURIVO page = (PageURIVO) this.pageURIMap.get(pageURI); if(page != null) { right = (RightVO) this.rightMap.get(page.getRightID()); } return right; } /** * ݿеpageURI */ private void loadAllPageRUI() throws DAOException { logger.debug("loadAllPageRUI()"); String sqlCode = "rightmanager.RightDAO.loadAllPageRUI().SELECT"; this.pageURIMap = new HashMap(); ResultSet rs = null; try { rs = DB.getInstance().queryBySQLCode(sqlCode, null); while(rs.next()) { PageURIVO page = this.getPageURIVO(rs); this.pageURIMap.put(page.getPageURI(), page); } } catch(SQLException e) { throw new DAOException(e); } finally { if(rs != null) { try { rs.close(); } catch(SQLException e) { logger.error(e); } } } } /** * ݿеȨRightVO */ private void loadAllRight() throws DAOException { logger.debug("loadAllRight()"); String sqlCode = "rightmanager.RightDAO.loadAllRight().SELECT"; this.rightMap = new HashMap(); //츴Ȩ޵ʱmap HashMap tmpParentMap = new HashMap(); ResultSet rs = null; try { rs = DB.getInstance().queryBySQLCode(sqlCode, null); while(rs.next()) { RightVO right = null; int levels = rs.getInt("levels"); String rightID = rs.getString("RIGHTID"); if(levels > 0) { //Ǹ right = new CompositeRightVO(); //ʱmapȡиȨ޵Ȩid List rightOfParent = (List) tmpParentMap.get(rightID); //ѾȨmapȡȨޣõȨ List rightListOfParent = new ArrayList(); for(int i = 0; i < rightOfParent.size(); i++) { rightListOfParent.add( this.rightMap.get(rightOfParent.get(i))) ; } ((CompositeRightVO) right).setRightList(rightListOfParent); } else { //Ǹ right = new RightVO(); } //ȨиȨޣijȨޣ //Ȩ޵id浽ʱmapУȵȨʱͿȡ String parentID = rs.getString("PARENTID"); if(parentID != null && parentID.trim().equals("")) { parentID = null; } if(parentID != null) { List rightOfParent = (List) tmpParentMap.get(parentID); if(rightOfParent == null) { rightOfParent = new ArrayList(); tmpParentMap.put(parentID, rightOfParent); } rightOfParent.add(rightID); } right.setRightID(rightID) ; right.setName(rs.getString("NAME")) ; right.setDesc(rs.getString("DESCS")) ; right.setParentID(parentID) ; this.rightMap.put(right.getRightID(), right) ; } } catch(SQLException e) { throw new DAOException(e); } finally { if(rs != null) { try { rs.close(); } catch(SQLException e) { logger.error(e); } } } } /** * ȡϵͳȨбվĿ¼Ȩޡ * @return list,Ȩб */ final List getAllRight () { if (logger.isDebugEnabled()) { logger.debug("getAllRight") ; } List rightList = new ArrayList(); rightList.addAll(this.rightMap.values()); return rightList ; } /** * ͨȨidȡȨϢ * @param rightID String Ȩid * @return RightVO ȨϢ */ final RightVO getRightVOByID(String rightID) { return (RightVO) this.rightMap.get(rightID); } /** * Ӽ¼ȡPageURIVO * @param rs ResultSet ¼ * @return PageURIVO PageURIVO * @throws SQLException */ private PageURIVO getPageURIVO(ResultSet rs) throws SQLException { PageURIVO page = new PageURIVO(); page.setRightID(rs.getString("RIGHTID")) ; page.setPageURI(rs.getString("PAGEURI")) ; page.setDesc(rs.getString("DESCS")) ; return page; } }
true
acd378b75d5738f8bc288abd65380b7311305197
Java
arunnair05/Septworkexamples
/src/test/java/org/arun/basic/Septworkexamples/web/pages/IndividualIncomePage.java
UTF-8
1,123
2.234375
2
[]
no_license
package org.arun.basic.Septworkexamples.web.pages; import static org.testng.Assert.assertTrue; import org.arun.basic.Septworkexamples.core.Log; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; public class IndividualIncomePage extends AbstractPage<IndividualIncomePage> { public IndividualIncomePage(WebDriver driver) { super(driver); } @FindBy(name = "borrowerIncome") public WebElement txtBorrowerIncome; @FindBy(name = "borrowerAdditionalIncome") public WebElement txtBorrowerAdditionalIncome; @FindBy(tagName = "button") public WebElement btnContinue; @Override protected void load() { wait.until(ExpectedConditions.urlContains("step=income")); wait.until(ExpectedConditions.visibilityOf(txtBorrowerAdditionalIncome)); wait.until(ExpectedConditions.visibilityOf(txtBorrowerIncome)); Log.info("Came inside Load of Individual Income "); } @Override protected void isLoaded() throws Error { assertTrue(driver.getCurrentUrl().contains("step=income")); } }
true
22b143479a7f6cf238bec07da6b199c801a2b1a5
Java
ahmetcagdasturan/Java-Bridge-Pattern-
/İsletimSistemi.java
UTF-8
237
2.078125
2
[]
no_license
public abstract class İsletimSistemi { private TestSeviye testSeviyesi; public İsletimSistemi(TestSeviye testSeviyesi) { this.testSeviyesi = testSeviyesi; } public void testeBasla() { testSeviyesi.testIslem(); } }
true
3ff48a5733ecc5adc65cfefafd575d3802ab1d74
Java
macalinao/PersonasAPI
/src/main/java/com/crimsonrpg/personas/personasapi/event/EventType.java
UTF-8
360
1.828125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.crimsonrpg.personas.personasapi.event; /** * Represents a type of event in Personas. */ public enum EventType { NPC_CREATE, NPC_DESPAWN, NPC_DESTROY, NPC_LEFT_CLICK, NPC_RIGHT_CLICK, NPC_SPAWN; }
true
098ef8ecef088da08130a023eec9ded02475e92b
Java
anishk33/ApigeeRules
/src/main/java/com/apigee/rules/helpers/DatatypeConverter.java
UTF-8
1,485
3.296875
3
[]
no_license
package com.apigee.rules.helpers; import com.apigee.rules.exception.DataNotFoundException; import com.apigee.rules.exception.InvalidDataException; import com.apigee.rules.models.Datatype; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; /** * A converter to create concrete objects from {@link String} values. * * @author Anish Kurian. */ public final class DatatypeConverter { /** * Converts the given {@link String} value to concrete data type based on given {@link Datatype}. * Checks the given data type and constructs object of appropriate type. * * @param value the value to be converted. * @param datatype the {@link Datatype}. * @return the converted object. * @throws InvalidDataException is given value is blank. * @throws DataNotFoundException if given data type conversion is not supported. */ public static Object convert(final String value, final Datatype datatype) { if (StringUtils.isBlank(value)) { throw new InvalidDataException("Cannot convert data type for value: " + value); } switch (datatype) { case STRING: return new String(value); case NUMBER: return NumberUtils.createDouble(value); default: throw new DataNotFoundException( String.format("Converter missing for datatype : %s!", datatype)); } } }
true
c95cdf8b132f5fca502e4f524239fce78c1d751e
Java
dude1410/social_network
/src/main/java/javapro/model/dto/PostDTO.java
UTF-8
877
1.867188
2
[]
no_license
package javapro.model.dto; import javapro.model.dto.auth.AuthorizedPerson; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; @Data public class PostDTO { @JsonProperty(value = "id") private Integer id; @JsonProperty(value = "time") private Long time; @JsonProperty(value = "author") private AuthorizedPerson author; @JsonProperty(value = "title") private String title; @JsonProperty(value = "post_text") private String postText; @JsonProperty(value = "is_blocked") private Boolean isBlocked; @JsonProperty(value = "likes") private Integer likes ; @JsonProperty(value = "comments") private List<CommentDTO> postComments; @JsonProperty(value = "type") private String postStatus; @JsonProperty(value = "tags") private List<TagDTO> tags; }
true
7ff9a0b599f68566b36d50a1171d1ae431f81705
Java
qvanphong/Simple-blog-api-with-Swagger
/src/main/java/tech/qvanphong/blog/repository/UserRepository.java
UTF-8
238
1.601563
2
[]
no_license
package tech.qvanphong.blog.repository; import org.springframework.data.repository.PagingAndSortingRepository; import tech.qvanphong.blog.model.User; public interface UserRepository extends PagingAndSortingRepository<User, Integer> { }
true
3190051ddf74d0949012108c2ca84d2a5f22505e
Java
BarCzerw/DesignPatterns
/src/main/java/designpatterns/behavioral/strategy/BankPayment.java
UTF-8
206
3.203125
3
[]
no_license
package designpatterns.behavioral.strategy; public class BankPayment implements Payment{ @Override public void pay(double price) { System.out.println("Paid " + price + " in bank"); } }
true
c29f36ed10f06421d10b0e97ea0550be00476fb6
Java
logan2013/tutorials
/spring-jwt/src/main/java/com/imtzp/jwt/security/util/JwtTokenGenerator.java
UTF-8
1,217
2.625
3
[]
no_license
package com.imtzp.jwt.security.util; import com.imtzp.jwt.security.transfer.JwtUserDto; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; public class JwtTokenGenerator { public static String generateToken(JwtUserDto u, String secret) { Claims claims = Jwts.claims().setSubject(u.getUsername()); claims.put("userId", u.getId()); claims.put("role", u.getRole()); return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact(); } public static void main(String[] args) { JwtUserDto user = new JwtUserDto(); user.setId(123L); user.setUsername("Pascal"); user.setRole("admin"); System.out.println("**************************************\n\n" + generateToken(user, "my-very-secret-key") + "\n\n**************************************"); /** * header和body是明文??? */ System.out.println(TextCodec.BASE64URL.decodeToString("eyJhbGciOiJIUzUxMiJ9")); System.out.println( TextCodec.BASE64URL.decodeToString("eyJzdWIiOiJQYXNjYWwiLCJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIn0")); System.out.println(TextCodec.BASE64URL.decodeToString( "tYfIzDTJBB7Nt8zZZUXzarbvHqKAB2-WQk_tlVyd0g9GwrpRVzEX4V5A91dd7-TcMmOPXTco8ysJncwHNk70AQ")); } }
true
d04d336612193a613a9bb773512148665300dfcf
Java
sdsaustin/sdsjava
/HelloJavaEE/src/HelloWorldServlet.java
UTF-8
1,424
2.640625
3
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HelloWorldServlet */ @WebServlet("/HelloWorldServlet") public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloWorldServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //read the request parameter String name=request.getParameter("name"); //get the writer PrintWriter writer=response.getWriter(); //set the MIME type response.setContentType("text/html"); // create a model and set it to the scope of request request.setAttribute("message","Hello "+name +" From JAVA Enterprise"); RequestDispatcher dispatcher=request.getRequestDispatcher("jsps/hello.jsp"); dispatcher.forward(request, response); } }
true
8469b5c4deea1b2ff2ff398a0ebd9b82f7387763
Java
moutainhigh/goddess-java
/modules/devicerepair/devicerepair-api/src/main/java/com/bjike/goddess/devicerepair/to/DeviceRepairTO.java
UTF-8
10,141
2.015625
2
[]
no_license
package com.bjike.goddess.devicerepair.to; import com.bjike.goddess.common.api.entity.ADD; import com.bjike.goddess.common.api.entity.EDIT; import com.bjike.goddess.common.api.to.BaseTO; import com.bjike.goddess.devicerepair.type.AuditState; import com.bjike.goddess.devicerepair.type.MaterialState; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 设备维修 * * @Author: [ sunfengtao ] * @Date: [ 2017-05-03 02:59 ] * @Description: [ ] * @Version: [ v1.0.0 ] * @Copy: [ com.bjike ] */ public class DeviceRepairTO extends BaseTO { /** * 地区 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "地区不能为空") private String area; /** * 项目组 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "项目组不能为空") private String projectGroup; /** * 项目名称 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "项目名称不能为空") private String projectName; /** * 申请人 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "申请人不能为空") private String applicant; /** * 设备名称 */ @NotBlank(groups = {EDIT.class}, message = "设备名称不能为空") private String deviceName; /** * 物资编号 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "物资编号不能为空") private String materialCoding; /** * 经手人 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "经手人不能为空") private String handler; /** * 设备负责人 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "设备负责人不能为空") private String devicePrincipal; /** * 设备出现的问题 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "设备出现的问题不能为空") private String deviceIssue; /** * 备注 */ private String comment; /** * 物资状态 */ @NotNull(groups = {EDIT.class}, message = "物资状态不能为空") private MaterialState materialState; /** * 保修期限(月) */ @NotNull(groups = {ADD.class, EDIT.class}, message = "保修期限(月)不能为空") private Double termOfService; /** * 是否在保修期 */ @NotNull(groups = {ADD.class, EDIT.class}, message = "是否在保修期不能为空") private Boolean whetherWarranty; /** * 保修联系人 */ private String warrantyContact; /** * 保修联系电话 */ private String warrantyContactPhone; /** * 购买网址/店铺 */ private String buyAddress; /** * 购买途径 */ private String purchaseWay; /** * 维修途径 */ private String repairWay; /** * 检测结果 */ private String detectResult; /** * 是否可维修 */ private Boolean whetherRepair; /** * 维修后使用期限 */ private String repairDeadline; /** * 维修价格 */ private Double repairPrice; /** * 预计维修好时间 */ private String planOverRepairTime; /** * 预计借款时间 */ private String planLoanTime; /** * 福利模块负责人 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "福利模块负责人不能为空") private String welfareModule; /** * 福利模块负责人审核状态 */ private AuditState welfareAuditState; /** * 项目经理 */ @NotBlank(groups = {ADD.class, EDIT.class}, message = "项目经理不能为空") private String pm; /** * 项目经理审核状态 */ private AuditState pmAuditState; /** * 厂家收款方式 */ private String venderReceiptMode; /** * 开户名称 */ private String accountName; /** * 开户账号 */ private String accountNumber; /** * 开户行 */ private String bankOfDeposit; /** * 是否付款 */ private Boolean whetherPayment; public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getProjectGroup() { return projectGroup; } public void setProjectGroup(String projectGroup) { this.projectGroup = projectGroup; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getApplicant() { return applicant; } public void setApplicant(String applicant) { this.applicant = applicant; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getMaterialCoding() { return materialCoding; } public void setMaterialCoding(String materialCoding) { this.materialCoding = materialCoding; } public String getHandler() { return handler; } public void setHandler(String handler) { this.handler = handler; } public String getDevicePrincipal() { return devicePrincipal; } public void setDevicePrincipal(String devicePrincipal) { this.devicePrincipal = devicePrincipal; } public String getDeviceIssue() { return deviceIssue; } public void setDeviceIssue(String deviceIssue) { this.deviceIssue = deviceIssue; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public MaterialState getMaterialState() { return materialState; } public void setMaterialState(MaterialState materialState) { this.materialState = materialState; } public Double getTermOfService() { return termOfService; } public void setTermOfService(Double termOfService) { this.termOfService = termOfService; } public Boolean getWhetherWarranty() { return whetherWarranty; } public void setWhetherWarranty(Boolean whetherWarranty) { this.whetherWarranty = whetherWarranty; } public String getWarrantyContact() { return warrantyContact; } public void setWarrantyContact(String warrantyContact) { this.warrantyContact = warrantyContact; } public String getWarrantyContactPhone() { return warrantyContactPhone; } public void setWarrantyContactPhone(String warrantyContactPhone) { this.warrantyContactPhone = warrantyContactPhone; } public String getBuyAddress() { return buyAddress; } public void setBuyAddress(String buyAddress) { this.buyAddress = buyAddress; } public String getPurchaseWay() { return purchaseWay; } public void setPurchaseWay(String purchaseWay) { this.purchaseWay = purchaseWay; } public String getRepairWay() { return repairWay; } public void setRepairWay(String repairWay) { this.repairWay = repairWay; } public String getDetectResult() { return detectResult; } public void setDetectResult(String detectResult) { this.detectResult = detectResult; } public Boolean getWhetherRepair() { return whetherRepair; } public void setWhetherRepair(Boolean whetherRepair) { this.whetherRepair = whetherRepair; } public String getRepairDeadline() { return repairDeadline; } public void setRepairDeadline(String repairDeadline) { this.repairDeadline = repairDeadline; } public Double getRepairPrice() { return repairPrice; } public void setRepairPrice(Double repairPrice) { this.repairPrice = repairPrice; } public String getPlanOverRepairTime() { return planOverRepairTime; } public void setPlanOverRepairTime(String planOverRepairTime) { this.planOverRepairTime = planOverRepairTime; } public String getPlanLoanTime() { return planLoanTime; } public void setPlanLoanTime(String planLoanTime) { this.planLoanTime = planLoanTime; } public String getWelfareModule() { return welfareModule; } public void setWelfareModule(String welfareModule) { this.welfareModule = welfareModule; } public AuditState getWelfareAuditState() { return welfareAuditState; } public void setWelfareAuditState(AuditState welfareAuditState) { this.welfareAuditState = welfareAuditState; } public String getPm() { return pm; } public void setPm(String pm) { this.pm = pm; } public AuditState getPmAuditState() { return pmAuditState; } public void setPmAuditState(AuditState pmAuditState) { this.pmAuditState = pmAuditState; } public String getVenderReceiptMode() { return venderReceiptMode; } public void setVenderReceiptMode(String venderReceiptMode) { this.venderReceiptMode = venderReceiptMode; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getBankOfDeposit() { return bankOfDeposit; } public void setBankOfDeposit(String bankOfDeposit) { this.bankOfDeposit = bankOfDeposit; } public Boolean getWhetherPayment() { return whetherPayment; } public void setWhetherPayment(Boolean whetherPayment) { this.whetherPayment = whetherPayment; } }
true
6438265b3a6118b028702716d5916b2d36925ef2
Java
flex-cle-fall-2018/we-can-read-it
/src/main/java/org/wecanreadit/ReaderController.java
UTF-8
14,313
1.984375
2
[]
no_license
package org.wecanreadit; import java.util.Collection; import java.util.Optional; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.annotation.Resource; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.util.WebUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.WebUtils; @Controller public class ReaderController { @Resource ReaderRepository readerRepo; @Resource GroupRepository groupRepo; @Resource GoalRepository goalRepo; @Resource DiscussionQuestionRepository questRepo; @Resource DiscussionAnswerRepository ansRepo; @Resource GroupBookRepository bookRepo; @Resource ReaderProgressRecordRepository readerProgressRecordRepo; @Resource MessageBoardPostRepository postRepo; @Resource LibrarianRepository libRepo; @Resource AuthService auth; @RequestMapping("/ReaderLogin") public String ReaderLoginPage() { return ("ReaderLogin"); } @PostMapping("/giveReaderPoints") public String giveReaderPoints(@RequestParam(required = true) String userName, int points, long groupId) { Reader reader = readerRepo.findByUsername(userName); reader.addPoints(points); readerRepo.save(reader); return "redirect:/group?id=" + groupId; } @RequestMapping("/questionlist") public String findQuestions(@CookieValue(value = "readerId") long readerId, Model model) { model.addAttribute("groups", readerRepo.findById(readerId).get().getGroups()); model.addAttribute("points", readerRepo.findById(readerId).get().getPoints()); return "groupquestionlist"; } @RequestMapping("/goalComplete/{groupId}/{goalId}") public String completeGoal(@CookieValue(value = "readerId") long readerId, @PathVariable("groupId") long groupId, @PathVariable("goalId") long goalId) { Goal goal = goalRepo.findById(goalId).get(); Reader reader = readerRepo.findById(readerId).get(); if (goal.containsReader(reader)) { return "redirect:/singlegroupquestions?id=" + groupId; } goal.addReader(reader); reader.addPoints(goal.getPoints()); goalRepo.save(goal); readerRepo.save(reader); return "redirect:/singlegroupquestions?id=" + groupId; } @RequestMapping("/singlegroupquestions") public String getSingleGroupsQuestions(@RequestParam(required = true) long id, @CookieValue(value = "readerId") long readerId, Model model) { ReadingGroup group = groupRepo.findById(id).get(); model.addAttribute("points", readerRepo.findById(readerId).get().getPoints()); Optional<Reader> identity = auth.getReaderIdentity(); if (identity.isPresent()) { Reader readerLoggedIn = identity.get(); Collection<Reader> readersInGroup = group.getAllMembers(); if (readersInGroup.contains(readerLoggedIn)) { model.addAttribute("group", group); model.addAttribute("books", group.getBooks()); model.addAttribute("questions", group.getQuestions()); model.addAttribute("goals", group.getGoals()); model.addAttribute("posts", group.getPosts()); model.addAttribute("reader", readerLoggedIn); return "singlegroupquestions"; } } return "notAuthorized"; } @PostMapping("/createnewreader") public String createNewReader(@CookieValue(value = "LibrarianId") long librarianId, String username, String password, String firstName, String lastName) { Reader reader = readerRepo.findByUsername(username); if (reader == null) { Reader newReader = new Reader(username, password, firstName, lastName); newReader.setLibrarian(libRepo.findById(librarianId).get()); readerRepo.save(newReader); } return "redirect:/readers"; } @PostMapping("/savePost") public String saveNewPost(@CookieValue(value = "readerId") long readerId, @RequestParam(required = true) String newPost, long groupid) { ReadingGroup group = groupRepo.findById(groupid).get(); Reader reader = readerRepo.findById(readerId).get(); MessageBoardPost post = postRepo.save(new MessageBoardPost(newPost)); group.addPost(post); post.setReader(reader); reader.savePost(post); groupRepo.save(group); postRepo.save(post); readerRepo.save(reader); return "redirect:/singlegroupquestions?id=" + groupid; } @RequestMapping("/readers") public String findAllReader(@CookieValue(required = false, value = "LibrarianId") Long librarianId, Model model) { if (librarianId != null) { Librarian lib = libRepo.findById(librarianId).get(); model.addAttribute("readers", lib.getAllReaders()); model.addAttribute("groups", lib.getAllGroups()); model.addAttribute("books", lib.getBooks()); return "readers"; } else { return "notAuthorized"; } } @RequestMapping("/reader") public String findAReader(@RequestParam(required = true) long id, Model model) { boolean isOwner = false; boolean isFriend = false; boolean isLibrarian = false; Reader profileOwner = readerRepo.findById(id).get(); Optional<Reader> readerIdentity = auth.getReaderIdentity(); Optional<Librarian> librarianIdentity = auth.getLibrarianIdentity(); if (librarianIdentity.isPresent() || readerIdentity.isPresent()) { if (readerIdentity.isPresent()) { model.addAttribute("points", readerIdentity.get().getPoints()); Reader readerLoggedIn = readerIdentity.get(); if(readerLoggedIn == profileOwner) { isOwner = true; } else { Collection<Reader> ownerFriends = profileOwner.getFriends(); if (ownerFriends.contains(readerLoggedIn)) { isFriend = true; } } } if (librarianIdentity.isPresent()) { Librarian librarian = librarianIdentity.get(); Collection<Reader> librarianReaders = librarian.getAllReaders(); if (librarianReaders.contains(profileOwner)) { isLibrarian = true; } } model.addAttribute("isOwner", isOwner); model.addAttribute("isFriend", isFriend); model.addAttribute("isLibrarian", isLibrarian); model.addAttribute("reader", profileOwner); model.addAttribute("readerProgressRecords", readerProgressRecordRepo.findByReader(profileOwner)); return "reader"; } return "notAuthorized"; } @RequestMapping("/groups") public String findAllGroups(@CookieValue(value = "LibrarianId") long librarianId, Model model) { Librarian lib = libRepo.findById(librarianId).get(); model.addAttribute("groups", lib.getAllGroups()); return "groups"; } @RequestMapping("/group") public String findAGroup(@RequestParam(required = true) long id, Model model) { ReadingGroup group = groupRepo.findById(id).get(); Optional<Librarian> librarianIdentity = auth.getLibrarianIdentity(); if(librarianIdentity.isPresent()) { model.addAttribute("group", group); model.addAttribute("readers", group.getAllMembers()); model.addAttribute("goals", group.getGoals()); model.addAttribute("questions", group.getQuestions()); model.addAttribute("groupBooks", group.getAllGroupBooks()); model.addAttribute("posts", group.getPosts()); return "group"; } return "notAuthorized"; } @PostMapping("/addQuestion") public String addQuestion(@RequestParam(required = true) String content, long id) { ReadingGroup group = groupRepo.findById(id).get(); group.addQuestion(questRepo.save(new DiscussionQuestion(content))); groupRepo.save(group); return "redirect:/group?id=" + id; } @RequestMapping(value = "/removeQuestion/{questId}/{groupId}") public String removeQuestion(@PathVariable("questId") long questId, @PathVariable("groupId") long groupId) { ReadingGroup group = groupRepo.findById(groupId).get(); DiscussionQuestion quest = questRepo.findById(questId).get(); group.removeQuestion(quest); groupRepo.save(group); questRepo.deleteById(questId); return "redirect:/group?id=" + groupId; } @GetMapping("/deleteGoal") public String deleteGoal(@RequestParam(required = true) String name, long id) { ReadingGroup group = groupRepo.findById(id).get(); Goal goal = goalRepo.findByName(name); group.removeGoal(goal); groupRepo.save(group); goalRepo.deleteById(goalRepo.findByName(name).getId()); return "redirect:/group?id=" + id; } @RequestMapping(value = "/removeGoal/{goalId}/{groupId}") public String removeGoal(@PathVariable("goalId") long goalId, @PathVariable("groupId") long groupId) { ReadingGroup group = groupRepo.findById(groupId).get(); Goal goal = goalRepo.findById(goalId).get(); group.removeGoal(goal); groupRepo.save(group); goalRepo.deleteById(goalId); return "redirect:/group?id=" + groupId; } @PostMapping("/addGoal") public String addAGoalToAGroup(@RequestParam(required = true) String name, long id, int pointValue) { ReadingGroup group = groupRepo.findById(id).get(); group.addGoal(goalRepo.save(new Goal(name, pointValue))); groupRepo.save(group); return "redirect:/group?id=" + id; } @PostMapping("/addGroup") public String createGroup(@CookieValue(value = "LibrarianId") long librarianId, @RequestParam(required = true) String groupName, String topic) { Librarian lib = libRepo.findById(librarianId).get(); ReadingGroup group = new ReadingGroup(groupName, topic); group.setLibrarian(lib); groupRepo.save(group); return "redirect:/groups"; } @GetMapping("/deleteGroup") public String deleteGroup(@RequestParam(required = true) String groupName) { ReadingGroup group = groupRepo.findByGroupName(groupName); Collection<GroupBook> groupBooks = bookRepo.findByReadingGroupsContains(group); for (GroupBook groupBook : groupBooks) { groupBook.removeReadingGroup(group); bookRepo.save(groupBook); } groupRepo.delete(group); return "redirect:/groups"; } @GetMapping("/deleteReader") public String deleteSingleReaderFromGroup(@RequestParam(required = true) String username, long id) { ReadingGroup group = groupRepo.findById(id).get(); group.removeMember(readerRepo.findByUsername(username)); groupRepo.save(group); return "redirect:/group?id=" + id; } @PostMapping("/addReader") public String addReaderToGroup(@RequestParam(required = true) String username, long id) { ReadingGroup group = groupRepo.findById(id).get(); Reader reader = readerRepo.findByUsername(username); group.addMember(reader); groupRepo.save(group); return "redirect:/group?id=" + id; } @PostMapping("/addbooktogroup") public String addBookToGroup(String title, long groupId) { ReadingGroup group = groupRepo.findById(groupId).get(); GroupBook book = bookRepo.findByTitle(title); group.addBook(book); groupRepo.save(group); return "redirect:/group?id=" + groupId; } @PostMapping("/saveanswer") public String saveAnswer(@CookieValue(value = "readerId") long readerId, @RequestParam(required = true) String answer, long id, long groupid) { DiscussionQuestion quest = questRepo.findById(id).get(); Reader reader = readerRepo.findById(readerId).get(); DiscussionAnswer newAnswer = ansRepo.save(new DiscussionAnswer(answer)); quest.addAnswer(newAnswer); reader.saveAnswer(newAnswer); newAnswer.setReader(reader); ansRepo.save(newAnswer); questRepo.save(quest); readerRepo.save(reader); return "redirect:/singlegroupquestions?id=" + groupid; } @RequestMapping("/addReaderProgressRecord") public String addReaderProgressRecord(long groupBookId, int monthFinished, int dayOfMonthFinished, int yearFinished, long readerId, Model model) { Optional<Reader> reader = readerRepo.findById(readerId); Reader readerResult = reader.get(); Optional<GroupBook> groupBook = bookRepo.findById(groupBookId); GroupBook groupBookResult = groupBook.get(); Collection<ReaderProgressRecord> readerProgressRecords = readerResult.getReaderProgressRecords(); for (ReaderProgressRecord readerProgressRecord : readerProgressRecords) { if (readerProgressRecord.getGroupBook().equals(groupBookResult)) { return "redirect:/groupBook?id=" + groupBookId; } } ReaderProgressRecord readerProgressRecord = new ReaderProgressRecord(groupBookResult, readerResult, monthFinished, dayOfMonthFinished, yearFinished); readerProgressRecordRepo.save(readerProgressRecord); return "redirect:/groupBook?id=" + groupBookId; } @RequestMapping("/removeReaderProgressRecord") public String removeReaderProgressRecord(@RequestParam long id) { Optional<ReaderProgressRecord> readerProgressRecord = readerProgressRecordRepo.findById(id); ReaderProgressRecord readerProgressResult = readerProgressRecord.get(); readerProgressResult.getReader().addPoints(-(readerProgressResult.getGroupBook().getPoints())); long readerId = readerProgressResult.getReader().getId(); readerProgressRecordRepo.delete(readerProgressResult); return "redirect:/reader?id=" + readerId; } @RequestMapping("/reader/{readerId}/friends") public String readerFriends(@PathVariable long readerId, Model model) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); Cookie readerIdCookie = WebUtils.getCookie(request, "readerId"); model.addAttribute("points", readerRepo.findById(readerId).get().getPoints()); if (readerIdCookie != null) { Long readerLoggedInId = new Long(readerIdCookie.getValue()); Reader readerLoggedIn = readerRepo.findById(readerLoggedInId).get(); Reader profileOwner = readerRepo.findById(readerId).get(); if (readerLoggedIn == profileOwner) { model.addAttribute("reader", readerRepo.findById(readerId).get()); model.addAttribute("friends", readerRepo.findById(readerId).get().getFriends()); model.addAttribute("pendingFriends", readerRepo.findById(readerId).get().getPendingFriends()); model.addAttribute("pendingFriendOf", readerRepo.findById(readerId).get().getPendingFriendOf()); return "readerFriends"; } } return "notAuthorized"; } }
true
d4e534080340f5c7e7ac5b6aeac994e239eb4fb7
Java
Kalon1997/OverchargeIndicatorAndroidApp
/MainActivity.java
UTF-8
3,891
2.0625
2
[]
no_license
package com.example.kalon.overchargeindicator; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import java.util.Calendar; public class MainActivity extends AppCompatActivity { private TextView chargeText; private BroadcastReceiver br = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int level=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0); chargeText.setText(String.valueOf(level) + "%"); IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); // boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || // status == BatteryManager.BATTERY_STATUS_FULL; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chargeText=(TextView)this.findViewById(R.id.textview); this.registerReceiver(this.br, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); Calendar cal=Calendar.getInstance(); int year=Calendar.getInstance().get(Calendar.YEAR); int month=Calendar.getInstance().get(Calendar.MONTH); int day_of_month=Calendar.getInstance().get(Calendar.DAY_OF_MONTH); int hr=Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int min=Calendar.getInstance().get(Calendar.MINUTE); cal.set(Calendar.MONTH,month); cal.set(Calendar.YEAR,year); cal.set(Calendar.DAY_OF_MONTH,day_of_month); cal.set(Calendar.HOUR_OF_DAY,20); cal.set(Calendar.MINUTE,27); Intent intent = new Intent(this, Aclass.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); //String value = chargeText.getText().toString(); //int desiredValue = Integer.parseInt(value); // alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show(); //Intent intent = new Intent(this, Mote.class); //PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA); // AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); // alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent ); // Toast.makeText(this, "Alarm worked.", Toast.LENGTH_LONG).show(); //IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); //Intent batteryStatus = context.registerReceiver(null, ifilter); //int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); // isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || // status == BatteryManager.BATTERY_STATUS_FULL; } }
true
88db2b97d1715644150f9d0f936b09245bd2bee2
Java
codeyeri7/DaBID
/backend/src/main/java/com/ssafy/api/service/WishService.java
UTF-8
485
1.851563
2
[]
no_license
package com.ssafy.api.service; import com.ssafy.api.response.LiveRes; import com.ssafy.db.entity.Live; import com.ssafy.db.entity.User; import com.ssafy.db.entity.WishList; import java.util.List; public interface WishService { List<WishList> getWishLives(User user); void putWishLive(User user, int prdId); void deleteWishLive(User user, int prdId); boolean checkWishLive(User user, int prdId); List<LiveRes> getBestLives(); int getLiveHearts(Live live); }
true
97aa9096a73969c738bc59b9d82a711437af05b5
Java
cwly101/java-reflection-demo
/java-mianshi-demo/src/com/mianshi/AtomicReferenceDemo.java
GB18030
978
3.5625
4
[]
no_license
package com.mianshi; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; import java.util.concurrent.atomic.AtomicReference; @Getter @AllArgsConstructor @ToString class Student{ private String name; private Integer age; } /** * AtomicReference Զԭʾ * @author caowei * @create 2020/1/29 */ public class AtomicReferenceDemo { public static void main(String[] args) { Student tom = new Student("tom",20); Student will = new Student("will", 36); // Զԭ AtomicReference<Student> atomicReference = new AtomicReference<>(); atomicReference.set(tom); // Ƚϲ滻 System.out.println(""+atomicReference.compareAndSet(tom, will)+"\t"+atomicReference.get().toString()); System.out.println(""+atomicReference.compareAndSet(tom, will)+"\t"+atomicReference.get().toString()); } }
true
fac1ec1790db0da94630b27f8426d5c9bcf8f027
Java
yaitsmesj/NewsRead
/app/src/main/java/com/example/suraj/newsread/SourceNewsActivity.java
UTF-8
1,129
2.453125
2
[]
no_license
package com.example.suraj.newsread; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import com.example.suraj.newsread.fragments.NewsFragment; import com.example.suraj.newsread.models.Articles; public class SourceNewsActivity extends AppCompatActivity implements NewsFragment.OnListFragmentInteractionListener { private static final String TAG = "Error"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_source_news); String source = getIntent().getStringExtra("SOURCE"); Log.d(TAG, "onCreate: SourceNewsAcitvity"); Fragment fragment = NewsFragment.getInstance(0, source); getSupportFragmentManager().beginTransaction() .add(R.id.fragment_Container, fragment) .commit(); Log.d(TAG, "onCreate: "); } @Override public void onListFragmentInteraction(Articles.BaseNews article) { Log.d(TAG, "onListFragmentInteraction: "); } }
true
34af7c93b034bcef636bbcee86a5e3bee49abc5f
Java
heisenberg2208/AgriTech
/FarmGuide/app/src/main/java/com/example/pankaj/farmguide/HeatMapActivity.java
UTF-8
2,051
2.25
2
[]
no_license
package com.example.pankaj.farmguide; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.TileOverlay; import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.maps.android.heatmaps.HeatmapTileProvider; import java.util.ArrayList; import java.util.List; public class HeatMapActivity extends AppCompatActivity implements OnMapReadyCallback { SupportMapFragment smf; GoogleMap gm; private HeatmapTileProvider mProvider; private TileOverlay mOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_heat_map); List<LatLng> list = null; smf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); smf.getMapAsync(this); list = readItems(); mProvider = new HeatmapTileProvider.Builder() .data(list) .build(); // Add a tile overlay to the map, using the heat map tile provider. mOverlay = gm.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider)); } public ArrayList<LatLng> readItems() { ArrayList<LatLng> list = new ArrayList<LatLng>(); list.add(new LatLng(15.02025, 16.0222)); list.add(new LatLng(15.025, 16.02)); list.add(new LatLng(15.020, 16.02263)); list.add(new LatLng(15.02015, 16.10222)); return list; } @Override public void onMapReady(GoogleMap googleMap) { gm = googleMap; LatLng latLng= new LatLng(-31,111); gm.addMarker(new MarkerOptions().position(latLng)); gm.moveCamera(CameraUpdateFactory.newLatLng(latLng)); } }
true
434129e78da40410a2b295c48bf9ce00c053d64e
Java
shermaza/DevelopmentKit
/src/com/artificial/cachereader/fs/IndexFile.java
UTF-8
1,956
2.34375
2
[ "MIT" ]
permissive
package com.artificial.cachereader.fs; import com.artificial.cachereader.DataSource; import com.artificial.cachereader.datastream.ByteStream; import com.artificial.cachereader.datastream.Stream; import com.artificial.cachereader.meta.ArchiveRequest; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class IndexFile { private static final int ENTRY_SIZE = 6; protected final DataSource source; protected final int cacheType; private ArchiveRequest[] metas; public IndexFile(DataSource system, int cacheType) { this.source = system; this.cacheType = cacheType; } public ArchiveRequest getArchiveMeta(int archive) { if (0 <= archive && archive < metas.length) return metas[archive]; else return null; } protected FileChannel getChannel() { return source.getIndexChannel(cacheType); } public void init() throws IOException { if (metas == null) { synchronized (this) { if (metas == null) { FileChannel channel = source.getIndexChannel(cacheType); int size = (int) channel.size(); ByteBuffer data = ByteBuffer.allocate(size); channel.read(data); Stream dataStream = new ByteStream(data.array()); decode(dataStream); } } } } private void decode(Stream dataStream) { int size = dataStream.getLeft(); int queryCount = size / ENTRY_SIZE; metas = new ArchiveRequest[queryCount]; for (int i = 0; i < metas.length; ++i) { metas[i] = getMeta(dataStream, i); } } private ArchiveRequest getMeta(Stream dataStream, int index) { return new ArchiveRequest(cacheType, index, dataStream.getUInt24(), dataStream.getUInt24()); } }
true
e050f3c8407cd325058d60f475e35724792c2f0f
Java
NicholasDowell/Contact-List-Group-Project
/src/MainMethod.java
UTF-8
1,829
3.890625
4
[]
no_license
import java.util.Scanner; /** * Tests all use cases and proves the program runs as specified. * @author Nick * */ public class MainMethod { public static void main(String[] args) { ContactList myList = new ContactList(); myList.read(); boolean notFinished = true; while (notFinished){ System.out.println(); System.out.print("You have a total of " + myList.getSize() + " contacts"); printMenu(); switch(getUserChoice()){ case 1: System.out.println("You chose option 1 to add a new contact:"); myList.addContact(); break; case 2: System.out.println("You chose option 2 for printing the entire contact list:"); myList.printAll(); break; case 3: System.out.println("You chose option 3 to search by last name:"); myList.find(); break; case 4: System.out.println("You chose option 4 to quit."); myList.write(); notFinished = false; break; } } } /** * Prints out the menu so the user can see the available options */ public static void printMenu(){ System.out.println(); System.out.println("**************************************************************"); System.out.println("MENU" + "\n"); System.out.println("1 - Enter a new person to the contact list (Last name required)" + "\n"); System.out.println("2 - Print the contact list" + "\n"); System.out.println("3 - Retrieve a person's information by last name" + "\n"); System.out.println("4 - Quit the program" + "\n"); System.out.println("*Please choose a number, then press Enter" + "\n" + "***************************************************************"); } /** * Gets an integer between 1 and 4 from the user * @return */ public static int getUserChoice(){ Scanner scan = new Scanner(System.in); return scan.nextInt(); } }
true
9123bb53cf36231cbba041c186101a419400712c
Java
guangheUlti/media_cms
/media-web/src/main/java/io/guangsoft/media/config/ShiroConfigProperties.java
UTF-8
2,778
1.773438
2
[]
no_license
package io.guangsoft.media.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @ConfigurationProperties(prefix = "guangsoft.shiro") public class ShiroConfigProperties { //最大尝试次数 private Integer maxRetryCount = 3; //第几次时需要使用验证码 private Integer showCaptchaRetryCount = 2; //凭证匹配器-算法 private String credentialsHashAlgorithmName = "md5"; //生成Hash值的迭代次数 private Integer credentialsHashIterations = 2; //表示是否存储散列后的密码为16进制,需要和生成密码时的一样 private Boolean credentialsStoredCredentialsHexEncoded = Boolean.TRUE; //全局session超时时间 1000*30*60milliseconds = 30 分钟(1800000) private Integer sessionGlobalSessionTimeout = 1800000; //session验证时间间隔(即验证会话是否还有效) 1000*60*60milliseconds = 1小时(3600000) private Integer sessionValidationInterval = 3600000; //session 缓存的名字 private String activeSessionCacheName = "activeSessionCache"; //CookieName private String sessionIdCookieName = "sessionId"; //CookieName private String sessionIdCookieDomain = ""; private String sessionIdCookiePath = "/"; private Boolean sessionIdCookieHttpOnly = Boolean.TRUE; //默认uid cookie 浏览器关闭后销毁 private Integer sessionIdCookieMaxAge = -1; //rememeber me cookie 名字 private String rememeberMeCookieName = "rememeberMe"; private String rememeberMeCookieDomain = ""; private String rememeberMeCookiePath = "/"; private Boolean rememeberMeCookieHttpOnly = Boolean.TRUE; //默认 rememberMe cookie 60 * 60 * 24 * 30 (30天) private Integer rememeberMeCookieMaxAge = 2592000; //cipherKey private String rememeberMeCookieBase64CipherKey = "KU471rVNQ6k7PQL4SqxgJg=="; //登录地址 private String loginUrl = "/login"; //退出地址 private String logoutSuccessUrl = "/login?logout=1"; //用户删除后 private String userNotfoundUrl = "/login?notfound=1"; //用户锁定地址 private String userLockedUrl = "/login?blocked=1"; //未知错误地址 private String userUnknownErrorUrl = "/login?unknown=1"; //未知错误地址 private String userForceLogoutUrl = "/login?forcelogout=1"; //没有授权地址 private String unauthorizedUrl = "/unauthorized"; //默认的登录成功页 private String defaultSuccessUrl = "/index"; //验证码是否开启 private Boolean jcaptchaEnable = Boolean.TRUE; //验证码错误时重定向的地址 private String jcaptchaErrorUrl = "/login?jcaptchaError=1"; //权限 private String filterChainDefinitions = ""; }
true
7ddd4dbc2654fc336465df3ac0f646bb05484534
Java
aidhog/swse
/src/org/semanticweb/swse/rank/master/MasterRankingArgs.java
UTF-8
2,207
1.984375
2
[]
no_license
package org.semanticweb.swse.rank.master; import org.deri.idrank.RankGraph; import org.semanticweb.swse.MasterArgs; import org.semanticweb.swse.RMIUtils; import org.semanticweb.swse.rank.RMIRankingServer; import org.semanticweb.swse.rank.SlaveRankingArgs; public class MasterRankingArgs extends MasterArgs<MasterRankingArgs>{ public static final RMIRankingServer DEFAULT_RI = new RMIRankingServer(); public static final MasterRanker DEFAULT_MASTER = new MasterRanker(); public static final String DEFAULT_RANKS_FILENAME_GZ = "ranks.nx.gz"; public static final String DEFAULT_RANKS_FILENAME_NGZ = "ranks.nx"; private boolean _gzoutranks = DEFAULT_GZ_OUT; private String _outranks = null; private SlaveRankingArgs _sra = null; private int _iters = RankGraph.ITERATIONS; private float _damping = RankGraph.DAMPING; public MasterRankingArgs(String outranks, SlaveRankingArgs sra){ _outranks = outranks; _sra = sra; } public void setGzRanksOut(boolean gzoutranks){ _gzoutranks = gzoutranks; } public boolean getGzRanksOut(){ return _gzoutranks; } public String getLocalRanksOut(){ return _outranks; } public void setIterations(int iters){ _iters = iters; } public int getIterations(){ return _iters; } public void setDamping(float damping){ _damping = damping; } public float getDamping(){ return _damping; } public SlaveRankingArgs getSlaveArgs(int server){ return _sra.instantiate(server); } public String toString(){ return "Master:: outranks:"+_outranks+" gzranks:"+_gzoutranks+" iters:"+_iters+" damp:"+_damping+"\n" +"Slave:: "+_sra; } public static final String getDefaultRanksOut(String outdir){ return getDefaultRanksOut(outdir, MasterArgs.DEFAULT_GZ_OUT); } public static final String getDefaultRanksOut(String outdir, boolean gz){ String outdirl = RMIUtils.getLocalName(outdir); if(gz) return outdirl+"/"+DEFAULT_RANKS_FILENAME_GZ; return outdirl+"/"+DEFAULT_RANKS_FILENAME_NGZ; } public RMIRankingServer getRMIInterface() { return DEFAULT_RI; } public MasterRanker getTaskMaster() { return DEFAULT_MASTER; } }
true