blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
c726738c304c9d1855825c839680fff9494595e1
3ee15bdf61159cec159c557dd8dddf7ab38e1da3
/src/main/java/com/deng/o2o/dao/ShopCategoryDao.java
e0fbc14014ce37d5d0ac8f874d7efc9b8c35e028
[]
no_license
dzh6386/school-o2o
5c3de4bddbbd58219cc21bf222d51080624b8d77
6287d8c078149ed9d9307334ca8e75654143ac87
refs/heads/master
2023-02-20T11:02:39.450065
2021-01-19T03:03:50
2021-01-19T03:03:50
330,840,954
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
package com.deng.o2o.dao; import com.deng.o2o.entity.ShopCategory; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ShopCategoryDao { List<ShopCategory> queryShopCategory(@Param("shopCategoryCondition") ShopCategory shopCategoryCondition); }
043063ef91c2216ba0d3712d8b3f0e5a86764f6d
94940580bcd569d86a08d21a3d65698a3f6c2e34
/src/spring/DependencyInjectionPropertiesSetter/FortuneServiceInterface.java
95cd23204ffd2a08b475a4904c6f9eaa7d926ca7
[ "Apache-2.0" ]
permissive
venkat-in/Spring-Hibernate
b8c5746f8981221182901bb9adfa3e451ba96da4
dbe2e9ca9e12fa54fdc246dae2cbe0de54e1fc48
refs/heads/master
2022-01-15T05:32:59.800990
2019-07-25T14:53:58
2019-07-25T14:53:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
131
java
package spring.DependencyInjectionPropertiesSetter; public interface FortuneServiceInterface { public String getFortune(); }
0491ac243a51472dec764dc6a52c47c17b662c34
3f1512fdd47a93cc7bd20c81f483e7c3aa5fa7ca
/Sympathetic_Arrays/SympatheticArrays.java
2b41984e7eb9efd9f65f10578ed867e299f26751
[]
no_license
natmortem/Java-tasks
a2496abc8ffebf7fa30f5947157eb57e9a8cfd91
2a15ef44cde1ce3e2a639eae0d99f3fe1c1ad7d0
refs/heads/master
2022-11-25T19:33:15.219451
2017-05-31T18:37:16
2017-05-31T18:37:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,833
java
package Sympathetic_Arrays; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class SympatheticArrays { private List<int[][]> listOfArrays; // здесь будут храниться массивы public static final String INPUT_FILE_PATH = "src/Sympathetic_Arrays/input.txt"; // путь к файлу входных данных public static final String OUTPUT_FILE_PATH = "src/Sympathetic_Arrays/output.txt"; // путь к файлу выходных файлов private void validateInputCountOfArrays(int base){ // количество возможных массивов if(base < 0 || base < 1 || base > 10){ throw new IllegalArgumentException("Input size should be > 0 and 1<= size <=10"); // будет выдавать ошибку } } public void readFile(String fileName) { // метод чтения файлов listOfArrays = new ArrayList<int[][]>(); // мы "загружаем" в список массивы try { Scanner input = new Scanner(new File(fileName).getAbsoluteFile()); // считыввается файл if(input.hasNextInt()){ // если есть следующий элемент, мы будем считывать данный файл int countOfArrays = input.nextInt(); // счёт массивов validateInputCountOfArrays(countOfArrays); // проверка данных } while (input.hasNextInt()){ // пока ещё есть следующие элементы, мы будем считывать файл int n = input.nextInt(); // данные по строкам int m = input.nextInt(); // данные по столбцам int[][] tmp = new int[n][m]; // создаём массив /не основная переменная/ for (int i = 0; i < n; i++) { // гуляемм по строкам for (int j = 0; j < m; j++) { // гуляем по столбцам int inputNumber = input.nextInt(); // числа из массивов tmp[i][j] = inputNumber; // записываем значения в массив } } listOfArrays.add(tmp); // добавляем массив в список } } catch (FileNotFoundException e) { e.printStackTrace(); // вернёт ошибку, в случае ошибки } } public void writeFile(String fileName, String result){ // медот вписывания данных в файл try { Writer writer = new FileWriter(fileName, true); // передаём имя файла, куда будем вписывать данные writer.append(result + "\n"); // записываем результат writer.flush(); // очищаем "место" writer.close(); // закрываем поток } catch (IOException e) { e.printStackTrace(); } } /* arrayOfNumbers.length - количество строк * arrayOfNumbers[0].length - количество столбцов * */ public String isSympathetic(int[][] arrayOfNumbers) { // метод проверки, являются ли массивы симпатичными for (int i = 0; i < arrayOfNumbers.length - 1; i++) { // проходимся по строкам for (int j = 0; j < arrayOfNumbers[0].length - 1; j++) { // проходим по столбцам if ( arrayOfNumbers[i][j + 1] == arrayOfNumbers[i][j] && // первый столбец сравниваем с нулевым столбцом arrayOfNumbers[i][j] == arrayOfNumbers[i + 1][j + 1] && //0-ой ст., 0-ой стр. сравниваем с след. ст. и стр. arrayOfNumbers[i][j] == arrayOfNumbers[i + 1][j] //0-ой ст., 0-ой стр. сравниваем со след. стр. этого же ст. ) { return "NO"; // если они все равны, то увы, этот массив не симпатичный } } } return "YES"; } public void checkArrays(){ readFile(INPUT_FILE_PATH); for (int[][] array : listOfArrays) { writeFile(OUTPUT_FILE_PATH, isSympathetic(array)); } } public static void main(String[] args) { SympatheticArrays sympatheticArrays = new SympatheticArrays(); sympatheticArrays.checkArrays(); } }
83d3cd372e71eed1017eeaeeda227cd22b23ff2c
a686429888b2d1dbb13456b2f50a26c26f688302
/TOTest/src/main/java/com/hand/TOPatterDemo.java
342b56eb274f3d2e7a5f5d535fdea46ef1bf59a7
[]
no_license
caojiameng/myproject
cea28ef45173ef964202564ebc5f2b418ec32745
feae2b7bfe90a2466c1be8360d11c445d1f4d8ed
refs/heads/master
2020-03-23T09:30:27.629923
2018-07-18T12:29:57
2018-07-18T12:29:57
141,391,869
0
0
null
null
null
null
UTF-8
Java
false
false
701
java
package com.hand; public class TOPatterDemo { public static void main(String[] args){ StudentBO studentBO = new StudentBO(); //输出所有学生 for (StudentVO studentVO : studentBO.getAllStudents()){ System.out.println("Student: [RollNo :"+studentVO.getRollNo()+",Name:"+studentVO.getName()+ "]"); } //更新学生 StudentVO student = studentBO.getAllStudents().get(0); student.setName("Mich"); studentBO.updateStudent(student); //获取学生 studentBO.getStudent(0); System.out.println("Student: [RollNo : " +student.getRollNo()+", Name : "+student.getName()+" ]"); } }
6a13299783cce88158b83994c2ae03d8d5954d2d
87d7e5a881ed5d4c44b3af6e1af62908075f4d0f
/src/main/java/br/ucs/easydent/app/dto/filtro/BaseFilter.java
c1aa4abd11bbd4e0bfce9d0566c3afb0e8eadea7
[]
no_license
lucasdoamaral/easydent-server
00a4bc989c061e5a7d35cddb494e1566fa612ed4
d5769cc69a135edc195a55bbddb6965690e31268
refs/heads/master
2021-01-09T20:41:06.893853
2017-08-01T20:13:46
2017-08-01T20:13:46
60,355,716
1
0
null
null
null
null
UTF-8
Java
false
false
252
java
package br.ucs.easydent.app.dto.filtro; import java.io.Serializable; import br.ucs.easydent.model.intf.Entidade; public abstract class BaseFilter <T extends Entidade> implements Serializable { private static final long serialVersionUID = 1L; }
c484452ec87daea485c3415671791a1861d1695d
0bf70b85b5a3f0fb51c6c3c45c2d8a7c4fa79a87
/net.solarnetwork.node/src/net/solarnetwork/node/setup/PKIService.java
22ebcc5daa22a830ef5f3443a7be346c9d65e36a
[]
no_license
Spudmn/solarnetwork-node
7a1839b41a1cd2d4e996caa8cb1d82baac3fcfeb
8701e756d91a92f76234c4b7a6e026528625b148
refs/heads/master
2021-01-15T11:03:11.181320
2014-11-06T20:21:13
2014-11-06T20:21:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,987
java
/* ================================================================== * PKIService.java - Dec 6, 2012 4:20:20 PM * * Copyright 2007-2012 SolarNetwork.net Dev Team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * ================================================================== */ package net.solarnetwork.node.setup; import java.security.cert.X509Certificate; import net.solarnetwork.support.CertificateException; /** * API for managing the node's certificate infrastructure. * * @author matt * @version 1.0 */ public interface PKIService { /** * Save the trusted CA certificate. * * <p> * The node maintains a root CA certificate for the SolarNet network it is * associated with. * </p> * * @param cert * the certificate * @throws CertificateException * if any certificate related error occurs */ void saveCACertificate(X509Certificate cert) throws CertificateException; /** * Get the configured CA certificate. * * @return the CA certificate, or <em>null</em> if not available * @throws CertificateException * if any certificate related error occurs */ X509Certificate getCACertificate() throws CertificateException; /** * Get the configured node certificate. * * @return the node certificate, or <em>null</em> if not available * @throws CertificateException * if any certificate related error occurs */ X509Certificate getNodeCertificate() throws CertificateException; /** * Check if the node's certificate is valid. * * <p> * The certificate is considered valid if it is signed by the given * authority and its chain can be verified and it has not expired. * </p> * * @param issuerDN * the expected issuer subject DN * * @return boolean <em>true</em> if considered valid * @throws CertificateException * if any certificate related error occurs */ boolean isNodeCertificateValid(String issuerDN) throws CertificateException; /** * Generate a new public and private key pair, and a new self-signed * certificate. * * @param dn * the certificate subject DN * @return the Certificate * @throws CertificateException * if any certificate related error occurs */ X509Certificate generateNodeSelfSignedCertificate(String dn) throws CertificateException; /** * Generate a PKCS#10 certificate signing request (CSR) for the node's * certificate. * * @return the PEM-encoded CSR * @throws CertificateException * if any certificate related error occurs */ String generateNodePKCS10CertificateRequestString() throws CertificateException; /** * Generate a PKCS#7 PEM encoding of the node's certificate. * * @return the PEM-encoded certificate * @throws CertificateException * if any certificate related error occurs */ String generateNodePKCS7CertificateString() throws CertificateException; /** * Generate a PKCS#7 PEM encoding of the node's certificate chain. * * @return the PEM-encoded certificate chain * @throws CertificateException * if any certificate related error occurs */ String generateNodePKCS7CertificateChainString() throws CertificateException; /** * Save a signed node certificate (previously created via * {@link #generateNodeSelfSignedCertificate(String)}). * * <p> * The issuer of the certificate must match the subject of the configured CA * certificate, and the certificate's subject must match the existing node * certificate's subject. * </p> * * @param certificateChain * the PKCS#7 signed certificate chain * @throws CertificateException * if any certificate related error occurs */ void saveNodeSignedCertificate(String certificateChain) throws CertificateException; /** * Save a PKCS#12 keystore as the node's certificate. * * <p> * The keystore can contain either a single self-signed certificate or a * signed certificate chain. * </p> * * @param keystore * the PKCS#12 keystore as a Base64 encoded string * @param password * the keystore password * @throws CertificateException * if any certificate related error occurs */ void savePKCS12Keystore(String keystore, String password) throws CertificateException; }
e6caf7d16304703b9cb03e4a22848f5cd227c9df
bfa1ff577cf9dd0d78983b1d185c1b1e2509ec9e
/src/util/Constants.java
3f1ecdbd90c5ae8119b8d147af5288a000b57106
[]
no_license
eren-murat/java-text-moba
e73f8d427d8bf24061c4305c749a14a86b6dd767
2ddf42c3873472af878a4df82d96fcb9506c41c9
refs/heads/master
2022-03-21T16:55:24.278074
2019-12-01T22:18:01
2019-12-01T22:18:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,439
java
package util; public final class Constants { private Constants() { } public static final int CHAMPION_TYPE = 0; public static final int CHAMPION_POS_X = 1; public static final int CHAMPION_POS_Y = 2; public static final float MODIFIER_5 = 0.05f; public static final float MODIFIER_10 = 0.1f; public static final float MODIFIER_15 = 0.15f; public static final float MODIFIER_20 = 0.2f; public static final float MODIFIER_25 = 0.25f; public static final float MODIFIER_30 = 0.3f; public static final float MODIFIER_40 = 0.4f; public static final int XP_INDICATOR = 200; public static final int XP_MULTIPLIER = 40; public static final int LEVEL_UP_XP = 250; public static final int LEVEL_UP_XP_GROWTH = 50; public static final int NAME_INDEX = 9; public static final int KNIGHT_HP = 900; public static final int KNIGHT_HP_GROWTH = 80; public static final float KNIGHT_TERRAIN_MODIFIER = 0.15f; public static final char KNIGHT_PREFERRED_TERRAIN = 'L'; public static final float KNIGHT_ABILITY_1_BASE = 200f; public static final float KNIGHT_ABILITY_1_GROWTH = 30f; public static final float KNIGHT_ABILITY_2_BASE = 100f; public static final float KNIGHT_ABILITY_2_GROWTH = 40f; public static final float KNIGHT_HP_PERCENT_INITIAL = 0.2f; public static final float KNIGHT_HP_PERCENT_GROWTH = 0.01f; public static final float KNIGHT_HP_PERCENT_CAP = 0.4f; public static final int KNIGHT_INCAPACITATION_ROUNDS = 1; public static final int PYROMANCER_HP = 500; public static final int PYROMANCER_HP_GROWTH = 50; public static final float PYRO_TERRAIN_MODIFIER = 0.25f; public static final char PYRO_PREFERRED_TERRAIN = 'V'; public static final float PYRO_ABILITY_1_BASE = 350f; public static final float PYRO_ABILITY_1_GROWTH = 50f; public static final float PYRO_ABILITY_2_BASE = 150f; public static final float PYRO_ABILITY_2_GROWTH = 20f; public static final float PYRO_OVERTIME_BASE = 50f; public static final float PYRO_OVERTIME_GROWTH = 30f; public static final int PYRO_OVERTIME_ROUNDS = 2; public static final int ROGUE_HP = 600; public static final int ROGUE_HP_GROWTH = 40; public static final float ROGUE_TERRAIN_MODIFIER = 0.15f; public static final char ROGUE_PREFERRED_TERRAIN = 'W'; public static final float ROGUE_ABILITY_1_BASE = 200f; public static final float ROGUE_ABILITY_1_GROWTH = 20f; public static final float ROGUE_ABILITY_2_BASE = 40f; public static final float ROGUE_ABILITY_2_GROWTH = 10f; public static final int ROGUE_OVERTIME_ROUNDS = 3; public static final int ROGUE_OVERTIME_ROUNDS_WOODS = 6; public static final float ROGUE_CRITICAL_HIT_MULTIPLIER = 1.5f; public static final int ROGUE_CRITICAL_HIT_CHANCE = 3; public static final int WIZARD_HP = 400; public static final int WIZARD_HP_GROWTH = 30; public static final float WIZARD_TERRAIN_MODIFIER = 0.1f; public static final char WIZARD_PREFERRED_TERRAIN = 'D'; public static final float WIZARD_ABILITY_1_BASE = 0.2f; public static final float WIZARD_ABILITY_1_GROWTH = 0.05f; public static final float WIZARD_ABILITY_1_PERCENT = 0.3f; public static final float WIZARD_ABILITY_2_BASE = 0.35f; public static final float WIZARD_ABILITY_2_GROWTH = 0.02f; public static final float WIZARD_ABILITY_2_CAP = 0.7f; }
659b46b46a6b1cfc1f7948f1d97a28c561e2112a
5fae52c87187940e17dcf1d6681c9a29dd6b0ff7
/src/main/java/Annabelle/RTreePushUp.java
8298366cf28e4aadd7bdca24b160631677e1823b
[]
no_license
DaliaW/Database-Engine-using-Java
26ca8f29d10cb33f268ff10ac4f339ba9ecc2474
ff34fe6f9629567b7562fb0098e14fa54f51196b
refs/heads/master
2022-11-06T10:21:37.333024
2020-06-18T18:48:46
2020-06-18T18:48:46
260,579,044
1
0
null
null
null
null
UTF-8
Java
false
false
406
java
package Annabelle; import java.io.IOException; public class RTreePushUp { /** * This class is used for push keys up to the inner nodes in case * of splitting at a lower level */ RTreeNode newNode; Comparable key; public RTreePushUp(RTreeNode newNode, Comparable key) throws ClassNotFoundException, IOException { this.newNode = newNode; this.key = key; this.newNode.refresh(); } }
06d1c1f843ac0fbcb8b35498c574e33a277170eb
19086df3e5933b6ec1d8f6dd157c80d751955c4f
/app/src/main/java/androidcodingchallenge/balagunateja/karlapudi/android_coding_test/CreateUserActivity.java
1344e725ab5a8f8b4c2fb69d6d10057d11077d57
[]
no_license
teja2495/Android_Coding_Test
a7e37098aa251bbdc62be570dcc0de374bb3b479
c7e0f124a724c3f6fceb29ecc97f440b8870fe53
refs/heads/master
2020-05-23T09:27:38.114841
2019-05-16T05:05:14
2019-05-16T05:05:14
186,706,911
0
0
null
null
null
null
UTF-8
Java
false
false
4,964
java
package androidcodingchallenge.balagunateja.karlapudi.android_coding_test; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class CreateUserActivity extends AppCompatActivity { Button submit, back; EditText name, job; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_user); submit = findViewById(R.id.buttonSubmit); name = findViewById(R.id.editTextName); job = findViewById(R.id.editTextJob); back = findViewById(R.id.backButton); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!isConnected()) { Toast.makeText(CreateUserActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show(); } else if(name.getText().toString().isEmpty() || job.getText().toString().isEmpty()) { Toast.makeText(CreateUserActivity.this, "Missing Values!", Toast.LENGTH_SHORT).show(); } else{ JSONObject jsonPostBody = new JSONObject(); try { String url = "https://reqres.in/api/users"; jsonPostBody.put("name", name.getText().toString()); jsonPostBody.put("job", job.getText().toString()); postData(url, jsonPostBody.toString()); } catch (JSONException e) { e.printStackTrace(); } } } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent myIntent = new Intent(CreateUserActivity.this, UserActivity.class); startActivity(myIntent); finish(); } }); } void postData(String url, String json) { OkHttpClient client = new OkHttpClient(); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { runOnMainThread(CreateUserActivity.this, "Error, User creating Failed! Try Again."); } @Override public void onResponse(Call call, Response response) throws IOException { try { JSONObject json = new JSONObject(response.body().string()); String msg = "User " + json.getString("name") + " created!"; runOnMainThread(CreateUserActivity.this, msg); } catch (JSONException e) { e.printStackTrace(); runOnMainThread(CreateUserActivity.this, "Error, User creating Failed! Try Again."); } } }); } void runOnMainThread(final Context context, final String msg) { if (context != null && msg != null) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); Intent myIntent = new Intent(CreateUserActivity.this, UserActivity.class); startActivity(myIntent); finish(); } }); } } private boolean isConnected() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected() || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI && networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) { return false; } return true; } }
868c5cb10982cfddbba117bf86ccbbdcb0c66e66
c5a397c1a3c69653ce3996c099b22cea948d4958
/src/man/java/fr/aekys/aekbotdev/commands/Command.java
72b93fc928b79951e48c3f86ba5705a0a3f9dc61
[ "MIT" ]
permissive
ImAekys/Aek-Dev
820ee3d6d81560f705576cbca564e1a9570ea44c
a00795761a28ca0eb8cea5c28cfd24c239ff9a38
refs/heads/master
2021-08-23T21:46:30.250387
2017-12-06T17:55:48
2017-12-06T17:55:48
113,345,078
0
1
null
2017-12-06T17:54:30
2017-12-06T17:10:49
Java
UTF-8
Java
false
false
384
java
package fr.aekys.aekbotdev.commands; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; /** * Creating by Aven at 06.12.2017 * **/ public interface Command { public boolean called(String args[], MessageReceivedEvent event); public void action(String args[], MessageReceivedEvent event); public void executed(boolean flag, MessageReceivedEvent event); }
8b4af9a3823853ab280ee7caa8b0a2b582982367
361b3eaf507f271b5cedf900b199d9d2d791bb82
/src/world/boss/slick/SlickRockDebris.java
6494f598fee120f5a111f5d1cc2fe83bd8f52db0
[]
no_license
hubol/2-desktop
cc4ad0368b7c3b43173664ec9daf3617777b7608
6946f6697cd19233655dbf8df0a5149c8ddd7be1
refs/heads/master
2022-11-29T05:33:52.003450
2020-07-24T15:12:29
2020-07-24T15:12:29
282,241,421
3
0
null
null
null
null
UTF-8
Java
false
false
814
java
package world.boss.slick; import world.control.Sound; import graphics.Sprite; import main.Calc; import main.Entity; public class SlickRockDebris extends Entity{ public boolean fuck; public SlickRockDebris(double x, double y) { super(x, y); sprite = Sprite.get("sSlickRockDebris"); imageSingle = (int)Calc.random(4); imageSpeed = 0; hspeed = Calc.rangedRandom(7.5); vspeed = -4 - Calc.random(6); angle = Calc.random(360); fuck = false; setDepth(-4); } public void step(){ if (!fuck){ vspeed += .8; hspeed *= .96; } else{ alpha -= .02; if (alpha <= 0) destroy(); } super.step(); if (y >= 378 && vspeed > 0 && !fuck){ Sound.playPitched("sSlickDebrisLand", .5); hspeed = 0; vspeed = 0; fuck = true; } if (y >= 480) destroy(); } }
1c0e767d60eedf4bceb9fae7fff0a0ed81fb8585
98d313cf373073d65f14b4870032e16e7d5466f0
/gradle-open-labs/example/src/main/java/se/molybden/Class13350.java
8fdabdf035f522006374b538ba7a6cdd63ff5224
[]
no_license
Molybden/gradle-in-practice
30ac1477cc248a90c50949791028bc1cb7104b28
d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3
refs/heads/master
2021-06-26T16:45:54.018388
2016-03-06T20:19:43
2016-03-06T20:19:43
24,554,562
0
0
null
null
null
null
UTF-8
Java
false
false
110
java
public class Class13350{ public void callMe(){ System.out.println("called"); } }
d546040ae3be8d2f0cf3f10e1b7f2e2b1e5263b1
904b4c1dc8f6ee419acbcf92c4308da79c231e77
/src/main/java/com/neyas/spring5recipeapp/commands/NotesCommand.java
82297b26008b46de2cc2133099cddc6b0609575b
[]
no_license
neyas/spring5-recipe-app
0331f7b67a757cccd2d600965f1e827594080ef1
57e55bb38522605542c30e90306c66aa07059450
refs/heads/master
2020-03-19T05:05:55.390563
2018-06-06T17:31:38
2018-06-06T17:31:38
135,899,579
0
0
null
2018-06-06T17:31:39
2018-06-03T11:50:16
Java
UTF-8
Java
false
false
242
java
package com.neyas.spring5recipeapp.commands; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class NotesCommand { private Long id; private String recipeNotes; }
79528362dd1dab50e4200c53d034d4259c0d3320
3dba4508e25343a508102173715e269ea77ace3b
/src/SeleniumSessions/FrameHandling.java
df8daafccef6312c245c5760a472542c5ce150a9
[]
no_license
parimalahc/JavaTrainingSessionRepo
a7e199c3c8a987434abbe78c38607529233483ac
8a8f39f17a8d0f20f2a10d2c579d202b9d7bfa9f
refs/heads/master
2020-06-12T01:12:02.330261
2019-06-26T20:21:20
2019-06-26T20:21:20
194,147,738
0
0
null
null
null
null
UTF-8
Java
false
false
1,023
java
package SeleniumSessions; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FrameHandling { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\USER\\Downloads\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.get("https://www.crmpro.com/index.html"); driver.findElement(By.name("username")).sendKeys("naveenk"); driver.findElement(By.name("password")).sendKeys("test@123"); Thread.sleep(3000); driver.switchTo().frame("mainpanel"); Thread.sleep(2000); driver.findElement(By.xpath("//a[contains(text(),'Contacts')]")).click(); } }
0e15197b5f06f18f20fb831bf68a69848fa88ccf
989ba8bd241b171a9bf7c3d985a62c6a5cd30591
/src/main/java/org/fiware/apps/repository/model/ResourceFilter.java
15ad65a72c8ffa40a656c13cbafdcedd3358bb1f
[ "BSD-3-Clause" ]
permissive
service-business-framework/Repository-RI
17e22a96067ca8feb03bf2c48a37b2074e7f89d3
5dcd3ac78927fa98e96e14af9e35dad9eb346d56
refs/heads/master
2021-01-01T15:51:17.230772
2013-11-08T09:56:50
2013-11-08T09:56:50
6,793,252
1
0
null
null
null
null
UTF-8
Java
false
false
1,244
java
package org.fiware.apps.repository.model; import java.util.regex.Pattern; import com.mongodb.BasicDBObject; public class ResourceFilter { private int offset; private int limit; private String filter=""; public ResourceFilter(int offset, int limit, String filter) { super(); this.offset = offset; this.limit = limit; this.filter = filter == null ? "" : filter; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public BasicDBObject parseFilter(){ BasicDBObject query = new BasicDBObject(); String[] filterStrings = this.filter.split(","); boolean added = false; for (int i=0; i<filterStrings.length; i++) { String[] filter = filterStrings[i].split(":"); if(filter.length==2){ Pattern p = Pattern.compile(filter[1], Pattern.CASE_INSENSITIVE); query.append(filter[0], p); added=true; } } if(!added){ Pattern pat = Pattern.compile(""); query.append("id", pat); } return query; } }
4a62f172005c28854afc3deb6a5dd3e20057e845
3d6f3f5184849eee01bc45d1f20a357a36bea23d
/Stox 3 2/app/src/main/java/com/stox/data/TickFetcher.java
fad9da05e5a45c39a4a5569166186821a79fc650
[]
no_license
ChristianC23/4900-Stox
388ec8520058b23e7542a22386337309c19ed7e2
31bc9922b154dfb76513fcb788f0906d6f6d1beb
refs/heads/master
2020-05-26T03:18:15.586190
2019-05-22T18:03:06
2019-05-22T18:03:06
188,088,791
0
0
null
null
null
null
UTF-8
Java
false
false
2,556
java
package com.stox.data; import android.os.Process; import android.util.Log; import org.patriques.AlphaVantageConnector; import org.patriques.TimeSeries; import org.patriques.input.timeseries.Interval; import org.patriques.input.timeseries.OutputSize; import org.patriques.output.AlphaVantageException; import org.patriques.output.timeseries.IntraDay; import org.patriques.output.timeseries.data.StockData; import java.util.List; public class TickFetcher { // singleton instance private static final TickFetcher instance = new TickFetcher(); private TickFetcher() { } public static TickFetcher getInstance() { return instance; } /** * Returns the list of data points for the given stock symbol and interval. * @param stockSymbol symbol (AMZN, MSFT, etc.) * @param interval interval (ONE_MIN, FIFTEEN_MIN, etc.) * @return list of data points */ public List<StockData> getData(final String stockSymbol, final Interval interval) { final FetchRunnable fetchRunnable = new FetchRunnable(stockSymbol, interval); final Thread thread = new Thread(fetchRunnable); thread.run(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return fetchRunnable.stockData; } /** * A job class for the actual data fetch, so that we can run it on a background thread. */ private static class FetchRunnable implements Runnable { String stockSymbol; Interval interval; List<StockData> stockData; public FetchRunnable(final String stockSymbol, final Interval interval) { this.stockSymbol = stockSymbol; this.interval = interval; } @Override public void run() { // send this thread to the background Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // connect to AlphaVantage with our API key final AlphaVantageConnector connector = new AlphaVantageConnector("1NDS61W4M4GFPFJA", 3000); // get and return data final TimeSeries stockTimeSeries = new TimeSeries(connector); try { final IntraDay response = stockTimeSeries.intraDay(stockSymbol, interval, OutputSize.FULL); stockData = response.getStockData(); } catch (final AlphaVantageException e) { Log.e("FETCHER", "exception while fetching tick data", e); } } } }
2465385805a0d15bb29aec5673440e334099a69f
3289fdc3374885ee2debb7fdda0fbb17c1f39f92
/代码/ssm_exam/ssm_exam_web/src/main/java/com/itheima/controller/PermissionController.java
d269184aadb5fc28c13aa16c46628585039716fb
[]
no_license
ChunGeHu/repostoryTest1
80fad755af80d9572280249027dbeecc78c93935
3cfb8c95b7aa135a187861be29203b22a49b0e37
refs/heads/master
2020-07-06T17:36:46.901662
2019-08-19T03:12:04
2019-08-19T03:12:04
203,092,129
3
0
null
null
null
null
UTF-8
Java
false
false
3,224
java
package com.itheima.controller; import com.itheima.domain.Permission; import com.itheima.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpSession; import java.util.List; /** * @Author 王磊 * @Date 2019/8/16/016 */ @Controller @RequestMapping(path = "/permission") public class PermissionController { @Autowired private PermissionService permissionService ; /** * 查询所有权限信息 * @return */ @RequestMapping(path = "/findAll") public String findAll(Model model){ //调用业务层查询数据 List<Permission> permissions = permissionService.findAll(); //将查询结果存入到Model中 model.addAttribute("permissions",permissions); //跳转视图 return "permission-list"; } /** * 添加权限信息 * @return */ @RequestMapping(path = "/add") public String add(Permission permission){ //调用业务层添加数据 permissionService.add(permission); //跳转视图 return "redirect:/permission/findAll" ; } /** * 查询所有的可以添加的权限信息 * @return */ @RequestMapping(path = "/findAdditablePermission") public String findAdditablePermission(Model model , String roleId){ //调用业务层查询数据 List<Permission> permissions = permissionService.findAdditablePermission(roleId); //将查询到的数据保存到Model中 model.addAttribute("permissions",permissions); model.addAttribute("roleId",roleId); //跳转视图 return "role-permission-add" ; } /** * 给角色添加权限 * @return */ @RequestMapping(path = "/addPermissions2Role") public String addPermissions2Role(String roleId,String[] ids){ //调用业务层添加数据 permissionService.addPermissions2Role(roleId,ids); //跳转视图 return "redirect:/role/findAll"; } /** * 查询用户菜单 * @return */ @RequestMapping(path = "/findMenus") public String findMenus(HttpSession session){ //从SpringSecurity中获取登录用户信息 //SecurityContext securityContext = SecurityContextHolder.getContext();//获取spring security的上下文对象 //Authentication authentication = securityContext.getAuthentication(); //获取认证对象 //获取当前登录用户名 String username = SecurityContextHolder.getContext().getAuthentication().getName(); //调用Service菜单数据 List<Permission> permissions = permissionService.findMenus(username); //将数据保存session中 session.setAttribute("menus",permissions); //跳转视图 return "redirect:/main.jsp"; } }
dd88dc08770a9d4040d79973fb861011569aee44
9507965cb7c50e863f80507641469e58b4736a8b
/src/Chp3_Stacks_and_Queues/Q6AnimalQueue.java
83a264ee866374f241a165816f0d1d3f720e277a
[]
no_license
ShijiZ/Cracking_the_Coding_Interview
79b2bf983321907c474e9886f70565460eb4a06c
a02be7d412ae9a1637bd17dd959ece3ad70d9527
refs/heads/master
2023-02-10T22:23:09.585336
2021-01-08T06:07:20
2021-01-08T06:07:20
208,915,168
0
0
null
null
null
null
UTF-8
Java
false
false
2,327
java
package Chp3_Stacks_and_Queues; import java.util.LinkedList; public class Q6AnimalQueue { LinkedList<Dog> dogs = new LinkedList<>(); LinkedList<Cat> cats = new LinkedList<>(); private int order = 0; public void enqueue(Animal a){ a.setOrder(order); order++; if (a instanceof Dog) dogs.addLast((Dog) a); else if (a instanceof Cat) cats.addLast((Cat) a); } public Animal dequeueAny(){ if (dogs.size() == 0) return dequeueCat(); if (cats.size() == 0) return dequeueDog(); Dog dog = dogs.peek(); Cat cat = cats.peek(); if (dog.isOlderThan(cat)) return dequeueDog(); else return dequeueCat(); } public Dog dequeueDog(){ return dogs.poll(); } public Cat dequeueCat(){ return cats.poll(); } public int size(){ return dogs.size() + cats.size(); } public static void main(String[] args) { Q6AnimalQueue animals = new Q6AnimalQueue(); animals.enqueue(new Cat("Callie")); animals.enqueue(new Cat("Kiki")); animals.enqueue(new Dog("Fido")); animals.enqueue(new Dog("Dora")); animals.enqueue(new Cat("Kari")); animals.enqueue(new Dog("Dexter")); animals.enqueue(new Dog("Dobo")); animals.enqueue(new Cat("Copa")); System.out.println(animals.dequeueAny().name); System.out.println(animals.dequeueAny().name); System.out.println(animals.dequeueAny().name); animals.enqueue(new Dog("Dapa")); animals.enqueue(new Cat("Kilo")); while (animals.size() != 0) { System.out.println(animals.dequeueAny().name); } } } abstract class Animal{ int order; protected String name; public Animal(String name){ this.name = name; } public void setOrder(int order){ this.order = order; } public int getOrder(){ return order; } /* Compare orders of animals to return the older item. */ public boolean isOlderThan(Animal a){ return this.order < a.order; } } class Dog extends Animal{ public Dog(String n){ super(n); } } class Cat extends Animal{ public Cat(String n){ super(n); } }
72298a4dd8a16dc159ed9cd82f49d1e66bc8a98a
30bde930a3290a6766551962302f4751bf985eb4
/Prac_Server/app/src/main/java/com/jmdroid/prac_server/network/resmodel/ResBasic.java
258c5b1b1351c560eaa0e8e8c1122b3e49d16416
[]
no_license
jimin530/Prac_Android
adb4a3e4ba24982c171b48c2c65301f0db5cb873
61e2d8b3220dd8906e25c483926e3f853e4dc803
refs/heads/master
2021-03-24T13:43:34.445431
2017-09-21T11:47:05
2017-09-21T11:47:05
86,223,790
0
0
null
null
null
null
UTF-8
Java
false
false
579
java
package com.jmdroid.prac_server.network.resmodel; /** * Created by jimin on 2017-02-24. */ public class ResBasic { String msg; String code; //ResError error; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } /* public ResError getError() { return error; } public void setError(ResError error) { this.error = error; }*/ }
be0611f7717809dac77f9dcef5f9f89b502a0046
914870faeaf77a610c37979ca61b137b1e89eade
/server/src/route/game/CommandsRoute.java
ba52a81444d5854b5fcc89cca0ccea613c8ebf3b
[]
no_license
film42/cs340-catan
29dc98023d8ff21eda11991ac341bd8513f1a8ae
bb86f4162881cb26450176c73de1075bae0a6610
refs/heads/master
2016-09-11T02:33:12.083821
2014-04-14T20:16:51
2014-04-14T20:16:51
16,019,243
0
0
null
null
null
null
UTF-8
Java
false
false
1,385
java
package route.game; import model.facade.GameFacade; import model.facade.MoveFacade; import route.CoreRoute; import spark.Request; import spark.Response; import spark.Route; /** * Created by Jon George on 3/6/14. */ public class CommandsRoute extends CoreRoute { private MoveFacade m_moveFacade; public CommandsRoute(MoveFacade moveFacade) { m_moveFacade = moveFacade; } @Override public void attach() { get(new Route("/game/commands") { @Override public Object handle(Request request, Response response) { int gameId = Integer.parseInt(request.cookie("catan.game")); String modelResponse = m_moveFacade.onGetCommands(gameId); return modelResponse; } }); post(new Route("/game/commands") { @Override public Object handle(Request request, Response response) { String json = request.body(); int gameId = Integer.parseInt(request.cookie("catan.game")); boolean modelResponse = m_moveFacade.onPostCommands(json, gameId); if(modelResponse){ return ""; }else{ response.status(401); return ""; } } }); } }
81e96bc375f4f4568e11902ec5ba7675da4fc1e0
7738a40c403f0e8342aa36475a6f152cf8a172aa
/app/src/main/java/com/abhidev/models/ShortTermCourse.java
5a00fa6bc8a2ba2c44348920855bf3da441e329c
[]
no_license
rishabhjainj/AbhiDev
33343755f5775ac71d6d202a5c77920dafe0c1ae
beb29c30b0889fb5053456a4c0923059e0fb6ab2
refs/heads/master
2022-02-26T09:29:34.390585
2019-09-17T08:26:27
2019-09-17T08:26:27
208,992,239
0
0
null
null
null
null
UTF-8
Java
false
false
2,202
java
package com.abhidev.models; public class ShortTermCourse { private Integer id; private Integer numLikes; private String name; private String image; private Boolean userLiked; private String offerredBy; private String url; private String description; private String contact; private Integer rating; private Integer duration; private Integer boostPercent; public Boolean getUserLiked() { return userLiked; } public void setUserLiked(Boolean userLiked) { this.userLiked = userLiked; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getNumLikes() { return numLikes; } public void setNumLikes(Integer numLikes) { this.numLikes = numLikes; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getOfferredBy() { return offerredBy; } public void setOfferredBy(String offerredBy) { this.offerredBy = offerredBy; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public Integer getRating() { return rating; } public void setRating(Integer rating) { this.rating = rating; } public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } public Integer getBoostPercent() { return boostPercent; } public void setBoostPercent(Integer boostPercent) { this.boostPercent = boostPercent; } }
4dfe5c2d06ddc13675aecff5aa4b54373a7f616f
46a19ecc9f63b0099d08cf292cb71726ba690a1e
/jiggle/SteepestDescent.java
02d8862f68da4726460d9c0e701ea80bf907e43a
[]
no_license
antfarmar/jiggle
6672bf9ba2b8e4a36e6eb85c04294c3badb8d6a0
6dfe8c94b2a274f3499e49fe5d23519b5e8fd43f
refs/heads/master
2021-05-27T21:10:21.242034
2014-02-09T01:18:16
2014-02-09T01:18:16
105,219,323
2
0
null
2017-09-29T02:11:37
2017-09-29T02:11:37
null
UTF-8
Java
false
false
604
java
package jiggle; /* Class for method of steepest descent. */ public class SteepestDescent extends FirstOrderOptimizationProcedure{ public SteepestDescent (Graph g, ForceModel fm, double accuracy) { super (g, fm, accuracy); } protected void computeDescentDirection () { int n = graph.numberOfVertices, d = graph.getDimensions (); if ((descentDirection == null) || (descentDirection.length != n)) descentDirection = new double [n] [d]; for (int i = 0; i < n; i++) { for (int j = 0; j < d; j++) { descentDirection [i] [j] = negativeGradient [i] [j]; } } } }
c6ec39fe83b87bb948ee432a08505dcb0e29666a
bd1a504efbaf0c6b85e5fc6a74b666ecf32294cf
/src/main/java/com/jackeroo/oauth/common/utils/RandImageUtil.java
d9a9b161e7f3ad072a2179f448d5c47c244f532e
[]
no_license
zhourenfei17/spring-boot-security-oauth
65919cf184260df3a7009209089b9ace81335654
a004b698b845eb0797e310dcc2f3cf5acd6a3fee
refs/heads/master
2022-12-03T22:43:48.741888
2020-08-22T07:57:58
2020-08-22T07:57:58
288,407,645
3
4
null
null
null
null
UTF-8
Java
false
false
4,568
java
package com.jackeroo.oauth.common.utils; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; import java.util.Random; /** * 登录验证码工具类 */ public class RandImageUtil { /** * 定义图形大小 */ private static final int width = 105; /** * 定义图形大小 */ private static final int height = 35; /** * 定义干扰线数量 */ private static final int count = 200; /** * 干扰线的长度=1.414*lineWidth */ private static final int lineWidth = 2; /** * 图片格式 */ private static final String IMG_FORMAT = "JPEG"; /** * base64 图片前缀 */ private static final String BASE64_PRE = "data:image/jpg;base64,"; /** * 直接通过response 返回图片 * @param response * @param resultCode * @throws IOException */ public static void generate(HttpServletResponse response, String resultCode) throws IOException { BufferedImage image = getImageBuffer(resultCode); // 输出图象到页面 ImageIO.write(image, IMG_FORMAT, response.getOutputStream()); } /** * 生成base64字符串 * @param resultCode * @return * @throws IOException */ public static String generate(String resultCode) throws IOException { BufferedImage image = getImageBuffer(resultCode); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); //写入流中 ImageIO.write(image, IMG_FORMAT, byteStream); //转换成字节 byte[] bytes = byteStream.toByteArray(); //转换成base64串 String base64 = Base64.getEncoder().encodeToString(bytes).trim(); base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n //写到指定位置 //ImageIO.write(bufferedImage, "png", new File("")); return BASE64_PRE+base64; } private static BufferedImage getImageBuffer(String resultCode){ // 在内存中创建图象 final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 final Graphics2D graphics = (Graphics2D) image.getGraphics(); // 设定背景颜色 graphics.setColor(Color.WHITE); // ---1 graphics.fillRect(0, 0, width, height); // 设定边框颜色 // graphics.setColor(getRandColor(100, 200)); // ---2 graphics.drawRect(0, 0, width - 1, height - 1); final Random random = new Random(); // 随机产生干扰线,使图象中的认证码不易被其它程序探测到 for (int i = 0; i < count; i++) { graphics.setColor(getRandColor(150, 200)); // ---3 final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内 final int y = random.nextInt(height - lineWidth - 1) + 1; final int xl = random.nextInt(lineWidth); final int yl = random.nextInt(lineWidth); graphics.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码 for (int i = 0; i < resultCode.length(); i++) { // 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 // graphics.setColor(new Color(20 + random.nextInt(130), 20 + random // .nextInt(130), 20 + random.nextInt(130))); // 设置字体颜色 graphics.setColor(Color.BLACK); // 设置字体样式 // graphics.setFont(new Font("Arial Black", Font.ITALIC, 18)); graphics.setFont(new Font("Times New Roman", Font.BOLD, 24)); // 设置字符,字符间距,上边距 graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26); } // 图象生效 graphics.dispose(); return image; } private static Color getRandColor(int fc, int bc) { // 取得给定范围随机颜色 final Random random = new Random(); if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } final int r = fc + random.nextInt(bc - fc); final int g = fc + random.nextInt(bc - fc); final int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
e3463d0148fb45b055eb99b1dc44c1e0ec60aba1
6d08e7dbabff98687f1007a4fcc3f8f155eb5ba1
/src/actions/PublicAction.java
554ca58f05212384fa9618b4ba27f5748f68c8bf
[]
no_license
Code-God/zysq
df1f7ff554b8648773603ec2548749d03e77284c
c7a6f08f889ae369cbb73ceca0d55c91e2a639a6
refs/heads/master
2020-03-21T12:34:34.764431
2018-06-25T07:43:13
2018-06-25T07:43:13
138,560,140
1
0
null
null
null
null
UTF-8
Java
false
false
90,756
java
package actions; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import model.GameReport; import model.Paging; import model.bo.AboutUs; import model.bo.Columns; import model.bo.Contacts; import model.bo.Experts; import model.bo.Gift; import model.bo.OnlineTests; import model.bo.PublishedStudy; import model.bo.PublishedTesting; import model.bo.Question; import model.bo.ShowCase; import model.bo.TP; import model.bo.Topics; import model.bo.Training; import model.bo.Vote; import model.bo.auth.Org; import model.bo.fenxiao.OneProduct; import model.bo.food.ShoppingCart; import model.bo.food.Spreader; import model.bo.wxmall.Pj; import model.vo.WxUser; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import org.apache.commons.lang.StringUtils; import org.apache.cxf.common.util.Base64Exception; import org.apache.cxf.common.util.Base64Utility; import org.apache.log4j.Logger; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import service.intf.AdminService; import service.intf.ICarInfoService; import service.intf.PublicService; import util.SysUtil; import actions.integ.weixin.WeiXinUtil; import com.base.ServerBeanFactory; import com.base.action.DispatchPagerAction; import com.base.log.LogUtil; import com.base.tools.Version; import com.constants.CupidStrutsConstants; import com.wfsc.common.bo.ad.AdvConfig; import com.wfsc.common.bo.order.Orders; import com.wfsc.common.bo.product.ProductCat; import com.wfsc.common.bo.product.Products; import com.wfsc.common.bo.user.Admin; import com.wfsc.common.bo.user.User; import com.wfsc.services.ad.IAdService; import com.wfsc.services.product.IHotelService; import com.wfsc.services.product.IProductsService; import com.wfsc.services.productcat.IProductCatService; import com.wfsc.util.DateUtil; import constants.MarkConstants; @Controller("PublicxAction") @Scope("prototype") public class PublicAction extends DispatchPagerAction { private static final long serialVersionUID = -3503415849917552421L; private Logger logger = LogUtil.getLogger(LogUtil.SERVER); /** * 用户登录 用户点击菜单后,会 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String login() throws Exception { // 身份证 String idcard = request.getParameter("idcard"); // 用户名 String username = request.getParameter("username"); // String city = request.getParameter("city"); // String hospital = request.getParameter("hospital"); String openId = request.getParameter("openId"); //验证码 String codeImage = request.getParameter("codeImage"); // String openId = // "1234";//==============================================>>测试代码 // String telephone = request.getParameter("telephone"); logger.info("in LOGIN -------- codeImage=" + codeImage + " | username=" + username + "|" + openId); if(codeImage.equalsIgnoreCase(request.getSession().getAttribute(CupidStrutsConstants.CODE_IMAGE_LOGIN).toString())){ request.setAttribute("info", "对不起,验证码不正确!"); return new String("/weixin/login.jsp"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); Map<String, String> param = new HashMap<String, String>(); param.put("username", username); param.put("idcard", idcard); param.put("openId", openId); // 判断openId if (openId == null || "null".equals(openId) || StringUtils.isEmpty(openId)) { request.setAttribute("info", "对不起,非法登录!"); return new String("/weixin/login.jsp"); } // if (!SysUtil.IsIDcard(idcard)) { // request.setAttribute("info", "对不起,请输入正确的身份证号码!"); // return new String("/weixin/login.jsp"); // } try { User u = service.login(param); if (u != null) { request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); logger.info("普通用户登录成功..."); } else { request.setAttribute("info", "对不起,您的登录信息不正确!"); return new String("/weixin/login.jsp"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("info", "对不起,登录失败,请重试!"); return new String("/weixin/login.jsp"); } // 分辨PC还是手机 String userAgent = request.getHeader("User-Agent"); logger.info("客户端类型:" + userAgent); // if (!WeiXinUtil.isFromMobile(userAgent)) {//非移动端 // return new String("/pc/index.jsp"); // }else{ // return new String("/main/index.jsp?login=y&openId=" + openId, true); // } // 登录后跳转到邮政咨询页面 // 加载邮政咨询的栏目 return yzindex(); } /** * 微商城用户登录 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String doLogin() throws Exception { String username = request.getParameter("username"); String pwd = request.getParameter("passwd"); logger.info(username + "===用户登录............"); String userAgent = request.getHeader("User-Agent"); logger.info("客户端类型:" + userAgent); if ("0".equals(Version.getInstance().getNewProperty("wxtest"))) { if (!WeiXinUtil.isFromMobile(userAgent)) {// 非移动端 request.setAttribute("info", "请从微信登录!"); return ("info"); } } AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); User u = service.getUserByNameAndPwd(username, pwd); if (u != null) { session.put(CupidStrutsConstants.SESSION_USER, u); PublicService pservice = (PublicService) ServerBeanFactory.getBean("publicService"); List<ShoppingCart> list = pservice.getShoppingCartPrdList(this.getCurrentUser().getId()); // 购物车里的数量 request.getSession().setAttribute(MarkConstants.CART_COUNT, list.size()); //更新登录时间 u.setLastLogin(new Date()); service.updateUser(u); } else { request.setAttribute("info", "对不起,用户名或密码错误!"); return ("info"); } return "index"; } /** * 微店网关。。。。。。。。。。。。。 通过自定义菜单,给定一个入口, 这个入口经过此Action, 因为openId会带过来,所以知道是否已经绑定过 * <li>如果绑定过,则直接自动登录 * <li>如果未绑定,后续一些操作将会提示绑定。 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String storeGateway() throws Exception { String openId = request.getParameter("openId"); logger.info(openId + "===商城首页............"); if (openId == null) { request.setAttribute("info", "对不起,非法入口,请从微信公众号访问!"); return ("info"); } // 查询是否绑定 AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); User u = service.getUserByOpenId(openId); if (u != null) { request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); } // 微商城首页 return new String("/jms/index.jsp"); } /** * 商品入口 通过自定义菜单,给定一个入口, 这个入口经过此Action, 因为openId会带过来,所以知道是否已经绑定过 * <li>如果绑定过,则直接自动登录 * <li>如果未绑定,后续一些操作将会提示绑定。 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String productGateway() throws Exception { try{ AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // if(!Version.getInstance().getNewProperty("wxtest").equals("y")){ // if(request.getSession().getAttribute(CupidStrutsConstants.WXOPENID) == null){ // request.setAttribute("info", "对不起,非法入口,请从微信公众号访问!"); // return ("info"); // } // } //转发的情况, 有org带过来, 需要重新设置一下session里的CupidStrutsConstants.FXCODE if(request.getParameter("orgId") != null){ Org orgById = service.getOrgById(Long.valueOf(request.getParameter("orgId"))); request.getSession().setAttribute(CupidStrutsConstants.FXCODE, orgById.getCode()); } String openId = ""; //测试代码 if(Version.getInstance().getNewProperty("wxtest").equals("y")){ openId = "1111"; }else{ if (this.getCurrentUser() == null) { openId = request.getSession().getAttribute(CupidStrutsConstants.WXOPENID).toString(); } else { openId = this.getCurrentUser().getOpenId(); } } // 商品分类 String productCat = request.getParameter("productCat"); // 产品ID String prdId = request.getParameter("prdId"); String prdCode = request.getParameter("prdCode"); logger.info(openId + "===商品分类..........." + productCat + "...prdId=" + prdId + " prdCode=" + prdCode); if (openId == null) { request.setAttribute("info", "对不起,非法入口,请从微信公众号访问!"); return ("info"); } else { request.setAttribute("openId", openId); } User u = service.getUserByOpenId(openId); if (u != null) { request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); request.setAttribute("nobind", "0"); } else { // 不是会员,第三方点击链接 request.setAttribute("nobind", "1"); } Products p = null; if (productCat == null) { if(prdId != null && !"undefined".equals(prdId) && !"null".equalsIgnoreCase(prdId)){ p = service.getProductById(Long.valueOf(prdId)); }else{ p = service.getProductByCode(prdCode); } } else { // 显示商品信息 p = service.getProductByGuige(productCat); } if (p == null) { request.setAttribute("info", "对不起,该产品不存在!"); return ("info"); } request.setAttribute("product", p); // 加载展示图片 List<String> pics = new ArrayList<String>(); String filePath = getProductPicPath(request, "/Prd" + p.getId() + "/"); File f = new File(filePath); if (f.exists()) { File[] listFiles = f.listFiles(); for (File file : listFiles) { if (file.getName().indexOf("-thumb") == -1) { pics.add("/private/UploadImages/Prd" + p.getId() + "/" + file.getName()); } } } request.setAttribute("picList", pics); // 判断是不是分销客 TODO String agent = request.getParameter("agent"); if(agent != null){//是分销客转发的链接 } //加载优惠券所属门店信息 Admin adminById = service.getAdminById(p.getServiceId().toString()); if(adminById != null){ request.setAttribute("storeAddress", adminById.getCompany()); request.setAttribute("phone", adminById.getPhone()); } // 产品详情页 // return "wxProductDetail"; //车险平台 return "wxCarProductDetail"; }catch(Exception e){ e.printStackTrace(); return null; } } /** * 登录后首页:邮政咨询 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String yzindex() throws Exception { String t = request.getParameter("t"); if (t == null) { t = "1"; } // 登录后跳转到邮政咨询页面 // 加载邮政咨询的栏目 AdminService as = (AdminService) ServerBeanFactory.getBean("adminService"); List<Columns> cols = as.getAllColumns(t); request.setAttribute("cols", cols); // 统计信息 as.updateStatistics("yzindex"); return new String("/wx/yzinfo.jsp"); } /** * 查看邮政咨询详情 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String viewInfoDetail() throws Exception { String id = request.getParameter("id"); if (id == null) { request.setAttribute("info", "对不起,参数不正确!"); return ("error"); } AdminService as = (AdminService) ServerBeanFactory.getBean("adminService"); ShowCase sc = as.getYzInfoDetail(Long.valueOf(id)); request.setAttribute("sc", sc); return new String("/wx/yzinfoDetail.jsp"); } /** * 点赞 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String zan() throws Exception { try { // 文章ID String targetId = request.getParameter("caseId"); PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); boolean b = service.zan(request.getSession().getId(), this.getCurrentUser(), targetId); if (b) { response.getWriter().write("1"); } else { // 不能连续点赞 response.getWriter().write("-1"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("fail"); } return null; } /** * 签到 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String sign() throws Exception { if (request.getSession().getAttribute(CupidStrutsConstants.SESSION_USER) == null) { // 未登录 request.setAttribute("info", "对不起,请登录后再操作!"); return ("login"); } try { PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); int s = service.sign(this.getCurrentUser()); response.getWriter().write(s + ""); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("fail"); } return null; } /** * 微信端统一入口方法 /wx/xxx.jsp * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String gotoPage() throws Exception { logger.info("in gotoPage.........................." + DateUtil.getLongCurrentDate()); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); if (request.getSession().getAttribute(CupidStrutsConstants.SESSION_USER) == null) { // 判断是否是绑定用户 String openId = request.getParameter("openId"); logger.info("openId==" + openId); request.getSession().setAttribute(MarkConstants.SES_OPENID, openId); User userByOpenId = service.getUserByOpenId(openId); logger.info("userByOpenId==" + userByOpenId); if (userByOpenId != null) {// 已经登录过 request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, userByOpenId); } else { // 把openId传递到登录页面,非常重要 request.setAttribute("openId", openId); // 未绑定过 request.setAttribute("info", "对不起,请登录后再操作!"); return ("login"); } } try { String page = request.getParameter("page"); logger.info("page====" + page); // 特殊页面处理,bizStudy if (page.startsWith("bizStudy")) { // http://60.12.228.130/yzwx/public.do?method=gotoPage&page=bizStudy.jsp#2&openId=oX4mujnnQcPASy5TrT String destPage = "/wx/" + StringUtils.split(page, "-")[0] + "?t=" + StringUtils.split(page, "-")[1]; logger.info("destPage====" + destPage); // 统计信息 service.updateStatistics(destPage); return new String(destPage); } else { if (!page.endsWith(".jsp") && !page.endsWith(".htm") && !page.endsWith(".html")) { request.setAttribute("info", "对不起,您请求的页面不存在!"); return ("info"); } // 统计信息 service.updateStatistics(page); response.sendRedirect(request.getContextPath() + "/weixin/" + page); return null; } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 开始答题:在线测试 从在线测试引导页上点击:【开始答题】后进入此方法。<br> * 针对该试卷需要生成唯一序列号。 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String startTest() throws Exception { try { UUID uuid = UUID.randomUUID(); String snum = uuid.toString(); request.setAttribute("snum", snum); String testId = request.getParameter("testId"); if (testId != null) { // 查出所有的在线考试题 AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<PublishedTesting> publishedTesting = service.getOnlineTests(Long.valueOf(testId)); request.setAttribute("list", publishedTesting); return new String("/wx/onlineTest.jsp?testId=" + testId); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 在线辅导开始 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String startDemoStudy() throws Exception { try { UUID uuid = UUID.randomUUID(); String snum = uuid.toString(); request.setAttribute("snum", snum); // 查出所有的在线辅导题 AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<PublishedStudy> publishedStudy = service.getPublishedStudy(); request.setAttribute("list", publishedStudy); return new String("/wx/onlineStudy.jsp"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 开始调查 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String startVote() throws Exception { try { // 查出所有的在线考调查 AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // 获取调查问卷 Vote v = service.getActiveVote(); request.setAttribute("v", v); return new String("/wx/onlineVote.jsp"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 提交测试结果 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String submitTest() throws Exception { try { Object snum = request.getAttribute("snum"); return new String("/wx/onlineTest.jsp"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 抢沙发 抢沙发:中午十二点到十二点零五分,期间前五名为抢沙发有效 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String sofa() throws Exception { if (request.getSession().getAttribute(CupidStrutsConstants.SESSION_USER) == null) { // 未登录 request.setAttribute("info", "对不起,请登录后再操作!"); return ("login"); } try { PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); // 抢沙发,返回1即为第一名,成功,否则返回当前名次 int rank = service.sofa(this.getCurrentUser()); response.getWriter().write(rank + ""); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("fail"); } return null; } /** * 英雄榜, AJAX * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String heroList() throws Exception { try { PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); List<User> list = service.getHeroList(); JSONArray fromObject = JSONArray.fromObject(list); String string = fromObject.toString(); response.getWriter().write(string); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("fail"); } return null; } /** * 根据OPENID加载用户信息 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String loadUserInfo() throws Exception { try { String openId = request.getParameter("openId"); PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); User u = service.getUserByOpenId(openId); if (u != null) { logger.info("111-- " + openId + " u.getUsername()=" + u.getUsername() + " u.getTelephone()= " + u.getTelephone()); // 如果已经存在,并且手机号码和用户名已经填写,则直接进入 if (u.getUsername() != null && u.getTelephone() != null) { logger.info("直接登录..."); // 更新最后登录时间 u.setLastLogin(new Date()); service.updateUser(u); request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); logger.info("普通用户【" + u.getUsername() + "】直接登录成功..."); JSONObject json = new JSONObject(); json.put("result", "pass"); json.put("openId", openId); response.getWriter().write(json.toString()); return null; } else { JSONObject json = new JSONObject(); json.put("result", "fail"); json.put("openId", openId); response.getWriter().write(json.toString()); } } else { JSONObject json = new JSONObject(); json.put("result", "fail"); json.put("openId", openId); response.getWriter().write(json.toString()); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); return null; } return null; } /** * getResumeList * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getShowCase() throws Exception { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "1" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 Map<String, String> paramMap = getParamMap(request); try { Map<String, Object> map = service.getShowCases(start, Integer.valueOf(limit).intValue(), paramMap); List<ShowCase> resumeList = (List<ShowCase>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!resumeList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(resumeList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("fail"); } return null; } /** * 用户注册\绑定 当未注册用户访问个人中心时,需要跳转到此页面。 输入信息有: 昵称, 电话, 邮箱 * * 点击个人中心任何菜单,均推送一个url地址,该地址带上openId号。只有注册后的用户才能继续访问,否则将进入提示注册页面。 */ public String doRegBind() throws Exception { try { // 提问 String openId = request.getParameter("openId"); String nickName = request.getParameter("nickName"); String telephone = request.getParameter("telephone"); String email = request.getParameter("email"); PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("openId", openId); paramMap.put("nickName", nickName); paramMap.put("telephone", telephone); paramMap.put("email", email); service.doRegisterBind(paramMap); response.getWriter().write("ok"); } catch (RuntimeException e) { e.printStackTrace(); response.getWriter().write("fail"); } return null; } /** * 显示专家 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getExperts() throws Exception { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); try { Map<String, Object> map = service.getExperts(start, Integer.valueOf(limit).intValue()); List<ShowCase> resumeList = (List<ShowCase>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!resumeList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(resumeList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("fail"); } return null; } /** * 查看文章详情 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String viewCase() throws Exception { try { String caseId = request.getParameter("id"); if (caseId == null) { request.setAttribute("info", "对不起,参数不正确!"); return ("error"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); ShowCase sc = service.getShowCase(caseId); if (sc != null) { request.setAttribute("sc", sc); } request.setAttribute("sc", sc); return new String("/wx/yzinfoDetail.jsp"); } catch (Exception e) { e.printStackTrace(); request.setAttribute("info", "对不起,出错了!"); return ("error"); } // //分辨PC还是手机 // String userAgent = request.getHeader("User-Agent"); // logger.info("客户端类型:" + userAgent); // if (!WeiXinUtil.isFromMobile(userAgent)) {//非移动端 // return ("articlePc"); // }else{ // return ("article"); // } } /** * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String viewExpert() throws Exception { try { String id = request.getParameter("id"); if (id == null) { request.setAttribute("info", "对不起,参数不正确!"); return ("error"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); Experts expert = service.getExpert(id); if (expert != null) { request.setAttribute("expert", expert); } String pc = request.getParameter("pc"); if ("y".equals(pc)) { return ("expertPc"); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("info", "对不起,出错了!"); return ("error"); } return ("expert"); } /** * 获得当月话题列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getTopics() throws IOException { String year = request.getParameter("dateym"); if (year == null) { year = DateUtil.getShortCurrentDate().substring(0, 4); } AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<Topics> questionsByDate = service.topics(Integer.valueOf(year)); PrintWriter out = response.getWriter(); if (!questionsByDate.isEmpty()) { out.write(JSONArray.fromObject(questionsByDate).toString()); } else { out.write("{\"result\":\"empty\"}"); } return null; } /** * 获得礼品列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getGifts() throws IOException { response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<Gift> gifts = service.getGifts(); PrintWriter out = response.getWriter(); if (!gifts.isEmpty()) { out.write(JSONArray.fromObject(gifts).toString()); } else { out.write("{\"result\":\"empty\"}"); } return null; } /** * 加载积分商品详情 * @return * @throws IOException */ public String loadGiftDetail() throws IOException { response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Long giftId = Long.valueOf(request.getParameter("giftId")); Gift gift = service.getGiftById(giftId); PrintWriter out = response.getWriter(); if (gift != null) { JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("gift", gift); out.write(JSONObject.fromObject(jo).toString()); } else { out.write("{\"msg\":\"empty\"}"); } return null; } /** * 获取本人预订的记录 * @return * @throws IOException */ public String getMyBookedRecord() throws IOException { response.setCharacterEncoding("UTF-8"); IHotelService service = (IHotelService) ServerBeanFactory.getBean("hotelService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("prdId", request.getParameter("prdId")); try { Paging pp = service.getMyBookedRecords(Integer.valueOf(page), Integer.valueOf(limit).intValue(), paramMap); if (!pp.getDatas().isEmpty()) { out.print(JSONObject.fromObject(pp).toString()); } else { out.print("{\"result\":\"null\"}"); } } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 邮政咨询:子栏目的条目加载 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getYzinfoList() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 Map<String, String> paramMap = getParamMap(request); try { Map<String, Object> map = service.getShowCases(start, Integer.valueOf(limit).intValue(), paramMap); List<ShowCase> resumeList = (List<ShowCase>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!resumeList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(resumeList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 培训信息列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getTrainingList() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 Map<String, String> paramMap = getParamMap(request); try { Map<String, Object> map = service.getTrainingList(start, Integer.valueOf(limit).intValue()); List<Training> resumeList = (List<Training>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!resumeList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(resumeList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 获得当前用户剩余积分 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getScore() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); int s = service.getScoreById(this.getCurrentUser().getId()); PrintWriter out = response.getWriter(); out.write(s + ""); return null; } // 在线考试试题总数 public String getOnlineTestCount() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String id = request.getParameter("id");// 考卷的ID logger.info("考卷ID---" + id); if (id != null) { int s = service.getTestCount(Long.valueOf(id)); OnlineTests onlineTest = service.getOnlineTest(Long.valueOf(id)); PrintWriter out = response.getWriter(); JSONObject jo = new JSONObject(); jo.put("count", s); jo.put("testTitle", onlineTest.getTestTitle()); jo.put("testDesc", onlineTest.getTestDesc()); out.write(jo.toString()); } return null; } // 在线辅导题目总数 public String getOnlineStudyCount() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); int s = service.getOnlineStudyCount(); PrintWriter out = response.getWriter(); out.write(s + ""); return null; } // 在线调查总数 public String getOnlineVoteCount() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); int s = service.getVoteCount(); Vote vote = service.getActiveVote(); PrintWriter out = response.getWriter(); JSONObject jo = new JSONObject(); jo.put("vtitle", vote.getVtitle()); jo.put("count", s); jo.put("vdesc", vote.getVdesc()); out.write(jo.toString()); return null; } /** * 检测该openId是否已经绑定过 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String checkBind() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String openId = request.getParameter("openId"); User u = service.getUserByOpenId(openId); PrintWriter out = response.getWriter(); if (u != null) { request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); out.write("ok"); } else { out.write("fail"); } return null; } /** * 兑换 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String duihuan() throws IOException { PrintWriter out = response.getWriter(); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String gifId = request.getParameter("giftId"); if (gifId == null) { out.write("ok"); return null; } boolean b = service.duihuan(this.getCurrentUser().getId(), Long.valueOf(gifId)); if (b) { out.write("ok"); } else { out.write("fail"); } return null; } /** * 兑换 产品,把商品作为奖品,和之前做好的功能不同,之前是独立的兑换奖品 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String duihuanPrd() throws IOException { PrintWriter out = response.getWriter(); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String prdId = request.getParameter("prdId"); if (prdId == null) { out.write("fail"); return null; } boolean b = service.duihuanPrd(this.getCurrentUser().getId(), Long.valueOf(prdId)); if (b) { out.write("ok"); } else { out.write("fail"); } return null; } /** * 获得当月话题的问题列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getQuestions() throws IOException { String date = request.getParameter("date"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<Question> questionsByDate = service.getQuestionsByDate(date); request.setAttribute("list", questionsByDate); return ("questionList"); } /** * 提交答案 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String submitAnswer() throws IOException { try { String[] parameterValues = request.getParameterValues("answer"); // 序列号 String snum = request.getParameter("snum"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); int score = service.saveAnswer(this.getCurrentUser(), parameterValues, snum); // 分辨PC还是手机 // String userAgent = request.getHeader("User-Agent"); // logger.info("客户端类型:" + userAgent); // if (!WeiXinUtil.isFromMobile(userAgent)) {//非移动端 // return new String("/pc/msg.jsp?m=5&msg=1"); // }else{ request.setAttribute("score", score); // 考卷ID request.setAttribute("id", request.getParameter("testId")); request.setAttribute("msg", WeiXinUtil.getTestMsg(score)); // 跳转到考试结果 return ("testResult"); // } } catch (Exception e) { e.printStackTrace(); return ("error"); } } /** * 在线辅导--提交答案 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String submitDemoTest() throws IOException { try { String[] parameterValues = request.getParameterValues("answer"); // 序列号 String snum = request.getParameter("snum"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); int score = service.saveDemoTestResult(this.getCurrentUser(), parameterValues, snum); // 分辨PC还是手机 // String userAgent = request.getHeader("User-Agent"); // logger.info("客户端类型:" + userAgent); // if (!WeiXinUtil.isFromMobile(userAgent)) {//非移动端 // return new String("/pc/msg.jsp?m=5&msg=1"); // }else{ request.setAttribute("score", score); request.setAttribute("msg", WeiXinUtil.getTestMsg(score)); // 另外,需要把题目所有正确答案输出 // 查出所有的在线辅导题 List<PublishedStudy> list = service.getPublishedStudy(); request.setAttribute("list", list); // 跳转到考试结果 return ("studyResult"); // } } catch (Exception e) { e.printStackTrace(); return ("error"); } } /** * 提交调查 * * 提交的关键域 <input type="hidden" value="17|A" id="v_17" name="answer"> * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String submitVote() throws IOException { try { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // 每个数组表示: VoteItem.id|用户选择的答案 String[] parameterValues = request.getParameterValues("answer"); String empType = request.getParameter("empType"); String jobType = request.getParameter("jobType"); String voteId = request.getParameter("voteId"); // 检查是否已经答过了 if (service.checkVoter(voteId)) { request.setAttribute("info", "对不起,该调查您已经参与过了,不能重复提交。"); return ("voteResult"); } int score = service.saveVote(this.getCurrentUser(), parameterValues, empType, jobType, voteId); // 跳转到考试结果 return ("voteResult"); // } } catch (Exception e) { e.printStackTrace(); return ("error"); } } // 投票者session缓存,防止重复投票 private List<String> tpUser = new ArrayList<String>(); /** * 提交投票 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String submitTP() throws IOException { try { if (tpUser.contains(request.getSession().getId())) { request.setAttribute("info", "对不起,您已经投过票了!"); return ("tpresult"); } AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String slimit = request.getParameter("slimit"); // 用户选择的选项ID String optId = request.getParameter("opts"); String[] opts = request.getParameterValues("opts"); if ("1".equals(slimit)) { service.updateTPCount(optId); } else { // 多选的情况 service.updateTPCount(opts); } tpUser.add(request.getSession().getId()); return ("tpresult"); } catch (Exception e) { e.printStackTrace(); return ("error"); } } /** * 在线考试 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getPublishedTesting() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); try { List<PublishedTesting> list = service.getPublishedTesting(); out.print(JSONArray.fromObject(list).toString()); } catch (Exception e) { e.printStackTrace(); out.write("{\"result\":\"fail\"}"); } return null; } /** * 获得报告 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getReport() throws Exception { logger.info("统计数据查询..."); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // 话题ID String topicId = request.getParameter("topicId"); List<GameReport> list = service.getReportList(Long.valueOf(topicId)); JSONArray fromObject = JSONArray.fromObject(list); logger.info("fromObject.toString()=" + fromObject.toString()); response.getWriter().write(fromObject.toString()); return null; } /** * 获得第一个案例 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getFirstCase() throws Exception { logger.info("统计数据查询..."); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // 0-病例分享 1-获奖病例 String type = request.getParameter("t"); ShowCase sc = service.getLastCase(type); JSONObject fromObject = JSONObject.fromObject(sc); logger.info("fromObject.toString()=" + fromObject.toString()); response.getWriter().write(fromObject.toString()); return null; } /** * 加载评价列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String loadPj() throws IOException { response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("prdId", request.getParameter("prdId")); try { Map<String, Object> map = service.loadPj(start, Integer.valueOf(limit).intValue(), paramMap); List<Pj> dataList = (List<Pj>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!dataList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(dataList); JsonConfig jc = new JsonConfig(); jc.setExcludes(new String[]{"pjer"}); out.print(JSONObject.fromObject(pp, jc).toString()); } else { out.print("{\"result\":\"null\"}"); } } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 获得第一个专家 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getFirstExpert() throws Exception { logger.info("统计数据查询..."); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Experts ex = service.getLastExpert(); JSONObject fromObject = JSONObject.fromObject(ex); logger.info("fromObject.toString()=" + fromObject.toString()); response.getWriter().write(fromObject.toString()); return null; } /** * 培训信息 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getTraining() throws Exception { logger.info("统计数据查询..."); try { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String id = request.getParameter("id"); Training t = service.getTraining(Long.valueOf(id)); JSONObject fromObject = JSONObject.fromObject(t); logger.info("fromObject.toString()=" + fromObject.toString()); response.getWriter().write(fromObject.toString()); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } public String getAboutUs() throws Exception { logger.info("统计数据查询..."); try { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); AboutUs t = service.getAboutus(); JSONObject fromObject = JSONObject.fromObject(t); logger.info("fromObject.toString()=" + fromObject.toString()); response.getWriter().write(fromObject.toString()); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } /** * 获得当前发布的投票 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String getTP() throws Exception { try { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); TP t = service.getTP(); if (t == null) {// 还没有任何投票 response.getWriter().write("{\"result\":\"nodata\"}"); } else { JsonConfig jc = new JsonConfig(); jc.setExcludes(new String[] { "items" }); JSONObject fromObject = JSONObject.fromObject(t, jc); response.getWriter().write(fromObject.toString()); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } /** * 用户提交反馈 * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String submitFeedBack() throws Exception { logger.info("提交反馈..."); try { PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); String sesid = request.getSession().getId(); logger.info("sesid==" + sesid); // 反馈 String name = request.getParameter("name"); String content = request.getParameter("content"); service.submitFeedback(name, content); request.setAttribute("info", Version.getInstance().getNewProperty("msg1")); } catch (Exception e) { e.printStackTrace(); request.setAttribute("info", "提交失败,请稍后重试!"); } return ("feedback"); } /** * 查询参数 * * @param request * @return */ private Map<String, String> getParamMap(HttpServletRequest request) { Map<String, String> paramMap = new HashMap<String, String>(); // **0-邮政资讯 1-业务学习 2-生活常识 */ String t = request.getParameter("t"); if (StringUtils.isNotBlank(t) && t != null && !"null".equals(t)) { paramMap.put("t", t); } // 所属子栏目 String cid = request.getParameter("cid"); if (StringUtils.isNotBlank(cid) && cid != null && !"null".equals(cid)) { paramMap.put("cid", cid); } // 文章类别: 0-邮政资讯 1-业务学习 2-生活常识 String docType = request.getParameter("docType"); if (StringUtils.isNotBlank(docType) && docType != null && !"null".equals(docType)) { paramMap.put("docType", docType); } // 业务学习模块,关键字 String keyword = request.getParameter("keyword"); if (StringUtils.isNotBlank(keyword) && keyword != null && !"null".equals(keyword)) { paramMap.put("keyword", keyword); } return paramMap; } /** * 进入商城首页 * 这里需要处理两种情况: * 1)如果是关注用户进入,只有一个参数: c, c的值是经过编码算法的分销商代码 * 2)如果是分销客转发的,这个URL除了c之外, 还要带上一个agent参数,这个agent就是转发者(分销客)的openId * 体现在state参数的不同,这种情况,state={分销商id},{分销客id} * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public String index() throws Exception { String referrerUserid=""; try { // 分销商编码, 从参数上传递过来的分销商编码是经过特定算法的: base64编码+随机10位字母; 有=号的,替换成英文逗号(,),然后再倒序 String reverseCode = request.getParameter("c"); logger.info("进入分销商城菜单...|" + reverseCode); String agentId = request.getParameter("agent"); if(agentId != null){ logger.info("通过分销客进入-------" + agentId); //把分销客的ID存到session里,后续支付订单时, 需要通过这个计算佣金到分销客 request.getSession().setAttribute("agentId", agentId); } if(Version.getInstance().getNewProperty("wxtest").equals("y")){ PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); User userByOpenId = service.getUserByOpenId("ohXRbxJRAvMg3avhgMgfatRrQRdU"); request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, userByOpenId); request.getSession().setAttribute(CupidStrutsConstants.WXOPENID, "ohXRbxJRAvMg3avhgMgfatRrQRdU"); } String fxCode = super.decodeFxCode(reverseCode); //得出分销商名称 AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); IAdService adService = (IAdService) ServerBeanFactory.getBean("adService"); Org orgBycode = service.getOrgBycode(fxCode); request.getSession().setAttribute(CupidStrutsConstants.FXCODE, fxCode); request.getSession().setAttribute(CupidStrutsConstants.FX_ID, orgBycode.getId().toString()); //分销商名称 request.getSession().setAttribute(CupidStrutsConstants.FXNAME, orgBycode.getOrgname()); request.getSession().setAttribute(CupidStrutsConstants.ORG, orgBycode); logger.info("企业组织编号ORGCODE==..." + fxCode); String userIdStr = request.getParameter("userIdStr"); //推荐人userid(通过扫描二维码进入) if(userIdStr!=null&&!userIdStr.equals("")){ referrerUserid = userIdStr.split("\\|")[0]; request.getSession().setAttribute(CupidStrutsConstants.REFERRER_USER_ID, referrerUserid); request.getSession().setAttribute("diseaseId", userIdStr.split("\\|")[1]); }else{ request.getSession().removeAttribute(CupidStrutsConstants.REFERRER_USER_ID); } User u = this.getCurrentUser(); if(u == null){ logger.info("in publicAction.index, User in session is null.."); Object openId = request.getSession().getAttribute(CupidStrutsConstants.WXOPENID); logger.info("openId = " + openId); if(openId != null){ u = service.getUserByOpenId(openId.toString()); if(u != null){ logger.info("refresh user in session...."); this.updateSessionUser(u); } } } //首页幻灯片的信息 List<AdvConfig> ppts = adService.getPptsByOrg(orgBycode.getId()); request.getSession().setAttribute("ppts", ppts); //加载首页logo request.getSession().setAttribute("WXMALL_BANNER", orgBycode.getWxMallIndexBanner()); request.getSession().setAttribute("WXMALL_LOGO", orgBycode.getWxMallLogo()); //根据当前总销商的商城设置,决定首页显示方式: 1) 列表, 2)缩略图方式, 3)单一商品爆款 // if(orgBycode.getIndexShow() == 0){//list列表 // return ("index"); // }else if(orgBycode.getIndexShow() == 1){ //2)缩略图方式 // return ("index-thumb"); // }else if(orgBycode.getIndexShow() == 2){ //单一商品爆款 // return ("index-one"); // } } catch (Exception e) { e.printStackTrace(); request.setAttribute("info", "进入首页失败,请稍后重试!"); } // return ("cp-index"); //找药神器的首页 if(referrerUserid==null||referrerUserid.equals("")){ return ("drug-index"); }else{ //通过推荐扫描进入项目详情页 return("drug-patientinfo"); } // return this.couponList(); } /** * 考卷列表 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getAllTestList() throws IOException { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); List<OnlineTests> tests = service.getAllTests(); PrintWriter out = response.getWriter(); if (!tests.isEmpty()) { out.write(JSONArray.fromObject(tests).toString()); } else { out.write("{\"result\":\"empty\"}"); } return null; } /** * 预定, 传递参数如下: * "count": count, "prdId": prdId, "tel":tel, "count":count, "bookdate":bookdate, "arriveTime":arriveTime * @return * @throws Exception */ public String bookroom() throws Exception{ String count = request.getParameter("count"); String prdId = request.getParameter("prdId"); String tel = request.getParameter("tel"); String username = request.getParameter("username"); //预定日期 String bookdate = request.getParameter("bookdate"); String orgId = this.getCurrentFenXiao().getId().toString(); //最晚到店时间 String arriveTime = request.getParameter("arriveTime"); //当前用户的openId String openId= ""; if("y".equals(Version.getInstance().getNewProperty("wxtest"))){ openId = "testOpenId1000001111111"; }else{ openId = request.getSession().getAttribute(CupidStrutsConstants.WXOPENID).toString(); } logger.info("预定房间:" + count + "|" + prdId + "|" + tel + "|" + bookdate + "|" + arriveTime + "| orgId=" + orgId + "| openId=" + openId); Map<String, String> param = new HashMap<String, String>(); param.put("count", count); param.put("prdId", prdId); param.put("orgId", orgId); param.put("openId", openId); param.put("username", username); param.put("tel", tel); param.put("bookdate", bookdate);//预定日期 param.put("arriveTime", arriveTime);//最晚到店时间, 24小时制 7表示7点, 11表示11点。 PrintWriter out = response.getWriter(); try{ IHotelService service = (IHotelService) ServerBeanFactory.getBean("hotelService"); int flag = service.bookRoom(param); if(flag == 1){ out.write("{\"msg\":\"ok\"}"); }else{ out.write("{\"msg\":\"fail\"}"); } }catch(Exception e){ e.printStackTrace(); out.write("{\"msg\":\"fail\"}"); } return null; } /** * 推广链接入口 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String spread() throws IOException { String vname = request.getParameter("vname"); String productCat = request.getParameter("productCat"); logger.info("推广链接入口;vname=" + vname); if (vname == null) { request.setAttribute("info", "对不起,参数错误!请重新打开推荐链接。"); return ("info"); } AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Spreader sp = service.getSpreadVip(vname); if (sp == null) { request.setAttribute("info", "对不起,推荐链接错误。"); return ("info"); } // 显示商品信息 Products p = service.getProductByGuige(productCat); request.setAttribute("product", p); request.setAttribute("vname", SysUtil.encodeBase64(vname));// 大V微信号 // 产品详情页 return new String("/jms/product.jsp"); } /** * 从推广链接直接购买 <br> * 先进入配送地址填写页面,然后 直接生成订单,并进入订单确认页面 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String directBuyOrder() throws IOException { String prdId = request.getParameter("prdId"); String count = request.getParameter("count"); try { // 转发者 String vname = request.getParameter("vname"); // 非关注用户的openId和nickname String openId = request.getParameter("openId"); String nickname = request.getParameter("nickname"); if (StringUtils.isEmpty(vname) || vname == null) { logger.info("非注册用户购买-------" + openId); } else { logger.info("推广链接,点击购买-------"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); // "count": count, // "prdId": prdId, // "userAddress": userAddress, // "postcode": postcode, // "accepter": accepter, // "telephone": telephone // 搜集地址数据 String accepter = request.getParameter("accepter"); String address = request.getParameter("address"); String telephone = request.getParameter("telephone"); String postcode = request.getParameter("postcode"); String invoiceTitle = request.getParameter("invoiceTitle"); String buyerMsg = request.getParameter("buyerMsg"); Map<String, String> param = new HashMap<String, String>(); // param.put("accepter", accepter); // param.put("address", address); // param.put("telephone", telephone); // param.put("postcode", postcode); param.put("invoiceTitle", invoiceTitle); param.put("buyerMsg", buyerMsg); param.put("destlocation", accepter + "|" + telephone + "|" + address + "|" + postcode); param.put("userId", null); param.put("prdId", prdId);// 产品ID param.put("count", count);// 数量 param.put("vname", SysUtil.decodeBase64(vname));// 关键参数。。。 param.put("openId", openId); param.put("nickname", nickname); // 直接生成免注册订单 Orders saveOrder = service.saveOrder(param); // 跳转到订单确认页 request.setAttribute("order", saveOrder); // 非关注用户的openId request.setAttribute("openId", openId); JSONObject jo = new JSONObject(); jo.put("result", "ok"); jo.put("orderId", saveOrder.getId().toString()); response.getWriter().write(JSONObject.fromObject(jo).toString()); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } /** * 查看订单详情 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String viewOrder() throws IOException { try { String orderId = request.getParameter("orderId"); String openId = request.getParameter("openId"); if (orderId == null) { request.setAttribute("info", "对不起,参数错误!"); return ("info"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); Orders order = service.getOrder(Long.valueOf(orderId)); request.setAttribute("order", order); request.setAttribute("openId", openId); logger.info("开放订单---" + openId); // 到订单确认页面 return ("confirmOrder"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 首页获取所有产品--佳美氏 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String getAllProductList() throws IOException { response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); Map<String, String> paramMap = new HashMap<String, String>(); if (request.getParameter("keyword") != null) { paramMap.put("keyword", request.getParameter("keyword")); } // ----积分兑换页面传递的参数,目的有2个,为了在列表上显示兑换按钮和兑换积分。--- if (request.getParameter("charge") != null) { paramMap.put("charge", request.getParameter("charge")); } // 当前的分类ID if (request.getParameter("pid") != null) { paramMap.put("pid", request.getParameter("pid")); } //当前分销商代码 paramMap.put("orgCode", this.getCurrentFxCode()); try { Map<String, Object> map = service.getAllProductList(start, Integer.valueOf(limit).intValue(), paramMap); List<Products> dataList = (List<Products>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!dataList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(dataList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 加载分类 * * @return * @throws IOException */ public String loadCat() throws IOException { response.setCharacterEncoding("UTF-8"); Object fxCode = request.getSession().getAttribute(CupidStrutsConstants.FXCODE); String pid = request.getParameter("pid"); if (fxCode == null || pid == null) { // 参数不正确 response.getWriter().write("{\"result\":\"param\"}"); return null; } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); // 查找子分类 List<ProductCat> subList = service.loadSubCategory(fxCode.toString(), pid); if (subList.isEmpty()) {// 没子分类,加载产品列表 // 加载产品 this.loadOrgProducts(pid); } else { JSONObject jo = new JSONObject(); jo.put("result", "1"); jo.put("list", subList); response.getWriter().write(JSONObject.fromObject(jo).toString()); } return null; } /** * 加载爆款商品图片列表,图片上附加URL * * @return * @throws IOException */ public String getOnePrdList() throws IOException { response.setCharacterEncoding("UTF-8"); Object obj = request.getSession().getAttribute(CupidStrutsConstants.ORG); if (obj == null) { // 参数不正确 response.getWriter().write("{\"result\":\"param\"}"); return null; } try{ PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); OneProduct one = service.getOneProductInfo(((Org)obj).getId()); IProductsService prdService = (IProductsService) ServerBeanFactory.getBean("productsService"); JSONObject jo = new JSONObject(); jo.put("result", "ok"); // Products prd = prdService.getPrductByCode(one.getPrdCode()); // if(prd != null){ // jo.put("prdId", prd.getId().toString()); // } jo.put("data", one); response.getWriter().write(JSONObject.fromObject(jo).toString()); } catch(Exception e){ e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } /** * 加载第一级产品分类 * @return * @throws IOException */ public String loadTopPrdCat() throws IOException { response.setCharacterEncoding("utf-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String orgCode = this.getCurrentFenXiao().getCode(); List<ProductCat> list = service.getTopCat(orgCode); JSONObject jo = new JSONObject(); jo.put("result", "ok"); jo.put("datas", list); logger.info(jo.toString()); response.getWriter().write(jo.toString()); return null; } /** * 加载二级分类 * @return * @throws IOException */ public String loadSubPrdCat() throws IOException { response.setCharacterEncoding("utf-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String pid = request.getParameter("pid"); String orgCode = this.getCurrentFenXiao().getCode(); List<ProductCat> list = service.getSubCat(orgCode, pid); JSONObject jo = new JSONObject(); jo.put("result", "ok"); jo.put("datas", list); logger.info(jo.toString()); response.getWriter().write(jo.toString()); return null; } /** * 加载当前分销商信息 * * @return * @throws IOException */ public String loadParentOrgInfo() throws IOException { response.setCharacterEncoding("UTF-8"); // 把分销商code传递到申请页面 String orgCode = this.getCurrentFxCode(); if(orgCode == null){ JSONObject jo = new JSONObject(); jo.put("result", "fail"); response.getWriter().write(JSONObject.fromObject(jo).toString()); return null; } AdminService adminService = (AdminService) ServerBeanFactory.getBean("adminService"); Org org = adminService.getOrgBycode(orgCode); String levelName = ""; if(org.getCode().length() == CupidStrutsConstants.LV_CODE_LENGTH){ levelName = "一级分销商"; }else if(org.getCode().length() == CupidStrutsConstants.LV_CODE_LENGTH * 2){ levelName = "二级分销商"; }else if(org.getCode().length() == CupidStrutsConstants.LV_CODE_LENGTH * 3){ levelName = "三级分销商"; } JSONObject jo = new JSONObject(); jo.put("result", "ok"); jo.put("orgName", org.getOrgname()); jo.put("orgCode", org.getCode()); jo.put("levelName", levelName); response.getWriter().write(JSONObject.fromObject(jo).toString()); return null; } /** * 检查验证码是否正确 * @return */ public String checkVerifyCode(){ String code = request.getParameter("code"); JSONObject jo = new JSONObject(); try{ Object codeInsession = request.getSession().getAttribute(CupidStrutsConstants.CODE_IMAGE_REGIST); if(codeInsession != null){ if(!codeInsession.equals(code)){//验证码不正确 jo.put("result", "fail"); }else{ jo.put("result", "ok"); } } response.getWriter().write(JSONObject.fromObject(jo).toString()); }catch(Exception e){ jo.put("result", "fail"); } return null; } /** * 分销商申请 * @return * @throws IOException */ public String fxApply() throws IOException { try { //验证码判断 String codeImage = request.getParameter("codeImage"); if(codeImage == null || !codeImage.equals(request.getSession().getAttribute(CupidStrutsConstants.CODE_IMAGE_REGIST).toString())){ request.setAttribute("info", "验证码不正确,请重新输入!"); return "fxapply-biz"; } // 搜集用户个人信息 String username = request.getParameter("username"); String telephone = request.getParameter("telephone"); String email = request.getParameter("email"); //经销商编码, 这个编码应该从session里获取,因为入口链接访问过以后, 分销商编码就已经存在session里了 String orgCode = request.getSession().getAttribute(CupidStrutsConstants.FXCODE).toString(); String openId = request.getParameter("openId"); //---------test-------------- // orgCode = "000002"; openId="asdfadsfFDfgsadf"; Map<String,String> param = new HashMap<String, String>(); param.put("username", username); param.put("telephone", telephone); param.put("email", email); param.put("orgCode", orgCode); param.put("openId", openId); logger.info("分销商申请-----"+param); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); service.addSubOrg(orgCode, param); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("info", "申请成功!"); return "info"; } /** * 个人分销客申请 * Ajax方法 * @return * @throws IOException */ public String fxPersonApply() throws IOException{ try{ AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String openId = this.getCurrentUser().getOpenId(); //申请成为分销客 User user = service.applyFxPerson(openId, this.getCurrentFxCode()); if(user == null){ response.getWriter().write("{\"result\":\"fail\"}"); }else{ response.getWriter().write("{\"result\":\"ok\"}"); } //更新session request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, user); }catch(Exception e){ e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } /** * 个人分销客状态查询,是否已经申请过了 * Ajax方法 * @return * @throws IOException */ public String checkFxPersonStatus() throws IOException{ try{ AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String openId = this.getCurrentUser().getOpenId(); //申请成为分销客 User user = service.getUserByOpenId(openId); if(user.getFlag() == 1){ response.getWriter().write("{\"result\":\"ok\",\"regDate\":\""+ user.getRegDate().toString().substring(0, 10) +"\"}"); }else{ response.getWriter().write("{\"result\":\"fail\"}"); } }catch(Exception e){ e.printStackTrace(); response.getWriter().write("{\"result\":\"fail\"}"); } return null; } private String loadOrgProducts(String pid) throws IOException { response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); PrintWriter out = response.getWriter(); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 起始记录 int start = (Integer.valueOf(page) - 1) * Integer.valueOf(limit); // 分页对象 model.Paging pp = new model.Paging(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); Map<String, String> paramMap = new HashMap<String, String>(); if (request.getParameter("keyword") != null) { paramMap.put("keyword", request.getParameter("keyword")); } // ----积分兑换页面传递的参数,目的有2个,为了在列表上显示兑换按钮和兑换积分。--- if (request.getParameter("charge") != null) { paramMap.put("charge", request.getParameter("charge")); } try { Map<String, Object> map = service.getAllProductList(start, Integer.valueOf(limit).intValue(), paramMap); List<Products> dataList = (List<Products>) map.get("list"); int total = Integer.valueOf(map.get("total").toString()); pp.setPage(Integer.valueOf(page));// 当前页码 pp.setLimit(Integer.valueOf(limit));// 每页显示条数 if (!dataList.isEmpty()) { pp.setTotal(total); // 总页数 if (total % pp.getLimit() != 0) { pp.setTotalPage(total / pp.getLimit() + 1); } else { pp.setTotalPage(total / pp.getLimit()); } logger.info("数据页数:" + pp.getTotalPage()); pp.setDatas(dataList); } out.print(JSONObject.fromObject(pp).toString()); } catch (Exception e) { e.printStackTrace(); out.print("{\"result\":\"fail\"}"); } return null; } /** * 用户点击菜单,进入积分兑换页 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String scoreCharge() throws IOException { try { String openId = request.getParameter("openId"); if (openId == null) { request.setAttribute("info", "对不起,参数错误!"); return ("info"); } PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); User userByOpenId = service.getUserByOpenId(openId); request.setAttribute("username", userByOpenId.getUsername()); request.setAttribute("openId", openId); // 加载积分不为0的商品 // 到积分兑换页面 return new String("/jms/scoreCharge.jsp"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 进入提示用户关注的url * @return * @throws IOException */ public String attHintUrl() throws IOException { try { String url = this.getCurrentFenXiao().getAttHintUrl(); logger.info("提示关注的url..."+ url); if(url == null){ response.sendRedirect(request.getContextPath() + "/weixin/noAtthintUrl.jsp"); }else{ response.sendRedirect(url); } return null; } catch (Exception e) { e.printStackTrace(); response.sendRedirect(request.getContextPath() + "/weixin/noAtthintUrl.jsp"); } return null; } /** * 会员注册 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String userReg() throws IOException { try { String codeImage = request.getParameter("codeImage"); if(!codeImage.equalsIgnoreCase(request.getSession().getAttribute(CupidStrutsConstants.CODE_IMAGE_REGIST).toString())){ request.setAttribute("info", "对不起,验证码不正确!"); return "wxreg"; } AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); // 搜集用户个人信息 String username = request.getParameter("username"); String newpwd = request.getParameter("newpwd"); String confirmpwd = request.getParameter("confirmpwd"); String telephone = request.getParameter("telephone"); // String birthday = request.getParameter("birthday"); String email = request.getParameter("email"); String openId = request.getSession().getAttribute(CupidStrutsConstants.WXOPENID).toString(); logger.info("分销商注册------openId---" + openId); //根据该分销商的公众号,获取粉丝的信息 Org org = this.getCurrentFenXiao(); WxUser wxUserByOrg = WeiXinUtil.getWxUserByOrg(openId, org.getAppid(), org.getAppsecret()); logger.info("注册时:::微信用户信息:" + wxUserByOrg.toString()); String fxCode = request.getSession().getAttribute(CupidStrutsConstants.FXCODE).toString(); if (!newpwd.equals(confirmpwd)) { request.setAttribute("info", "对不起,两次密码输入不一致。"); return "wxlogin"; } User u = new User(); u.setUsername(username); u.setTelephone(telephone); u.setOpenId(openId); u.setPassword(newpwd); //------微信用户属性-------------------------- u.setNickName(wxUserByOrg.getNickName()); u.setHeadimgurl(wxUserByOrg.getHeadimgurl()); u.setCity(wxUserByOrg.getCity()); u.setProvince(wxUserByOrg.getProvince()); u.setCountry(wxUserByOrg.getCountry()); u.setSex(wxUserByOrg.getSex()); u.setSubscribTime(wxUserByOrg.getSubscribeTime()); u.setEmail(email); u.setRegDate(new Date()); // 根据fenxiaocode查询分销商 u.setOrg(service.getOrgBycode(fxCode)); u.setStatus(1);//默认可用????????????????????? // u.setBirthday(birthday); // 注册送积分 String regScore = Version.getInstance().getNewProperty("regScore"); if (regScore == null) { u.setScore(0); } else { u.setScore(Integer.valueOf(regScore)); } service.saveUser(u); request.getSession().setAttribute(CupidStrutsConstants.SESSION_USER, u); // session.put(CupidStrutsConstants.SESSION_USER, u); } catch (Exception e) { e.printStackTrace(); // 到注册成功页面 request.setAttribute("info", "注册失败!"); return "info"; } // 到注册成功页面 request.setAttribute("info", "注册成功!"); return "info"; } /** * 拿红包 * @return * @throws IOException */ public String takeHongbao() throws IOException { try{ response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String openId = request.getParameter("openId"); String uuid = request.getParameter("uuid"); if (openId == null) { response.getWriter().write("{\"result\":\"fail\"}"); return null; } //根据uuid和openId, 将红包数据和用户绑定, 并更新红包库存 int b = service.takeHongbao(this.getCurrentFenXiao().getId(), openId, uuid); JSONObject jo = new JSONObject(); if(b == 1){ jo.put("msg", "ok"); }else if(b == 9){//红包没有了 jo.put("msg", "null"); }else if(b == 2){ jo.put("msg", "multi"); }else{ jo.put("msg", "fail"); } response.getWriter().write(jo.toString()); }catch(Exception e){ e.printStackTrace(); } return null; } /** * 前台:生成红包的推广链接, 主要用来转发 * "uuid": uuid, "openId": openId, "orgId": orgId * @return * @throws IOException */ public String createHongBaoLink() throws IOException{ response.setCharacterEncoding("UTF-8"); //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfa261c6dad08e42c&redirect_uri=http%3A%2F%2Fwww.91lot.com%2Ffenxiao%2Fwx%2Fwx_wxMall.Q&response_type=code&scope=snsapi_userinfo&state=84#wechat_redirect String orgId = request.getParameter("orgId"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Org orgById = service.getOrgById(Long.valueOf(orgId)); String appId = orgById.getAppid(); String serverUrl = Version.getInstance().getNewProperty("wxServer"); logger.info("前台---createhongbaoLink---serverUrl==" + serverUrl); if(appId == null || StringUtils.isEmpty(appId)){ response.getWriter().write("{\"msg\":\"appId\"}"); return null; } // "uuid": uuid, //红包的批次代码 // "hbid": hbid 红包的数据库ID String param = request.getParameter("uuid")+","+orgId;//通过state传递的参数 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appId +"&redirect_uri=http%3A%2F%2F"+ serverUrl +"%2Fhotel%2Fwx%2Fwx_wxHongbao.Q&response_type=code&scope=snsapi_base&state="+ param +"#wechat_redirect"; response.getWriter().write("{\"msg\":\"ok\",\"result\":\""+ url +"\"}"); return null; } /** * 加载负责人,佣金, appid等信息 * * @param mapping * @param form * @param request * @param response * @return * @throws IOException */ public String loadCharger() throws IOException { try{ response.setCharacterEncoding("UTF-8"); AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String orgId = request.getParameter("id"); if (orgId == null) { response.getWriter().write("{\"result\":\"fail\"}"); return null; } Org org = service.getCharger(Long.valueOf(orgId)); JSONObject jo = new JSONObject(); if (org.getCharger() == null) { jo.put("result", "null"); } else { jo.put("result", "ok"); jo.put("id", org.getCharger().getId()); jo.put("name", org.getCharger().getUsername()); } //分销商佣金 jo.put("commission", org.getCommission()); //分销客佣金 jo.put("personCommission", org.getPersonCommission()); jo.put("appid", org.getAppid()); jo.put("appsecret", org.getAppsecret()); jo.put("wxID", org.getWxID()); jo.put("mallexpire", org.getWxmallexpire()); jo.put("shareLogo", org.getShareLogo()); jo.put("shareTitle", org.getShareTitle()); jo.put("shareDesc", org.getShareDesc()); response.getWriter().write(jo.toString()); }catch(Exception e){ e.printStackTrace(); } return null; } /** * 加载红包首页的个性化图片 * 路径: upload\org-78\hongbao\hongbao.xxx * @return */ public String loadHongBaoPic(){ String orgId = request.getParameter("orgId"); // orgId = "78"; AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Org org = service.getOrgById(Long.valueOf(orgId)); PrintWriter out = null; try { out = response.getWriter(); out.write("{\"msg\":\"ok\",\"result\":\""+ org.getHongbaoPic() +"\"}"); } catch (IOException e) { out.write("{\"msg\":\"fail\"}"); e.printStackTrace(); } return null; } public static void main(String[] args) { // DecimalFormat df = new DecimalFormat("00000"); // Number parse = df.parse("03010"); // System.out.println("parse=" + parse.intValue()); // UUID uuid = UUID.randomUUID(); // String snum = uuid.toString(); // System.out.println(snum); String text = "003"; String encode = Base64Utility.encode(text.getBytes()); String string = encode.replaceAll("=", ",") + SysUtil.getRandomCode(10); System.out.println("ENCODE=="+encode); String reverse = StringUtils.reverse(string); System.out.println("reverse str=="+reverse); byte[] decode; try { decode = Base64Utility.decode(StringUtils.reverse(reverse).substring(0, string.length() - 10).replaceAll(",", "=")); // byte[] decode = Base64Utility.decode(StringUtils.reverse(reverse)); System.out.println(new String(decode)); } catch (Base64Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String loadContact() throws IOException{ response.setCharacterEncoding("UTF-8"); String locId = request.getParameter("locId"); Long orgId = Long.valueOf(request.getParameter("orgId")); PrintWriter out = null; try{ AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); Contacts contacts = service.getContacts(orgId, Integer.valueOf(locId)); out = response.getWriter(); if(contacts != null){ JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("result", contacts); out.print(jo.toString()); } }catch(Exception e){ out.write("{\"msg\":\"fail\",\"result\":\"\"}"); } return null; } /** * 车险平台:::设置用户所在城市 * @return */ public String setCity(){ // CupidStrutsConstants.SES_CITY PrintWriter out = null; try{ out = response.getWriter(); String province = request.getParameter("province"); String city = request.getParameter("city"); User currentUser = this.getCurrentUser(); request.getSession().setAttribute(CupidStrutsConstants.SES_CITY, city); //更新数据库 AdminService ss = (AdminService) ServerBeanFactory.getBean("adminService"); currentUser.setCity(city); currentUser.setCountry("中国"); currentUser.setProvince(province); ss.updateUser(currentUser); JSONObject jo = new JSONObject(); jo.put("msg", "ok"); String encodeParam = super.encodeFxCode(this.getCurrentFenXiao().getCode()); String dest = request.getContextPath() + "/public/pub_index.Q?c=" + encodeParam; logger.info("城市设置成功("+ province + "|" + city +"), 接下去url-" + dest); //改变当前session中的FXcode,因为后面的优惠券列表是根据fenxiaoCode去查找各自代理商发布的 PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); Org org = service.getOrgByCity(city); if(org != null){ request.getSession().setAttribute(CupidStrutsConstants.FXCODE, org.getCode()); request.getSession().setAttribute(CupidStrutsConstants.WXFENXIAO, org); } jo.put("result", dest);//目标页面 out.print(jo.toString()); }catch(Exception e){ e.printStackTrace(); JSONObject jo = new JSONObject(); jo.put("msg", "fail"); out.print(jo.toString()); } return null; } /** * 车险平台:::获取发现列表 * @return * @throws IOException */ public String getFaxianLists() throws Exception { response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { AdminService service = (AdminService) ServerBeanFactory.getBean("adminService"); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 查询参数 Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("openId", this.getCurrentUser().getOpenId()); Paging pp = service.getFaxianList(Integer.valueOf(page), Integer.valueOf(limit), paramMap); if(!pp.getDatas().isEmpty()){ JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("result", pp); out.print(jo.toString()); } else { out.print("{\"msg\":\"null\"}"); } } catch (Exception e) { e.printStackTrace(); out.print("{\"msg\":\"fail\"}"); } return null; } /** * 车险服务入口 * @return */ public String carins() throws Exception{ try{ String openId = this.getCurrentUser().getOpenId(); request.setAttribute("openId", openId); return "car-ins"; // return "car-index"; }catch(Exception e){ e.printStackTrace(); } return null; } /** * 优惠券购买列表 * @return */ public String couponList(){ return "car-couponList"; } public String getRescueList() throws IOException{ response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { ICarInfoService service = (ICarInfoService) ServerBeanFactory.getBean("carService"); String page = request.getParameter("page") == null ? "0" : request.getParameter("page").toString(); String limit = request.getParameter("limit") == null ? "20" : request.getParameter("limit").toString(); // 查询参数 // Map<String, String> paramMap = getParamMap(request); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("openId", this.getCurrentUser().getOpenId()); paramMap.put("area", this.getCurrentUser().getCity()); paramMap.put("province", this.getCurrentUser().getProvince()); Paging pp = service.getRescueList(Integer.valueOf(page), Integer.valueOf(limit), paramMap); if(!pp.getDatas().isEmpty()){ out.print(JSONObject.fromObject(pp).toString()); } else { out.print("{\"msg\":\"null\"}"); } } catch (Exception e) { e.printStackTrace(); out.print("{\"msg\":\"fail\"}"); } return null; } /** * 初始化优惠券分类 * @return * @throws Exception */ public String loadCouponCats() throws Exception{ response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { IProductCatService service = (IProductCatService) ServerBeanFactory.getBean("productCatService"); List<ProductCat> pcats = service.getPrdCatsByParentId(0L); List<ProductCat> cats = new ArrayList<ProductCat>(); ProductCat p = null; if(pcats.size() > 1){//没有父级的情况 cats = pcats; }else{// p = pcats.get(0);//根节点,===优惠券 cats = service.getPrdCatsByParentId(p.getId()); } if(!cats.isEmpty()){ JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("result", cats); out.print(jo.toString()); } else { out.print("{\"msg\":\"null\"}"); } } catch (Exception e) { e.printStackTrace(); out.print("{\"msg\":\"fail\"}"); } return null; } public String loadFaxianDetail() throws IOException{ response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try{ String dbId = request.getParameter("dbId"); PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); ShowCase sc = service.getShowCase(dbId); if(sc != null){ JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("result", sc); out.print(jo.toString()); } else { out.print("{\"msg\":\"null\"}"); } }catch(Exception e){ e.printStackTrace(); request.setAttribute("info", "获取信息失败"); return "info"; } return null; } /** * 加载推荐优惠券 * @return * @throws IOException */ public String loadRecommended() throws IOException{ response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try{ PublicService service = (PublicService) ServerBeanFactory.getBean("publicService"); List<AdvConfig> list = service.getRecommendedList(this.getCurrentFenXiao().getId()); if(list != null && !list.isEmpty()){ JSONObject jo = new JSONObject(); jo.put("msg", "ok"); jo.put("result", list); out.print(jo.toString()); } else { out.print("{\"msg\":\"null\"}"); } }catch(Exception e){ e.printStackTrace(); request.setAttribute("info", "获取信息失败"); return "info"; } return null; } }
b9b0888f2197921ea3823df8fc0c125c2fb4e674
5f507bc3497310c5debe085a2a82743c5e263ed3
/base/src/test/java/de/n26/n26androidsamples/base/common/preconditions/PreconditionsTest.java
ef1039e41ec6a73bb0c448acd89fb3e56a9a0404
[ "Apache-2.0" ]
permissive
hbnetBen/N26AndroidSamples
0883d43690b1c6ea6965d849c42630c49b9d89a9
edc9c90a9e43b72dee80b848fdb1e5e62005bc46
refs/heads/master
2020-04-02T06:09:24.008241
2017-09-12T10:02:08
2017-09-12T10:02:08
154,132,824
1
0
NOASSERTION
2018-10-22T11:36:37
2018-10-22T11:36:37
null
UTF-8
Java
false
false
1,416
java
package de.n26.n26androidsamples.base.common.preconditions; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.assertj.core.api.Assertions.assertThat; public class PreconditionsTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void checkNotNull_doesNotThrowException_whenNonNull() { Preconditions.checkNotNull(new Object()); } @Test public void checkNotNull_throwsNullPointerException_whenNull() { thrown.expect(NullPointerException.class); Preconditions.checkNotNull(null); } @Test public void checkNotNullWithMessage_doesNotThrowException_whenNonNull() { Preconditions.checkNotNull(new Object(), "Unused message"); } @Test public void checkNotNullWithMessage_throwsNullPointerExceptionWithMessage_whenNull() { final String message = "message"; thrown.expect(NullPointerException.class); thrown.expectMessage(message); Preconditions.checkNotNull(null, message); } @Test public void get_returnsParameter_whenNonNull() { Object obj = new Object(); assertThat(Preconditions.get(obj)).isEqualTo(obj); } @Test public void get_throwsNullPointerException_whenNull() { thrown.expect(NullPointerException.class); Preconditions.get(null); } }
79b26ffa4645af2b9552d8425da8400934819889
217c52a593aa555bc33d09cb058cd66ddb0ec68e
/LibraryManagmentBeeHyvCaseStudyJwt[Backend_JAVA]/src/test/java/com/beehyv/demo/BookServiceTest.java
9911ffb4f6cef021b1d422e76ccba4f7b84007b5
[]
no_license
Sreejit-K/Library--Tracking-System-Angular-SpringBoot-Project
3c517afc1e5c3f30d131715b2587ddc141cd7ae1
dbe3af21da9e0d5d37284327d15f9b91718fa650
refs/heads/master
2023-03-24T03:41:24.417988
2021-03-25T15:30:27
2021-03-25T15:30:27
351,483,210
0
0
null
null
null
null
UTF-8
Java
false
false
7,723
java
package com.beehyv.demo; import static org.junit.Assert.assertEquals; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.beehyv.demo.Dto.BookDto; import com.beehyv.demo.model.Book; import com.beehyv.demo.repository.BookRepository; import com.beehyv.demo.repository.BorrowRepository; import com.beehyv.demo.repository.StudentRepository; import com.beehyv.demo.service.BookService; import com.beehyv.demo.service.StudentService; import javassist.NotFoundException; @ExtendWith(MockitoExtension.class) @ExtendWith(SpringExtension.class) @SpringBootTest @TestMethodOrder(OrderAnnotation.class) public class BookServiceTest { @MockBean private StudentRepository studentRepository; @MockBean private BookRepository bookRepository; @MockBean private BorrowRepository borrowRepository; @InjectMocks private StudentService studentService; @InjectMocks private BookService bookService; //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void saveBookTest() throws NotFoundException { Book book = new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19) ; Mockito.when(bookRepository.save(book)).thenReturn(book) ; assertEquals(book, bookService.saveBook(book) ); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getBookbyTitleTest() throws NotFoundException { String title = "Twilight"; Book book = new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19) ; Mockito.when(bookRepository.findByTitle(title)).thenReturn(book) ; assertEquals(book, bookService.getBookByTitle(title)); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getAllBooksTest() throws NotFoundException { Mockito.when(bookRepository.findAll()).thenReturn(Stream.of( new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19), new Book(2,"Fantasy", "amsworth", "You", "ComiconLimited", 43, 21, 65, 19,"BeehyvLtd", "OutOfStock", 29)).collect(Collectors.toList())) ; assertEquals(2, bookService.getAllBooks().size()); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getBookByIdTest() throws NotFoundException { int id = 1; Optional<Book> book = Optional.of(new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19)); Mockito.when(bookRepository.findById(id)).thenReturn(book); assertEquals(book.get(), bookService.getBookById(id)); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void updateStudentByIdTest() throws NotFoundException { BookDto bookDto = new BookDto(1, "heamsworth", "FantasyBooks", "Twilight", "ComiconLimited", 34, 12, 56, 9, "BeehyvLtd", "OutOfStock"); Optional<Book> book = Optional.of(new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19)); Mockito.when(bookRepository.findById(bookDto.getBookId())).thenReturn(book); Mockito.when(bookRepository.save(book.get())).thenReturn(book.get()); assertEquals(bookDto.toString() ,bookService.updateBook(book.get()).toString()); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void deleteStudentByIdTest() throws Throwable { int id = 1 ; Optional<Book> book = Optional.of(new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19)); Mockito.when(bookRepository.findById(id)).thenReturn(book); assertEquals("Book has been made unavailable with id : " + id , bookService.deleteBook(id)); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getAlltrendingBooksTest() throws NotFoundException { Mockito.when(bookRepository.findListOfBestBorrowedBooks()).thenReturn(Stream.of( new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19), new Book(2,"Fantasy", "amsworth", "You", "ComiconLimited", 43, 21, 65, 19,"BeehyvLtd", "OutOfStock", 29)).collect(Collectors.toList())) ; assertEquals(2, bookService.OrderOfBestBooks().size()); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getAllTrendingBooksPerCategoryTest() throws NotFoundException { String subject = "Fantasy"; Mockito.when(bookRepository.SearchBestBooksBySubject(subject)).thenReturn(Stream.of( new Book(1,"Fantasy", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19), new Book(2,"Fantasy", "amsworth", "You", "ComiconLimited", 43, 21, 65, 19,"BeehyvLtd", "OutOfStock", 29)).collect(Collectors.toList())) ; assertEquals(2, bookService.OrderOfBestSubjectBooks(subject).size()); } //---------------------------------------------------------------------------------------------------------------------------------------------------- @Test public void getBookByAuthorsTest() throws NotFoundException { String authors = "heamsworth"; Book book = new Book(1,"FantasyBooks", "heamsworth", "Twilight", "ComiconLimited", 34, 12, 56, 9,"BeehyvLtd", "OutOfStock", 19) ; Mockito.when(bookRepository.findByAuthors(authors)).thenReturn(book) ; assertEquals(book, bookService.findByAuthors(authors)); } //---------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------------------- }
fdf5390863297171ace3170f354edcfb042a7ace
3e8c365557763d021f67ceb20b5bec45ff530552
/src/DungeonCrawl/HeroPowers/Sorcerer/ThunderSlam.java
2469015e04b73b67eb139d1068dcef69c8615ccf
[]
no_license
Epasper/DungeonCrawl
7b2124fb880f90251bc30169d29e7941c1cf95d7
a106b4d6279bb3e50d277a6da5c75491708787e4
refs/heads/master
2023-04-27T21:50:41.785927
2019-08-07T07:56:17
2019-08-07T07:56:17
181,691,645
0
0
null
null
null
null
UTF-8
Java
false
false
1,164
java
package DungeonCrawl.HeroPowers.Sorcerer; import DungeonCrawl.HeroPowers.HeroPower; import DungeonCrawl.StaticRules.HeroClasses; import DungeonCrawl.StaticRules.TypesOfPowers; import DungeonCrawl.StaticRules.AttributeNames; import DungeonCrawl.StaticRules.CreatureDefenses; import DungeonCrawl.StaticRules.TypesOfActions; public class ThunderSlam extends HeroPower { public ThunderSlam() { setPowerName("Thunder Slam"); setCharacterClass(HeroClasses.Sorcerer.toString()); setTypeOfPower(TypesOfPowers.ENCOUNTER.toString().replace('_', ' ').toLowerCase()); setUsedAction(TypesOfActions.STANDARD.toString().toLowerCase()); setPowerLevel(1); setRange(10); setNumberOfTargets("one target"); setAttributeUsedToHit(AttributeNames.Charisma.toString()); setDefenseToBeChecked(CreatureDefenses.Fortitude.toString()); setDamageDiceDealt(2); setTypeOfDamageDice(10); setDamageModifier(AttributeNames.Charisma.toString()); setThisWeaponDamage(false); setHitDescription("2d10 + Charisma modifier thunder damage, and you push the target 3 squares."); } }
9289216ad85817a3eae33dbd88182c30d2ced066
dd59639b4b47aa75d4fd450be68b05e9c2a3810c
/InfoSource/src/main/java/webframeapp/interfaces/RelateEntities.java
ad9fea78d7e335025b12427a8aad140f848cc5d8
[]
no_license
sikza/ICTDTech
bcae8c1147e86afe334a7bfae752c33389819d8a
7cf57a10baf908dd9698f31c0e6575b8cbc02b0d
refs/heads/master
2021-09-20T13:49:37.181383
2018-08-10T06:36:27
2018-08-10T06:36:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,485
java
package webframeapp.interfaces; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for relateEntities complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="relateEntities"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="arg0" type="{http://interfaces.webFrameApp/}orgEntity" minOccurs="0"/> * &lt;element name="arg1" type="{http://interfaces.webFrameApp/}orgEntity" minOccurs="0"/> * &lt;element name="arg2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="arg3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="arg4" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "relateEntities", propOrder = { "arg0", "arg1", "arg2", "arg3", "arg4" }) public class RelateEntities { protected OrgEntity arg0; protected OrgEntity arg1; protected String arg2; protected String arg3; protected boolean arg4; /** * Gets the value of the arg0 property. * * @return * possible object is * {@link OrgEntity } * */ public OrgEntity getArg0() { return arg0; } /** * Sets the value of the arg0 property. * * @param value * allowed object is * {@link OrgEntity } * */ public void setArg0(OrgEntity value) { this.arg0 = value; } /** * Gets the value of the arg1 property. * * @return * possible object is * {@link OrgEntity } * */ public OrgEntity getArg1() { return arg1; } /** * Sets the value of the arg1 property. * * @param value * allowed object is * {@link OrgEntity } * */ public void setArg1(OrgEntity value) { this.arg1 = value; } /** * Gets the value of the arg2 property. * * @return * possible object is * {@link String } * */ public String getArg2() { return arg2; } /** * Sets the value of the arg2 property. * * @param value * allowed object is * {@link String } * */ public void setArg2(String value) { this.arg2 = value; } /** * Gets the value of the arg3 property. * * @return * possible object is * {@link String } * */ public String getArg3() { return arg3; } /** * Sets the value of the arg3 property. * * @param value * allowed object is * {@link String } * */ public void setArg3(String value) { this.arg3 = value; } /** * Gets the value of the arg4 property. * */ public boolean isArg4() { return arg4; } /** * Sets the value of the arg4 property. * */ public void setArg4(boolean value) { this.arg4 = value; } }
f27839f477553eb44aa3f3f536b20ab17e4d42f6
5fb0e7082e5a3831d2096f59620600cdadc4508c
/src/com/trading/servlet/MakeTradeServlet.java
5cf2cc1a36241c0845901632830d036df7ec3ac4
[]
no_license
deep-lee/TradingPlatformWeb
9347392d7385ae8282ce41be17059ed12a3eeee6
a7f5671790545865b04b2ed54cc08c0e06a3a347
refs/heads/master
2021-01-15T10:35:06.317770
2017-08-08T13:19:39
2017-08-08T13:19:39
99,589,625
0
0
null
null
null
null
UTF-8
Java
false
false
1,682
java
package com.trading.servlet; import java.io.IOException; import java.sql.SQLException; 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 com.trading.service.MakeTradeService; /** * Servlet implementation class MakeTradeServlet */ @WebServlet("/MakeTradeServlet") public class MakeTradeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private MakeTradeService makeTradeService; /** * @see HttpServlet#HttpServlet() */ public MakeTradeServlet() { super(); // TODO Auto-generated constructor stub makeTradeService = new MakeTradeService (); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); try { makeTradeService.makeTrade (request); } catch (NumberFormatException | ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
f77afc456bc5bcc4bc8c60299810b028f546cd45
b4e122e0c0bf26397a7ca1348cbd4a78212d2de8
/app/src/main/java/com/study/hotfixdemo/HotFix/LoadBugClass.java
65f9102a13d7f93b0b0c6dfe46e2d82a58e50d03
[]
no_license
hcgrady2/HotFixDemo
5b1359d9fc5e869dece8ab361574667219e95b47
6bd3cd1bc5a92730f2fc3cd500cf3c13f88fe5cd
refs/heads/master
2020-04-27T08:04:40.465257
2019-03-08T06:57:42
2019-03-08T06:57:42
174,158,229
0
0
null
null
null
null
UTF-8
Java
false
false
238
java
package com.study.hotfixdemo.HotFix; /** * Created by WenTong on 2019/3/8. */ public class LoadBugClass { public String getBugString() { BugClass bugClass = new BugClass(); return bugClass.bug(); } }
635f9dbf2b42dabe3fb5e31cdc09a8ce6e8c54dd
e799d9ac9a097af833d319c2aabdee38476a80e9
/src/main/java/RestaurantService.java
2dfd31bec31b1c68254f0876fcdcfc5fd43ee484
[]
no_license
saivamsi96/C3_Project_Sai_Vamsi
2a2c404e26ef37b69ee129d473a6450a63cb3f80
a425f9ea697201cbfebcd020c8e0a52301f6ad58
refs/heads/master
2023-04-01T03:18:04.502901
2021-04-03T11:51:45
2021-04-03T11:51:45
354,272,979
0
0
null
null
null
null
UTF-8
Java
false
false
1,209
java
import java.time.LocalTime; import java.util.ArrayList; import java.util.List; public class RestaurantService { private static List<Restaurant> restaurants = new ArrayList<>(); public Restaurant findRestaurantByName(String restaurantName) throws restaurantNotFoundException { //DELETE ABOVE STATEMENT AND WRITE CODE HERE for(Restaurant restaurant: restaurants){ if(restaurant.getName().equals(restaurantName)); return restaurant; } throw new restaurantNotFoundException(restaurantName); } public Restaurant addRestaurant(String name, String location, LocalTime openingTime, LocalTime closingTime) { Restaurant newRestaurant = new Restaurant(name, location, openingTime, closingTime); restaurants.add(newRestaurant); return newRestaurant; } public Restaurant removeRestaurant(String restaurantName) throws restaurantNotFoundException { Restaurant restaurantToBeRemoved = findRestaurantByName(restaurantName); restaurants.remove(restaurantToBeRemoved); return restaurantToBeRemoved; } public List<Restaurant> getRestaurants() { return restaurants; } }
c81905e44ab8e02b8757b0ff20c662ab103f92ba
7cf8860695d83086fb84cc5cd2e07695b41d309a
/src/main/java/org/zeroturnaround/jenkins/reporter/ReadTestReportHandler.java
5aa92861898566eef0c1f73245354ea5db8b99f1
[ "Apache-2.0" ]
permissive
vovan-/jenkins-reporter
423420e0f0345edb7d2e82217e7e0aa1ac8528eb
293e8897bac7a8990e34c013f84c45cc54b3af9b
refs/heads/master
2020-03-17T10:38:08.429695
2015-12-05T13:26:10
2015-12-05T13:26:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,799
java
package org.zeroturnaround.jenkins.reporter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.zeroturnaround.jenkins.reporter.model.TestCase; import org.zeroturnaround.jenkins.reporter.model.TestReport; public final class ReadTestReportHandler extends DefaultHandler { private final TestReport testReport; private boolean ageNode = false; private boolean classNameNode = false; private StringBuffer errorDetails, errorStackTrace; private boolean errorDetailsNode = false; private boolean errorStackTraceNode = false; private boolean failCountNode = false; private boolean matrixJob; private boolean methodNameNode = false; private boolean passCountNode = false; private boolean plainJob; private boolean rootNode = false; private boolean skipCountNode = false; private boolean statusNode = false; private TestCase testCase; private boolean totalCountNode = false; ReadTestReportHandler(TestReport testReport) { this.testReport = testReport; } @Override public void characters(char ch[], int start, int length) throws SAXException { if (rootNode && failCountNode) { testReport.setFailCount(Integer.parseInt(new String(ch, start, length))); } else if (rootNode && skipCountNode) { testReport.setSkipCount(Integer.parseInt(new String(ch, start, length))); } else if (rootNode && passCountNode) { testReport.setPassCount(Integer.parseInt(new String(ch, start, length))); } else if (rootNode && totalCountNode) { testReport.setTotalCount(Integer.parseInt(new String(ch, start, length))); } else if (statusNode) { testCase.setStatus(new String(ch, start, length)); } else if (ageNode) { testCase.setAge(Integer.parseInt(new String(ch, start, length))); } else if (classNameNode) { testCase.setClassName(new String(ch, start, length)); } else if (methodNameNode) { testCase.setMethodName(new String(ch, start, length)); } else if (errorDetailsNode) { errorDetails.append(new String(ch, start, length)); } else if (errorStackTraceNode) { errorStackTrace.append(new String(ch, start, length)); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("matrixTestResult")) { rootNode = false; } else if (qName.equals("testResult")) { rootNode = false; } else if (qName.equalsIgnoreCase("case")) { if (testCase.getStatus() != null && (testCase.getStatus().equals("FAILED") || testCase.getStatus().equals("REGRESSION"))) { testReport.getTestCases().add(testCase); testCase = new TestCase(); // to avoid mutating it later (e.g. <name> tag occurs outside of <case> too) } } else if (failCountNode) { failCountNode = false; } else if (qName.equalsIgnoreCase("skipCount")) { skipCountNode = false; } else if (qName.equalsIgnoreCase("passCount")) { passCountNode = false; } else if (qName.equalsIgnoreCase("totalCount")) { totalCountNode = false; } else if (statusNode) { statusNode = false; } else if (ageNode) { ageNode = false; } else if (classNameNode) { classNameNode = false; } else if (methodNameNode) { methodNameNode = false; } else if (qName.equalsIgnoreCase("errorDetails")) { errorDetailsNode = false; testCase.setErrorDetails(errorDetails.toString()); errorDetails = null; } else if (qName.equalsIgnoreCase("errorStackTrace")) { errorStackTraceNode = false; testCase.setErrorStackTrace(errorStackTrace.toString()); errorStackTrace = null; } } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equals("matrixTestResult")) { matrixJob = true; rootNode = true; } else if (qName.equals("testResult")) { plainJob = true; rootNode = true; } else if (qName.equalsIgnoreCase("childReport")) { if (matrixJob) { // "childReport" is next element after the header in // matrix job rootNode = false; } } else if (qName.equalsIgnoreCase("suite")) { if (plainJob) { // "suite" is next element after the header in // plain job rootNode = false; // in case of plain job we need to calculate totalCount // manually if (testReport.getTotalCount() == 0) { testReport.setTotalCount(testReport.getPassCount() + testReport.getFailCount() + testReport.getSkipCount()); } } } else if (qName.equalsIgnoreCase("case")) { testCase = new TestCase(); } else if (qName.equalsIgnoreCase("failCount")) { failCountNode = true; } else if (qName.equalsIgnoreCase("skipCount")) { skipCountNode = true; } else if (qName.equalsIgnoreCase("passCount")) { passCountNode = true; } else if (qName.equalsIgnoreCase("totalCount")) { totalCountNode = true; } else if (qName.equalsIgnoreCase("status")) { statusNode = true; } else if (qName.equalsIgnoreCase("age")) { ageNode = true; } else if (qName.equalsIgnoreCase("className")) { classNameNode = true; } else if (qName.equalsIgnoreCase("name")) { methodNameNode = true; } else if (qName.equalsIgnoreCase("errorDetails")) { errorDetailsNode = true; errorDetails = new StringBuffer(); } else if (qName.equalsIgnoreCase("errorStackTrace")) { errorStackTraceNode = true; errorStackTrace = new StringBuffer(); } } }
658880c63b01d8e244101431a8bcc2af4a4f3f9d
b202c4ca3b1c78d6ec280b87bf27880c4f720aa8
/hookTest/mylibrary/src/com/lingcloud/apptrace/sdk/NetInfors.java
ee720cea73d3330290a5863ba0b38e58ece3d131
[]
no_license
hetianlong0/hookTest
01213f029561c5e4343501bb50faee9be3656ece
8b675a0e17f69b4b4345592689dd5c676ea5583e
refs/heads/master
2020-09-22T17:54:42.108818
2016-09-05T01:50:37
2016-09-05T01:50:37
66,046,285
0
0
null
null
null
null
UTF-8
Java
false
false
154
java
package com.lingcloud.apptrace.sdk; public class NetInfors { //获得本机IP地址 public String ip; //获得网络类型 public String net_type; }
cdd018a1329952de1a65907e2e5b4ef8079c642c
bbb8bacf0e8eac052de398d3e5d75da3ded226d2
/emulator_dev/src/main/java/gr/codebb/arcadeflex/WIP/v037b7/mame/gfxobjC.java
459bca9c97882869fd7675bef71b642246058e6a
[]
no_license
georgemoralis/arcadeflex-037b7-deprecated
f9ab8e08b2e8246c0e982f2cfa7ff73b695b1705
0777b9c5328e0dd55e2059795738538fd5c67259
refs/heads/main
2023-05-31T06:55:21.979527
2021-06-16T17:47:07
2021-06-16T17:47:07
326,236,655
1
0
null
null
null
null
UTF-8
Java
false
false
9,417
java
/* * ported to 0.37b7 */ package gr.codebb.arcadeflex.WIP.v037b7.mame; public class gfxobjC { /*TODO*///static struct gfx_object_list *first_object_list; public static void gfxobj_init() { /*TODO*/// first_object_list = 0; } public static void gfxobj_close() { /*TODO*/// struct gfx_object_list *object_list,*object_next; /*TODO*/// for(object_list = first_object_list ; object_list != 0 ; object_list=object_next) /*TODO*/// { /*TODO*/// free(object_list->objects); /*TODO*/// object_next = object_list->next; /*TODO*/// free(object_list); /*TODO*/// } } /*TODO*/// /*TODO*///#define MAX_PRIORITY 16 /*TODO*///struct gfx_object_list *gfxobj_create(int nums,int max_priority,const struct gfx_object *def_object) /*TODO*///{ /*TODO*/// struct gfx_object_list *object_list; /*TODO*/// int i; /*TODO*/// /*TODO*/// /* priority limit check */ /*TODO*/// if(max_priority >= MAX_PRIORITY) /*TODO*/// return 0; /*TODO*/// /*TODO*/// /* allocate object liset */ /*TODO*/// if( (object_list = malloc(sizeof(struct gfx_object_list))) == 0 ) /*TODO*/// return 0; /*TODO*/// memset(object_list,0,sizeof(struct gfx_object_list)); /*TODO*/// /*TODO*/// /* allocate objects */ /*TODO*/// if( (object_list->objects = malloc(nums*sizeof(struct gfx_object))) == 0) /*TODO*/// { /*TODO*/// free(object_list); /*TODO*/// return 0; /*TODO*/// } /*TODO*/// if(def_object == 0) /*TODO*/// { /* clear all objects */ /*TODO*/// memset(object_list->objects,0,nums*sizeof(struct gfx_object)); /*TODO*/// } /*TODO*/// else /*TODO*/// { /* preset with default objects */ /*TODO*/// for(i=0;i<nums;i++) /*TODO*/// memcpy(&object_list->objects[i],def_object,sizeof(struct gfx_object)); /*TODO*/// } /*TODO*/// /* setup objects */ /*TODO*/// for(i=0;i<nums;i++) /*TODO*/// { /*TODO*/// /* dirty flag */ /*TODO*/// object_list->objects[i].dirty_flag = GFXOBJ_DIRTY_ALL; /*TODO*/// /* link map */ /*TODO*/// object_list->objects[i].next = &object_list->objects[i+1]; /*TODO*/// } /*TODO*/// /* setup object_list */ /*TODO*/// object_list->max_priority = max_priority; /*TODO*/// object_list->nums = nums; /*TODO*/// object_list->first_object = object_list->objects; /* top of link */ /*TODO*/// object_list->objects[nums-1].next = 0; /* bottom of link */ /*TODO*/// object_list->sort_type = GFXOBJ_SORT_DEFAULT; /*TODO*/// /* resource tracking */ /*TODO*/// object_list->next = first_object_list; /*TODO*/// first_object_list = object_list; /*TODO*/// /*TODO*/// return object_list; /*TODO*///} /*TODO*/// /*TODO*////* set pixel dirty flag */ /*TODO*///void gfxobj_mark_all_pixels_dirty(struct gfx_object_list *object_list) /*TODO*///{ /*TODO*/// /* don't care , gfx object manager don't keep color remapped bitmap */ /*TODO*///} /*TODO*/// /*TODO*////* update object */ /*TODO*///static void object_update(struct gfx_object *object) /*TODO*///{ /*TODO*/// int min_x,min_y,max_x,max_y; /*TODO*/// /*TODO*/// /* clear dirty flag */ /*TODO*/// object->dirty_flag = 0; /*TODO*/// /*TODO*/// /* if gfx == 0 ,then bypass (for special_handler ) */ /*TODO*/// if(object->gfx == 0) /*TODO*/// return; /*TODO*/// /*TODO*/// /* check visible area */ /*TODO*/// min_x = Machine->visible_area.min_x; /*TODO*/// max_x = Machine->visible_area.max_x; /*TODO*/// min_y = Machine->visible_area.min_y; /*TODO*/// max_y = Machine->visible_area.max_y; /*TODO*/// if( /*TODO*/// (object->width==0) || /*TODO*/// (object->height==0) || /*TODO*/// (object->sx > max_x) || /*TODO*/// (object->sy > max_y) || /*TODO*/// (object->sx+object->width <= min_x) || /*TODO*/// (object->sy+object->height <= min_y) ) /*TODO*/// { /* outside of visible area */ /*TODO*/// object->visible = 0; /*TODO*/// return; /*TODO*/// } /*TODO*/// object->visible = 1; /*TODO*/// /* set draw position with adjust source offset */ /*TODO*/// object->draw_x = object->sx - /*TODO*/// ( object->flipx ? /*TODO*/// (object->gfx->width - (object->left + object->width)) : /* flip */ /*TODO*/// (object->left) /* non flip */ /*TODO*/// ); /*TODO*/// /*TODO*/// object->draw_y = object->sy - /*TODO*/// ( object->flipy ? /*TODO*/// (object->gfx->height - (object->top + object->height)) : /* flip */ /*TODO*/// (object->top) /* non flip */ /*TODO*/// ); /*TODO*/// /* set clipping point to object draw area */ /*TODO*/// object->clip.min_x = object->sx; /*TODO*/// object->clip.max_x = object->sx + object->width -1; /*TODO*/// object->clip.min_y = object->sy; /*TODO*/// object->clip.max_y = object->sy + object->height -1; /*TODO*/// /* adjust clipping point with visible area */ /*TODO*/// if (object->clip.min_x < min_x) object->clip.min_x = min_x; /*TODO*/// if (object->clip.max_x > max_x) object->clip.max_x = max_x; /*TODO*/// if (object->clip.min_y < min_y) object->clip.min_y = min_y; /*TODO*/// if (object->clip.max_y > max_y) object->clip.max_y = max_y; /*TODO*///} /*TODO*/// /*TODO*////* update one of object list */ /*TODO*///static void gfxobj_update_one(struct gfx_object_list *object_list) /*TODO*///{ /*TODO*/// struct gfx_object *object; /*TODO*/// struct gfx_object *start_object,*last_object; /*TODO*/// int dx,start_priority,end_priority; /*TODO*/// int priorities = object_list->max_priority; /*TODO*/// int priority; /*TODO*/// /*TODO*/// if(object_list->sort_type&GFXOBJ_DO_SORT) /*TODO*/// { /*TODO*/// struct gfx_object *top_object[MAX_PRIORITY],*end_object[MAX_PRIORITY]; /*TODO*/// /* object sort direction */ /*TODO*/// if(object_list->sort_type&GFXOBJ_SORT_OBJECT_BACK) /*TODO*/// { /*TODO*/// start_object = object_list->objects + object_list->nums-1; /*TODO*/// last_object = object_list->objects-1; /*TODO*/// dx = -1; /*TODO*/// } /*TODO*/// else /*TODO*/// { /*TODO*/// start_object = object_list->objects; /*TODO*/// last_object = object_list->objects + object_list->nums; /*TODO*/// dx = 1; /*TODO*/// } /*TODO*/// /* reset each priority point */ /*TODO*/// for( priority = 0; priority < priorities; priority++ ) /*TODO*/// end_object[priority] = 0; /*TODO*/// /* update and sort */ /*TODO*/// for(object=start_object ; object != last_object ; object+=dx) /*TODO*/// { /*TODO*/// /* update all objects */ /*TODO*/// if(object->dirty_flag) /*TODO*/// object_update(object); /*TODO*/// /* store link */ /*TODO*/// if(object->visible) /*TODO*/// { /*TODO*/// priority = object->priority; /*TODO*/// if(end_object[priority]) /*TODO*/// end_object[priority]->next = object; /*TODO*/// else /*TODO*/// top_object[priority] = object; /*TODO*/// end_object[priority] = object; /*TODO*/// } /*TODO*/// } /*TODO*/// /*TODO*/// /* priority sort direction */ /*TODO*/// if(object_list->sort_type&GFXOBJ_SORT_PRIORITY_BACK) /*TODO*/// { /*TODO*/// start_priority = priorities-1; /*TODO*/// end_priority = -1; /*TODO*/// dx = -1; /*TODO*/// } /*TODO*/// else /*TODO*/// { /*TODO*/// start_priority = 0; /*TODO*/// end_priority = priorities; /*TODO*/// dx = 1; /*TODO*/// } /*TODO*/// /* link between priority */ /*TODO*/// last_object = 0; /*TODO*/// for( priority = start_priority; priority != end_priority; priority+=dx ) /*TODO*/// { /*TODO*/// if(end_object[priority]) /*TODO*/// { /*TODO*/// if(last_object) /*TODO*/// last_object->next = top_object[priority]; /*TODO*/// else /*TODO*/// object_list->first_object = top_object[priority]; /*TODO*/// last_object = end_object[priority]; /*TODO*/// } /*TODO*/// } /*TODO*/// if(last_object == 0 ) /*TODO*/// object_list->first_object = 0; /*TODO*/// else /*TODO*/// last_object->next = 0; /*TODO*/// } /*TODO*/// else /*TODO*/// { /* non sort , update only linked object */ /*TODO*/// for(object=object_list->first_object ; object !=0 ; object=object->next) /*TODO*/// { /*TODO*/// /* update all objects */ /*TODO*/// if(object->dirty_flag) /*TODO*/// object_update(object); /*TODO*/// } /*TODO*/// } /*TODO*/// /* palette resource */ /*TODO*/// if(object->palette_flag) /*TODO*/// { /*TODO*/// /* !!!!! do not supported yet !!!!! */ /*TODO*/// } /*TODO*///} /*TODO*/// /*TODO*///void gfxobj_update(void) /*TODO*///{ /*TODO*/// struct gfx_object_list *object_list; /*TODO*/// /*TODO*/// for(object_list=first_object_list ; object_list != 0 ; object_list=object_list->next) /*TODO*/// gfxobj_update_one(object_list); /*TODO*///} /*TODO*/// /*TODO*///static void draw_object_one(struct osd_bitmap *bitmap,struct gfx_object *object) /*TODO*///{ /*TODO*/// if(object->special_handler) /*TODO*/// { /* special object , callback user draw handler */ /*TODO*/// object->special_handler(bitmap,object); /*TODO*/// } /*TODO*/// else /*TODO*/// { /* normaly gfx object */ /*TODO*/// drawgfx(bitmap,object->gfx, /*TODO*/// object->code, /*TODO*/// object->color, /*TODO*/// object->flipx, /*TODO*/// object->flipy, /*TODO*/// object->draw_x, /*TODO*/// object->draw_y, /*TODO*/// &object->clip, /*TODO*/// object->transparency, /*TODO*/// object->transparet_color); /*TODO*/// } /*TODO*///} /*TODO*/// /*TODO*///void gfxobj_draw(struct gfx_object_list *object_list) /*TODO*///{ /*TODO*/// struct osd_bitmap *bitmap = Machine->scrbitmap; /*TODO*/// struct gfx_object *object; /*TODO*/// /*TODO*/// for(object=object_list->first_object ; object ; object=object->next) /*TODO*/// { /*TODO*/// if(object->visible ) /*TODO*/// draw_object_one(bitmap,object); /*TODO*/// } /*TODO*///} }
976c5c60e0e87e0bf3f8968dbf4caebdefc615ae
21a66613cc7121e8527389fcef0e246b3dc7b382
/Java/Basico/08 Arreglos de registros/01 Referencias a objetos/Referencias.java
3876d2f80b220cf84b4036c55efd44e9ff63089f
[]
no_license
BarreraSlzr/Aprendiendo
5e6efd535c636f53ca12e216bbc00742d41083e3
e1b1032be30df797d4ae46705bc8df6d2e0f820a
refs/heads/master
2021-07-14T07:54:03.861703
2017-10-18T18:17:32
2017-10-18T18:17:32
107,445,286
0
0
null
null
null
null
UTF-8
Java
false
false
739
java
public class Referencias { public static void main(String args[]){ Persona luis=new Persona(); Persona alberto; luis.nombre="Luis Alberto"; luis.telefono=1234567; alberto=luis; System.out.println("Valores originales"); System.out.println("luis.nombre:"+luis.nombre+ ", telefono:"+luis.telefono); System.out.println("alberto.nombre:"+alberto.nombre+ ", telefono:"+alberto.telefono); System.out.println("Valores modificados"); alberto.telefono=7890123; System.out.println("luis.nombre:"+luis.nombre+ ", telefono:"+luis.telefono); System.out.println("alberto.nombre:"+alberto.nombre+ ", telefono:"+alberto.telefono); } } class Persona{ String nombre; long telefono; }
1f2da841fd092b59d1562f68576f5bbc9f08710e
a3e9de23131f569c1632c40e215c78e55a78289a
/alipay/alipay_sdk/src/main/java/com/alipay/api/domain/KoubeiRetailShopitemModifyModel.java
4d156211a72f74843ff162f2ef46d63ea348b055
[]
no_license
P79N6A/java_practice
80886700ffd7c33c2e9f4b202af7bb29931bf03d
4c7abb4cde75262a60e7b6d270206ee42bb57888
refs/heads/master
2020-04-14T19:55:52.365544
2019-01-04T07:39:40
2019-01-04T07:39:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,913
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * isv 回传的门店商品信更新接口 * * @author auto create * @since 1.0, 2017-04-14 18:08:34 */ public class KoubeiRetailShopitemModifyModel extends AlipayObject { private static final long serialVersionUID = 8294256129132337653L; /** * 店铺商品的品牌名称 */ @ApiField("brand_code") private String brandCode; /** * 店铺商品的商品类别 */ @ApiField("category_code") private String categoryCode; /** * 商品描述 */ @ApiField("description") private String description; /** * 店铺商品SKU */ @ApiField("item_code") private String itemCode; /** * 口碑门店id */ @ApiField("kb_shop_id") private String kbShopId; /** * 参考价格 */ @ApiField("price") private String price; /** * 店铺商品的名称 */ @ApiField("title") private String title; public String getBrandCode() { return this.brandCode; } public void setBrandCode(String brandCode) { this.brandCode = brandCode; } public String getCategoryCode() { return this.categoryCode; } public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getItemCode() { return this.itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getKbShopId() { return this.kbShopId; } public void setKbShopId(String kbShopId) { this.kbShopId = kbShopId; } public String getPrice() { return this.price; } public void setPrice(String price) { this.price = price; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } }
dde18b7cad888a3c9cadba312984b57ed8ac8a4d
6ce3fd145b558e323c1ccfe00b87878b92b7c22a
/src/com/crazy/java006/polymorphism/inter/Circle.java
60d014c0a4ac5b3827a3be0c5833a5122fbe126c
[]
no_license
liuxinjie123/crazy_java
e74ec974493089b859c2979da34a6ad346f2aaf6
d66c63bdae02b88a50da41ce3ea20e10dc1eae81
refs/heads/master
2022-11-21T18:10:40.783775
2020-08-02T14:19:27
2020-08-02T14:19:27
268,749,973
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package com.crazy.java006.polymorphism.inter; public class Circle implements Shape { @Override public void erase() { System.out.println("erase a circle."); } @Override public void drew() { System.out.println("draw a circle."); } }
b7f60cce241852dc09c39ea35508951ccdf805bb
4a6cc69db16aec71b8ac69abbe86ef427a71353e
/ebx/src/main/java/com/metservice/krypton/KryptonBitmap2Builder.java
613e5675a487ccb00d2783f138c3638f5b15f094
[]
no_license
craig-a-roach/geowx
0532c1d4dbea383ad229200b208aaebbdbbe2b5d
7cd7e2b7254f4a6b38762f4965dacb290f47bad1
refs/heads/master
2021-03-12T22:04:17.573558
2014-04-28T06:39:09
2014-04-28T06:39:09
9,379,471
0
1
null
null
null
null
UTF-8
Java
false
false
1,396
java
/* * Copyright 2014 Meteorological Service of New Zealand Limited all rights reserved. No part of this work may be stored * in a retrievable system, transmitted or reproduced in any way without the prior written permission of the * Meteorological Service of New Zealand */ package com.metservice.krypton; /** * @author roach */ public class KryptonBitmap2Builder extends KryptonSection2Builder { @Override void save(Section2Buffer dst) { dst.u1(m_indicator); if (m_oEmitter != null) { m_oEmitter.saveBitmap(dst); } } @Override public int estimatedOctetCount() { final int bmc = m_oEmitter == null ? 0 : m_oEmitter.bitmapByteCount(); return 6 + bmc; } @Override public int sectionNo() { return 6; } public KryptonBitmap2Builder(IBitmap2Emitter oEmitter) { if (oEmitter == null || !oEmitter.requiresBitmap()) { m_indicator = Table6_0.DoesNotApply; m_oEmitter = null; } else { m_indicator = Table6_0.Supplied; m_oEmitter = oEmitter; } } public KryptonBitmap2Builder(int indicator) { m_indicator = indicator; m_oEmitter = null; } private final int m_indicator; private final IBitmap2Emitter m_oEmitter; public static class Table6_0 { public static final int Supplied = 0; public static final int PreviouslyDefined = 254; public static final int DoesNotApply = 255; } }
6492dae184d8540d8c6aa6f163f1aba94a7cc32b
25deabf0889e8550a0c6216c3fcd86b4cedca863
/app/src/main/java/com/earaujo/usinglivedata/rest/model/Preview.java
94fab5548416bfc00090912c3cb490d02a8a29ca
[]
no_license
esanchos/UsingLiveData
5a293a019755759152d8400d921691adc13b13fb
ccdd0617d372f656a23e094c9093d02133145eab
refs/heads/master
2020-04-05T15:25:53.635655
2018-11-12T12:23:04
2018-11-12T12:23:04
156,967,516
1
0
null
null
null
null
UTF-8
Java
false
false
647
java
package com.earaujo.usinglivedata.rest.model; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Preview { @SerializedName("images") @Expose private List<Image> images = null; @SerializedName("enabled") @Expose private boolean enabled; public List<Image> getImages() { return images; } public void setImages(List<Image> images) { this.images = images; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
fa531970fa5ae0bfbb43601742fdb9b6b710e8d4
3ce15dc0af4cf0cd62977fc93c8ac158e17a9526
/src/soundsystem/SoundSystem.java
df5f1ac7cae6573460935d1f1f5437b2652f8e85
[]
no_license
MosesEjim/SoundStreaming
934bb973b7a29d76bc45e6a2c0636b10b5b186f1
d32766788471b03c8bdd80fb14d9d251d85458cd
refs/heads/master
2020-04-17T17:32:40.425930
2019-02-08T09:28:53
2019-02-08T09:28:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
699
java
package soundsystem; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class SoundSystem extends Application { public static Stage window; @Override public void start(Stage stage) throws Exception { window = stage; Parent root = FXMLLoader.load(getClass().getResource("home.fxml")); Scene scene = new Scene(root); window.setScene(scene); window.show(); } public static void main(String[] args) { launch(args); } }
[ "CS LAB [email protected]" ]
ab9ce1abf9e59e9915110d4d50b6e88f627d4366
91824d746654fe12881b4fc3b55c553aae0d22ac
/java/leetcode/restore_ip_addresses/Solution.java
9aaff7bca6a22c9e7ab081a37758080970c24c9f
[ "Apache-2.0" ]
permissive
ckclark/leetcode
a1a173c67a36a3256b198f853fcd3d15aa5abbb7
844c6f18d06dcb397db76436e5f4b8ddcb1beddc
refs/heads/master
2021-01-15T08:14:43.368516
2020-02-14T07:25:05
2020-02-14T07:30:10
42,386,911
0
0
null
null
null
null
UTF-8
Java
false
false
1,357
java
package leetcode.restore_ip_addresses; import java.util.ArrayList; public class Solution { public static final int IP_BYTES = 4; public void dfs(ArrayList<String> ans, char[] input, int offset, int length, int[] ipaddr, int depth){ if(offset == length && depth == IP_BYTES){ ans.add(ipaddr[0] + "." + ipaddr[1] + "." + ipaddr[2] + "." + ipaddr[3]); }else if(offset < length && depth < IP_BYTES){ ipaddr[depth] = input[offset] - '0'; dfs(ans, input, offset + 1, length, ipaddr, depth + 1); if(offset + 2 <= length){ int d = (input[offset] - '0') * 10 + (input[offset + 1] - '0'); if(d >= 10){ ipaddr[depth] = d; dfs(ans, input, offset + 2, length, ipaddr, depth + 1); } } if(offset + 3 <= length){ int d = (input[offset] - '0') * 100 + (input[offset + 1] - '0') * 10 + (input[offset + 2] - '0'); if(d >= 100 && d < 256){ ipaddr[depth] = d; dfs(ans, input, offset + 3, length, ipaddr, depth + 1); } } } } public ArrayList<String> restoreIpAddresses(String s) { ArrayList<String> ans = new ArrayList<String>(); dfs(ans, s.toCharArray(), 0, s.length(), new int[4], 0); return ans; } public static void main(String[] args){ ArrayList<String> ans = new Solution().restoreIpAddresses("999101"); for(String s : ans){ System.err.println(s); } } }
347d3d26413fdf08ce8d45ac0b2773dae9f24e07
ac55749807c464adf80ad92255c5bd5f3cb5104d
/holaspringhibernate/src/main/java/net/rodor/holaspringhibernate/test/TestTipoPermiso.java
8fef74d9cacfb91601242ea740201c5d3d3099c3
[]
no_license
jrodorgit/holaspringhibernate
f10c28c7c946ffae7e5be4b8c097f1adc21e2b95
f8398fa7d38a2471ad7e52044057c72a7717056f
refs/heads/master
2020-04-23T01:57:50.701446
2019-03-12T10:54:37
2019-03-12T10:54:37
170,830,130
0
0
null
null
null
null
UTF-8
Java
false
false
1,318
java
package net.rodor.holaspringhibernate.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import net.rodor.holaspringhibernate.dao.services.OIXXXService; import net.rodor.holaspringhibernate.entity.TipoPermiso; public class TestTipoPermiso { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "net/rodor/holaspringhibernate/test/config.xml"); // servicio que utiliza jdbcTempate para extraer resultado a traves de un sql standar. OIXXXService service = (OIXXXService) context.getBean("OIXXXService"); List<TipoPermiso> permisos = service.permisosRol(3); System.out.println(permisos); // servicio que utiliza hibernateTemplate para crear una entidad y actualizar otra // la transaccionalidad reside en el servicio no en el dao. TipoPermiso permiso = new TipoPermiso(); permiso.setNombre("macarrones999"); permiso.setDescripcion("con tomate999"); TipoPermiso permisoUpdate = new TipoPermiso(); permisoUpdate.setId(15); permisoUpdate.setNombre("macarronesyyy"); permisoUpdate.setDescripcion("con tomateyyy"); service.doService(permiso, permisoUpdate); } }
5f6d00553c2a50a800fd1eb3c1c3551597360117
6a26b6b5d79d9929c063c234e6fac5851aa75357
/app/src/androidTest/java/com/android/guidepage/ExampleInstrumentedTest.java
b065497cae28078fe738a05c2f19c8ea37fac659
[ "Apache-2.0" ]
permissive
sure13/GuidePage
346d4b824a03d2d71a173a6997c421f6c0de9705
cf32b8e698e15375da351cd39aa83ab52d32d4eb
refs/heads/master
2021-07-03T06:04:22.158332
2021-03-01T07:43:39
2021-03-01T07:43:39
225,838,132
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
package com.android.guidepage; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.android.guidepage", appContext.getPackageName()); } }
b1e87749013b15052323166febe8df61ac5ac976
9f29054f738f8a454ab500f975174464c6759aad
/src/checkInf.java
25eb212b6c016a6838fb3830b8cb0981671c3f1c
[]
no_license
qingsheng2016/Monopoly
195bd6dc728419d58d13b78484fee023dda3ce41
5511b42a0d0642e1d3f0c222bbc6493c276ef5dd
refs/heads/master
2021-01-09T06:15:14.694326
2016-06-07T09:28:45
2016-06-07T09:28:45
60,534,737
0
0
null
null
null
null
UTF-8
Java
false
false
2,044
java
import java.util.Scanner; /** * Created by dell on 2016/4/26. */ public class checkInf { public void check(Person person,Map map){ Scanner scanner = new Scanner(System.in); System.out.println("请输入您想查询的点与您相差的步数(后方用负数)"); int number = scanner.nextInt(); int temp=number+person.step; int result; if(temp>=0){ result=temp%51;} else{ result=temp+51; } int size = map.cells.size(); for(int i=0;i<size;i++){ if(map.cells.get(i).step==result){ if(map.cells.get(i).type.equals("房产")){ Land land= (Land) map.cells.get(i).events.get(0); String inf="<可供出售状态>"; if(land.owner!=null){ inf=land.owner.information; } System.out.print("类型:房产\n"+"名称:"+map.cells.get(i).events.get(0).information+"\n"+"初始价格:2000元\n"+"当前等级:"+land.level+"\n"+"拥有者:"+inf+"\n"); }else if(map.cells.get(i).type.equals("银行")){ System.out.print("类型:银行\n"); }else if(map.cells.get(i).type.equals("空地")){ System.out.print("类型:空地\n"); }else if(map.cells.get(i).type.equals("道具店")){ System.out.print("类型:道具店\n"); }else if(map.cells.get(i).type.equals("彩票站")){ System.out.print("类型:彩票站\n"); }else if(map.cells.get(i).type.equals("新闻")){ System.out.print("类型:新闻\n"); }else if(map.cells.get(i).type.equals("点券")){ System.out.print("类型:点券\n"); }else if(map.cells.get(i).type.equals("卡片")){ System.out.print("类型:卡片\n"); } } } } }
1e1f3b771ba1a77d728dfdb65d7b1ddfc0b4569d
b99c3c1b295ee60d025220bc5f4f01ee1ba8c732
/app/src/test/java/cn/jr1/msghook/ExampleUnitTest.java
68d592c2bc47a11fec294b765e68fbf631a793bd
[]
no_license
Sawyer-zh/msghook
031441134dc88179e814790e9b4db85401b1202c
dfcdc5cd7edd24af37e33cf9486e6d2b2ed11c56
refs/heads/master
2020-04-09T07:03:43.356299
2018-12-29T16:20:39
2018-12-29T16:20:39
160,138,868
1
0
null
null
null
null
UTF-8
Java
false
false
408
java
package cn.jr1.msghook; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
a761334c3c21954f5b015305eebf1dcf941e7841
a6572d3b5070407481419962c20fa2a0316a38b8
/day_05/practice_memberManagement/app/src/main/java/com/tje/practice_membermanagement/MemberRecyclerViewAdapter.java
c52193c10f872bbe87ad173e22d6353e9cd9bebe
[]
no_license
shsewonitw/study_android
4e19a30022012e61ba0a8d26a2e631676915c136
f53ef709de7e1a27dc5b4e1b1f26db0c5abf78c6
refs/heads/master
2020-07-04T15:29:19.833671
2019-08-21T08:05:09
2019-08-21T08:05:09
202,324,838
0
0
null
null
null
null
UTF-8
Java
false
false
1,657
java
package com.tje.practice_membermanagement; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class MemberRecyclerViewAdapter extends RecyclerView.Adapter<MemberRecyclerViewAdapter.ViewHolder> { public static class ViewHolder extends RecyclerView.ViewHolder{ public TextView name; public TextView age; public TextView phone; public TextView address; public TextView registDate; public ViewHolder(@NonNull View view) { super(view); name = view.findViewById(R.id.tv_recycle_name); age = view.findViewById(R.id.tv_recycle_age); phone = view.findViewById(R.id.tv_recycle_phone); address = view.findViewById(R.id.tv_recycle_address); registDate = view.findViewById(R.id.tv_recycle_registDate); } } @NonNull @Override public MemberRecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.item_member,parent,false); View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_member,parent,false); ViewHolder vh =new ViewHolder(v); return vh; } @Override public void onBindViewHolder(@NonNull MemberRecyclerViewAdapter.ViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
21bc29f765e77d450add40dc2befaf80c031fe07
fc63affc8750dc3d2e22840f4dbc4606094769ff
/src/sample/ZooShopPet/MainZoo.java
1be83c8db8be41a46b900427efd8a8c2ab6002bc
[]
no_license
evoskoboeva/FX_Practice_25032021_ZooShopPet
354370a52dc0f449dd637d20bffcf8504e84b7a8
d6c1e3dab8bda86b659df0f9adf4f69a76000fad
refs/heads/master
2023-03-26T09:23:21.541744
2021-03-26T23:16:52
2021-03-26T23:16:52
351,640,103
0
0
null
null
null
null
UTF-8
Java
false
false
710
java
package sample.ZooShopPet; import java.time.LocalDate; public class MainZoo { public static void main(String[] args) { Cat cat = new Cat("Kot", LocalDate.of(2011,02,15),100, LocalDate.of(2021, 03, 12), "long","www"); System.out.println(cat); Dog dog = new Dog(200,LocalDate.of(2015, 05, 05), "Pes", LocalDate.of(2021, 03, 13),"www2",70); System.out.println(dog); /*ArrayList<ZooShopPet> animals =new ArrayList<>(); animals.add(cat); animals.add(dog); */ ZooShop zooShop = new ZooShop(); zooShop.addAnimal(cat); zooShop.addAnimal(dog); System.out.println(zooShop); } }
[ "GITHUB [email protected]" ]
aae6f28653bf31ce1881313845d0283cce09e721
50b1ebb57dac9221915d563eae372a3337ae2ad0
/src/main/java/pugz/omni/client/render/OmniChestTileEntityRenderer.java
54209ec9cab3080b18d64e03572f80e3a38a8f38
[ "MIT" ]
permissive
wchen1990/Omni
52f1c41b0c942a504219e8e312e61066d8b1fdc5
4d40caa1e9a9f5fa377ad43858dcc9feca32b13f
refs/heads/main
2023-02-08T20:56:58.965316
2021-01-04T04:44:08
2021-01-04T04:44:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,064
java
package pugz.omni.client.render; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import it.unimi.dsi.fastutil.floats.Float2FloatFunction; import it.unimi.dsi.fastutil.ints.Int2IntFunction; import net.minecraft.block.*; import net.minecraft.client.renderer.Atlases; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.client.renderer.model.RenderMaterial; import net.minecraft.client.renderer.tileentity.DualBrightnessCallback; import net.minecraft.client.renderer.tileentity.TileEntityRenderer; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.state.properties.ChestType; import net.minecraft.tileentity.ChestTileEntity; import net.minecraft.tileentity.IChestLid; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityMerger; import net.minecraft.util.Direction; import net.minecraft.util.math.vector.Vector3f; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import java.util.Calendar; @OnlyIn(Dist.CLIENT) public class OmniChestTileEntityRenderer<T extends TileEntity & IChestLid> extends TileEntityRenderer<T> { private final ModelRenderer singleLid; private final ModelRenderer singleBottom; private final ModelRenderer singleLatch; private final ModelRenderer rightLid; private final ModelRenderer rightBottom; private final ModelRenderer rightLatch; private final ModelRenderer leftLid; private final ModelRenderer leftBottom; private final ModelRenderer leftLatch; private boolean isChristmas; public OmniChestTileEntityRenderer(TileEntityRendererDispatcher rendererDispatcherIn) { super(rendererDispatcherIn); Calendar calendar = Calendar.getInstance(); if (calendar.get(2) + 1 == 12 && calendar.get(5) >= 24 && calendar.get(5) <= 26) { this.isChristmas = true; } this.singleBottom = new ModelRenderer(64, 64, 0, 19); this.singleBottom.addBox(1.0F, 0.0F, 1.0F, 14.0F, 10.0F, 14.0F, 0.0F); this.singleLid = new ModelRenderer(64, 64, 0, 0); this.singleLid.addBox(1.0F, 0.0F, 0.0F, 14.0F, 5.0F, 14.0F, 0.0F); this.singleLid.rotationPointY = 9.0F; this.singleLid.rotationPointZ = 1.0F; this.singleLatch = new ModelRenderer(64, 64, 0, 0); this.singleLatch.addBox(7.0F, -1.0F, 15.0F, 2.0F, 4.0F, 1.0F, 0.0F); this.singleLatch.rotationPointY = 8.0F; this.rightBottom = new ModelRenderer(64, 64, 0, 19); this.rightBottom.addBox(1.0F, 0.0F, 1.0F, 15.0F, 10.0F, 14.0F, 0.0F); this.rightLid = new ModelRenderer(64, 64, 0, 0); this.rightLid.addBox(1.0F, 0.0F, 0.0F, 15.0F, 5.0F, 14.0F, 0.0F); this.rightLid.rotationPointY = 9.0F; this.rightLid.rotationPointZ = 1.0F; this.rightLatch = new ModelRenderer(64, 64, 0, 0); this.rightLatch.addBox(15.0F, -1.0F, 15.0F, 1.0F, 4.0F, 1.0F, 0.0F); this.rightLatch.rotationPointY = 8.0F; this.leftBottom = new ModelRenderer(64, 64, 0, 19); this.leftBottom.addBox(0.0F, 0.0F, 1.0F, 15.0F, 10.0F, 14.0F, 0.0F); this.leftLid = new ModelRenderer(64, 64, 0, 0); this.leftLid.addBox(0.0F, 0.0F, 0.0F, 15.0F, 5.0F, 14.0F, 0.0F); this.leftLid.rotationPointY = 9.0F; this.leftLid.rotationPointZ = 1.0F; this.leftLatch = new ModelRenderer(64, 64, 0, 0); this.leftLatch.addBox(0.0F, -1.0F, 15.0F, 1.0F, 4.0F, 1.0F, 0.0F); this.leftLatch.rotationPointY = 8.0F; } public void render(T tileEntityIn, float partialTicks, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int combinedLightIn, int combinedOverlayIn) { World world = tileEntityIn.getWorld(); boolean flag = world != null; BlockState blockstate = flag ? tileEntityIn.getBlockState() : Blocks.CHEST.getDefaultState().with(ChestBlock.FACING, Direction.SOUTH); ChestType chesttype = blockstate.hasProperty(ChestBlock.TYPE) ? blockstate.get(ChestBlock.TYPE) : ChestType.SINGLE; Block block = blockstate.getBlock(); if (block instanceof AbstractChestBlock) { AbstractChestBlock<?> abstractchestblock = (AbstractChestBlock)block; boolean flag1 = chesttype != ChestType.SINGLE; matrixStackIn.push(); float f = blockstate.get(ChestBlock.FACING).getHorizontalAngle(); matrixStackIn.translate(0.5D, 0.5D, 0.5D); matrixStackIn.rotate(Vector3f.YP.rotationDegrees(-f)); matrixStackIn.translate(-0.5D, -0.5D, -0.5D); TileEntityMerger.ICallbackWrapper<? extends ChestTileEntity> icallbackwrapper; if (flag) { icallbackwrapper = abstractchestblock.combine(blockstate, world, tileEntityIn.getPos(), true); } else { icallbackwrapper = TileEntityMerger.ICallback::func_225537_b_; } float f1 = icallbackwrapper.<Float2FloatFunction>apply(ChestBlock.getLidRotationCallback(tileEntityIn)).get(partialTicks); f1 = 1.0F - f1; f1 = 1.0F - f1 * f1 * f1; int i = icallbackwrapper.<Int2IntFunction>apply(new DualBrightnessCallback<>()).applyAsInt(combinedLightIn); RenderMaterial rendermaterial = this.getMaterial(tileEntityIn, chesttype); IVertexBuilder ivertexbuilder = rendermaterial.getBuffer(bufferIn, RenderType::getEntityCutout); if (flag1) { if (chesttype == ChestType.LEFT) { this.renderModels(matrixStackIn, ivertexbuilder, this.leftLid, this.leftLatch, this.leftBottom, f1, i, combinedOverlayIn); } else { this.renderModels(matrixStackIn, ivertexbuilder, this.rightLid, this.rightLatch, this.rightBottom, f1, i, combinedOverlayIn); } } else { this.renderModels(matrixStackIn, ivertexbuilder, this.singleLid, this.singleLatch, this.singleBottom, f1, i, combinedOverlayIn); } matrixStackIn.pop(); } } private void renderModels(MatrixStack matrixStackIn, IVertexBuilder bufferIn, ModelRenderer chestLid, ModelRenderer chestLatch, ModelRenderer chestBottom, float lidAngle, int combinedLightIn, int combinedOverlayIn) { chestLid.rotateAngleX = -(lidAngle * ((float)Math.PI / 2F)); chestLatch.rotateAngleX = chestLid.rotateAngleX; chestLid.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); chestLatch.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); chestBottom.render(matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); } protected RenderMaterial getMaterial(T tileEntity, ChestType chestType) { return Atlases.getChestMaterial(tileEntity, chestType, this.isChristmas); } }
133156855fe967db6f8eb2b5d324c2bba4cf0a08
acb5bc351d52b218b70773238617f912e84a61eb
/tika-ner-grobid/src/test/java/org/apache/tika/parser/ner/grobid/GrobidNERecogniserTest.java
0982ef58f4e675509811d0b383b96722dfba5f55
[]
no_license
sandeepkulkarni/Evaluating-Polar-Dynamic-DataSet
bc343833982cc867dbe912c75d53acd4d96fbeae
ae3a496089d46ce4de3f6c74671b999ae905f47a
refs/heads/master
2021-01-18T02:24:19.201676
2016-05-08T03:59:12
2016-05-08T03:59:12
55,752,908
0
0
null
null
null
null
UTF-8
Java
false
false
2,600
java
/* * 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 owlocationNameEntitieship. * 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.tika.parser.ner.grobid; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashSet; import org.apache.tika.Tika; import org.apache.tika.config.TikaConfig; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ner.NamedEntityParser; import org.junit.Test; import org.apache.tika.language.LanguageIdentifier; /** *Test case for {@link Grobid NER} */ public class GrobidNERecogniserTest { @Test public void testGetEntityTypes() throws Exception { String text = "I've lost one minute."; System.setProperty(NamedEntityParser.SYS_PROP_NER_IMPL, GrobidNERecogniser.class.getName()); Tika tika = new Tika(new TikaConfig(NamedEntityParser.class.getResourceAsStream("tika-config.xml"))); Metadata md = new Metadata(); tika.parse(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), md); HashSet<String> set = new HashSet<String>(); LanguageIdentifier identifier = new LanguageIdentifier(text); System.out.println(identifier.getLanguage()); set.clear(); set.addAll(Arrays.asList(md.getValues("NER_MEASUREMENT_NUMBERS"))); assertTrue(set.contains("one")); set.clear(); set.addAll(Arrays.asList(md.getValues("NER_MEASUREMENT_UNITS"))); assertTrue(set.contains("minute")); set.clear(); set.addAll(Arrays.asList(md.getValues("NER_MEASUREMENTS"))); assertTrue(set.contains("one minute")); set.clear(); set.addAll(Arrays.asList(md.getValues("NER_NORMALIZED_MEASUREMENTS"))); assertTrue(set.contains("60 s")); } }
ae0ab6a2d05a7fe0edf1f443e480773101c83491
0cf473af136e6cbb6436e089088c99c2d36da0f2
/app/src/main/java/c/example/mainscreen/MainActivity.java
b87070e1434fb88a8366f451406dfe5b18b82cd6
[]
no_license
HewMunHon/mainscreen
0174ad02f7f23bad3a80867d0417a89544c2dfe0
60ac6798dc666de2082ba7752454f59e35882aca
refs/heads/master
2022-12-11T02:07:51.893126
2020-09-13T09:44:21
2020-09-13T09:44:21
293,209,106
0
0
null
null
null
null
UTF-8
Java
false
false
1,392
java
package c.example.mainscreen; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button =(Button) findViewById(R.id.LoginBtn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openlogin(); } }); button = (Button) findViewById(R.id.RegisterBtn); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { openregister(); } }); } public void openlogin(){ Intent intent = new Intent(this, login.class); startActivity(intent); } public void openregister(){ Intent intent = new Intent(this, register.class); startActivity(intent); } }
1306b16743755c86238d8246623c401513a0c1c9
88b87e60afb4878d742dd10d00f22dac8e0013c2
/src/main/java/com/dunya/stakechannel/accounts/model/TotalBill.java
93e9c028cd87966ae9936971f122fb65af96b68d
[]
no_license
pranaysahota/mongodb-api-account-service
092a4d3ede86105ff693aa0e9d7ed9861c1b311c
c2f9893f3f679fc9e0776901b3aeba40d64968d0
refs/heads/master
2020-04-01T01:21:03.808004
2018-10-12T10:32:38
2018-10-12T10:32:38
152,734,736
0
0
null
null
null
null
UTF-8
Java
false
false
1,960
java
package com.dunya.stakechannel.accounts.model; import java.math.BigDecimal; import java.util.List; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; public class TotalBill { @JsonProperty("account_name") private String accountName; @JsonProperty("total_cpu_bill") @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) private BigDecimal totalCpuBill; @JsonProperty("total_net_bill") @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT) private BigDecimal totalNetBill; @JsonProperty("time_period") private TimePeriod timePeriod; @JsonProperty("transactions") private List<Transactions> transactions; public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public BigDecimal getTotalCpuBill() { return totalCpuBill; } public void setTotalCpuBill(BigDecimal totalCpuBill) { this.totalCpuBill = totalCpuBill; } public BigDecimal getTotalNetBill() { return totalNetBill; } public void setTotalNetBill(BigDecimal totalNetBill) { this.totalNetBill = totalNetBill; } public TimePeriod getTimePeriod() { return timePeriod; } public void setTimePeriod(TimePeriod timePeriod) { this.timePeriod = timePeriod; } public List<Transactions> getTransactions() { return transactions; } public void setTransactions(List<Transactions> transactions) { this.transactions = transactions; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("TotalBill [accountName="); builder.append(accountName); builder.append(", totalCpuBill="); builder.append(totalCpuBill); builder.append(", totalNetBill="); builder.append(totalNetBill); builder.append(", timePeriod="); builder.append(timePeriod); builder.append(", transactions="); builder.append(transactions); builder.append("]"); return builder.toString(); } }
deb6f370daff383dbb8e95005d02f6e4005cab2c
e1e5bd6b116e71a60040ec1e1642289217d527b0
/H5/L2_Scripts_com/L2_Scripts_Revision_20720_2268/src/l2s/gameserver/model/entity/events/actions/IfElseAction.java
c7a19e6951b682db4d56dc724c2d8fe3a556459b
[]
no_license
serk123/L2jOpenSource
6d6e1988a421763a9467bba0e4ac1fe3796b34b3
603e784e5f58f7fd07b01f6282218e8492f7090b
refs/heads/master
2023-03-18T01:51:23.867273
2020-04-23T10:44:41
2020-04-23T10:44:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
958
java
package l2s.gameserver.model.entity.events.actions; import java.util.Collections; import java.util.List; import l2s.gameserver.model.entity.events.EventAction; import l2s.gameserver.model.entity.events.Event; /** * @author VISTALL * @date 8:38/05.03.2011 */ public class IfElseAction implements EventAction { private String _name; private boolean _reverse; private List<EventAction> _ifList = Collections.emptyList(); private List<EventAction> _elseList = Collections.emptyList(); public IfElseAction(String name, boolean reverse) { _name = name; _reverse = reverse; } @Override public void call(Event event) { List<EventAction> list = (_reverse ? !event.ifVar(_name) : event.ifVar(_name)) ? _ifList : _elseList; for(EventAction action : list) action.call(event); } public void setIfList(List<EventAction> ifList) { _ifList = ifList; } public void setElseList(List<EventAction> elseList) { _elseList = elseList; } }
8ff33007b5d73cee3819e2a39f384657007f556f
3296534591d3613d10275d481294e27ab9eb9cad
/JavaClassContents/src/week2/day5/ThreadTest.java
aa81e92513194acd78719c9ce14a5b5dce413f8a
[]
no_license
rycbr124/practice
d8729cfd5d07b38dbd28ca68578d3bddcdddc978
e0df0ad1a564da93e3ff12596fe4d1a4ac3464d9
refs/heads/master
2022-12-20T13:38:33.313113
2020-02-02T05:47:08
2020-02-02T05:47:08
237,722,459
0
0
null
2022-12-16T01:02:18
2020-02-02T05:17:30
Java
UTF-8
Java
false
false
842
java
//package week2.day5; // //class ThreadB extends Thread{ // int total; // // public void run() { // synchronized(this){ // for(int i=0;i<5;i++) { // System.out.println(i+"를 더합니다."); // total+=i; // try { // Thread.sleep(500); // }catch (InterruptedException en) { // en.printStackTrace(); // } // } // notify(); // } // } //} // //public class ThreadTest { // // public static void main(String[] args) { // Thread b = new Thread(); // int total; // // b.start(); // synchronized(this){ // for(int i=0;i<5;i++) { // System.out.println(i+"를 더합니다."); // total+=i; // try { // Thread.sleep(500);//0.5초 // }catch (InterruptedException en) { // en.printStackTrace(); // } // } // notify(); // } // // } // //}
739969fa94dbf9189f355538726afb8dd3a0ee1f
ab54e9d298c15a2bf4767c02e590c13184808786
/src/cz/tul/cc/db/DBSort.java
58a8966e73f4b7e23248f5cb781915bf30332268
[]
no_license
vojtaw/krivky_clanek
e3f80cc28dd89f85acc2b96d2bd1097dd0c696bb
ca9ed1837d40cce505856643df4cfdc9644dfd2b
refs/heads/master
2021-01-15T10:50:49.867823
2016-01-18T13:03:00
2016-01-18T13:03:00
27,908,780
0
0
null
null
null
null
UTF-8
Java
false
false
1,356
java
package cz.tul.cc.db; import java.util.LinkedHashMap; import java.util.Map; /** * * @author ikopetschke */ public class DBSort { /** * vnintrni trida reprezentujici jednu polozku sortu */ public class Sort { private DBFieldsEnum field; private SortTypeEnum sortType; private Sort(DBFieldsEnum field, SortTypeEnum sortType) { this.field = field; this.sortType = sortType; } public DBFieldsEnum getField() { return field; } public void setField(DBFieldsEnum field) { this.field = field; } public SortTypeEnum getSortType() { return sortType; } public void setSortType(SortTypeEnum sortType) { this.sortType = sortType; } } private Map<DBFieldsEnum, Sort> sorts; public DBSort() { sorts = new LinkedHashMap<>(); } public Map<DBFieldsEnum, Sort> getSorts() { return this.sorts; } public Sort getSort(DBFieldsEnum field) { return this.sorts.get(field); } public void addSort(DBFieldsEnum field, SortTypeEnum sortType) { addSort( new Sort(field, sortType)); } public void addSort(Sort sort) { this.sorts.put(sort.getField(), sort); } }
5915d10d352bd755433c56add60ad9d007c06d09
55198905555db7de06a5ed6e743b9087560ee82e
/PlayerLib/VideoSurface/src/main/java/com/yc/videosurface/MeasureHelper.java
1f90c8853f538f6e452c56c85aa48f4420f52464
[ "Apache-2.0" ]
permissive
Mario0o/LifeHelper
c68ebe76e50283403587558dfdfdddd418667943
83c22ffbd61186aa86d29a325755e5f796d1e117
refs/heads/master
2023-08-17T05:49:25.116555
2023-08-14T23:51:17
2023-08-14T23:51:17
190,854,495
0
0
null
2023-08-15T08:02:23
2019-06-08T06:37:35
Java
UTF-8
Java
false
false
5,573
java
/* Copyright 2017 yangchong211(github.com/yangchong211) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.yc.videosurface; import android.view.View; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * <pre> * @author yangchong * blog : https://github.com/yangchong211 * time : 2018/9/21 * desc : 帮助类 * revise: * </pre> */ public final class MeasureHelper { @IntDef({PlayerScreenScaleType.SCREEN_SCALE_DEFAULT,PlayerScreenScaleType.SCREEN_SCALE_16_9, PlayerScreenScaleType.SCREEN_SCALE_4_3,PlayerScreenScaleType.SCREEN_SCALE_MATCH_PARENT, PlayerScreenScaleType.SCREEN_SCALE_ORIGINAL,PlayerScreenScaleType.SCREEN_SCALE_CENTER_CROP}) @Retention(RetentionPolicy.SOURCE) public @interface ScreenScaleType{} /** * 播放视频缩放类型 */ @Retention(RetentionPolicy.SOURCE) public @interface PlayerScreenScaleType { /** * 默认类型 */ int SCREEN_SCALE_DEFAULT = 0; /** * 16:9比例类型,最为常见 */ int SCREEN_SCALE_16_9 = 1; /** * 4:3比例类型,也比较常见 */ int SCREEN_SCALE_4_3 = 2; /** * 充满整个控件视图 */ int SCREEN_SCALE_MATCH_PARENT = 3; /** * 原始类型,指视频的原始类型 */ int SCREEN_SCALE_ORIGINAL = 4; /** * 剧中裁剪类型 */ int SCREEN_SCALE_CENTER_CROP = 5; } private int mVideoWidth; private int mVideoHeight; private int mCurrentScreenScale; private int mVideoRotationDegree; /** * 设置视频旋转角度 * @param videoRotationDegree 角度值 */ public void setVideoRotation(int videoRotationDegree) { mVideoRotationDegree = videoRotationDegree; } /** * 设置视频宽高 * @param width 宽 * @param height 高 */ public void setVideoSize(int width, int height) { mVideoWidth = width; mVideoHeight = height; } public void setScreenScale(@ScreenScaleType int screenScale) { mCurrentScreenScale = screenScale; } /** * 注意:VideoView的宽高一定要定死,否者以下算法不成立 * 借鉴于网络 */ public int[] doMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mVideoRotationDegree == 90 || mVideoRotationDegree == 270) { // 软解码时处理旋转信息,交换宽高 widthMeasureSpec = widthMeasureSpec + heightMeasureSpec; heightMeasureSpec = widthMeasureSpec - heightMeasureSpec; widthMeasureSpec = widthMeasureSpec - heightMeasureSpec; } int width = View.MeasureSpec.getSize(widthMeasureSpec); int height = View.MeasureSpec.getSize(heightMeasureSpec); if (mVideoHeight == 0 || mVideoWidth == 0) { return new int[]{width, height}; } //如果设置了比例 switch (mCurrentScreenScale) { //默认正常类型 case PlayerScreenScaleType.SCREEN_SCALE_DEFAULT: default: if (mVideoWidth * height < width * mVideoHeight) { width = height * mVideoWidth / mVideoHeight; } else if (mVideoWidth * height > width * mVideoHeight) { height = width * mVideoHeight / mVideoWidth; } break; //原始类型,指视频的原始类型 case PlayerScreenScaleType.SCREEN_SCALE_ORIGINAL: width = mVideoWidth; height = mVideoHeight; break; //16:9比例类型,最为常见 case PlayerScreenScaleType.SCREEN_SCALE_16_9: if (height > width / 16 * 9) { height = width / 16 * 9; } else { width = height / 9 * 16; } break; //4:3比例类型,也比较常见 case PlayerScreenScaleType.SCREEN_SCALE_4_3: if (height > width / 4 * 3) { height = width / 4 * 3; } else { width = height / 3 * 4; } break; //充满整个控件视图 case PlayerScreenScaleType.SCREEN_SCALE_MATCH_PARENT: width = widthMeasureSpec; height = heightMeasureSpec; break; //剧中裁剪类型 case PlayerScreenScaleType.SCREEN_SCALE_CENTER_CROP: if (mVideoWidth * height > width * mVideoHeight) { width = height * mVideoWidth / mVideoHeight; } else { height = width * mVideoHeight / mVideoWidth; } break; } return new int[]{width, height}; } }
aa289f2f311759653bf521274589d375c90f8d90
4c5e190a9eb4925d5ef4be5f9e7f69f2bae8a9c0
/Utils/cleansdk/src/main/java/com/clean/spaceplus/cleansdk/boost/engine/data/IPhoneMemoryInfo.java
eccdd41a4f6c9fee61a1ef5539d39bee2b7b052e
[]
no_license
SteamedBunZL/AndroidUtils
5bb4346a373b0ef3deace4d7ad69e9deeca90ab2
31f9b630f5b67d8608a6b5bfc6caee4cd3c045ee
refs/heads/master
2020-09-18T05:34:36.300027
2018-06-05T06:24:57
2018-06-05T06:24:57
66,835,083
0
1
null
null
null
null
UTF-8
Java
false
false
1,118
java
package com.clean.spaceplus.cleansdk.boost.engine.data; import android.os.Parcelable; /** * @author zengtao.kuang * @Description: 手机内存信息接口 * @date 2016/4/6 14:27 * @copyright TCL-MIG */ public interface IPhoneMemoryInfo extends Parcelable { /** * 当前数据是真实内存值 * */ int STATE_REAL_DATA = 1; /** * 处于进程清理后的内存不增时间段内 * */ int STATE_CACHED_DATA = 2; int TIMEOUT_SHORT = 1000 * 20; int TIMEOUT_LONG = 1000 * 80; int DEFAULT_USED_MEMORY_PERCENT = 85; /** * 获取当前数据状态 * @return IPhoneMemoryInfo.STATE_REAL_DATA</br> * IPhoneMemoryInfo.STATE_CACHED_DATA * */ int getState(); /** * 获取可用内存,单位byte * */ long getAvailableMemoryByte(); /** * 获取总内存,单位byte * */ long getTotalMemoryByte(); /** * 获取内存已用内存占比 * */ int getUsedMemoryPercentage(); /** * 判断当前是否处于缓存期间内 * @return */ boolean isInCache(); }
7330e726a481081e2ef530dcfea4932a3b8b9402
c0436fd4484d0a87862950e204a94c233e0c086a
/src/lib/ui/factories/SearchPageObjectFactory.java
794a34933a9ce7f2ec4d34657e2b5849589f2ca5
[]
no_license
tankisleva/JavaAppiumAutomation
7ce538e659148c784b50cb4ccf1ba530776c4e4f
b09b3bbd4f8f433441138c4fedd5660f37527385
refs/heads/master
2020-05-09T18:45:20.626439
2019-06-08T09:51:29
2019-06-08T09:51:29
181,353,851
0
0
null
null
null
null
UTF-8
Java
false
false
696
java
package lib.ui.factories; import io.appium.java_client.AppiumDriver; import lib.Platform; import lib.ui.SearchPageObject; import lib.ui.android.AndroidSearhPageObject; import lib.ui.ios.IOSSearchPageObject; import lib.ui.mobile_web.MwSearchPageObject; import org.openqa.selenium.remote.RemoteWebDriver; public class SearchPageObjectFactory { public static SearchPageObject get(RemoteWebDriver driver){ if(Platform.getInstance().isAndroid()){ return new AndroidSearhPageObject(driver); } else if (Platform.getInstance().isIos()) { return new IOSSearchPageObject(driver); } else { return new MwSearchPageObject(driver); } } }
9b5b26ad4322d9330c9bbf6196403a0bcbc7cefb
bdb883715afbf8ea5675d08916a640ed1813707d
/ld-oai/src/main/java/pt/ist/oai/harvester/cmd/GetRecordCmd.java
6f9203e2f6b2cff4b43ee3c1caf80f12168dd3a1
[]
no_license
SrishtiSingh-eu/europeana_ld
a6cdb9bc9df082d27e80e3763a3acac05bc810b9
1da7b8b6be98483ea5eac8a0d3e89d54200510e8
refs/heads/master
2020-09-10T14:23:40.002285
2018-11-30T16:23:00
2018-11-30T16:23:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,611
java
package pt.ist.oai.harvester.cmd; import java.io.*; import java.util.*; import javax.xml.transform.stream.*; import org.apache.commons.cli.*; import pt.ist.oai.harvester.*; import pt.ist.oai.harvester.model.*; import pt.ist.oai.harvester.model.rw.*; import static pt.ist.oai.harvester.cmd.HarvesterConfigs.*; public class GetRecordCmd extends VerbCmd { @Override protected String getVerb() { return "GetRecord"; } @Override @SuppressWarnings("static-access") protected Options buildOptions() { Options options = new Options(); options.addOption(new Option("help", getProperty("info.Verbs.help"))); options.addOption(OptionBuilder.withArgName("host") .hasArg() .withDescription(getProperty("info.Verbs.host")) .isRequired() .create("host")); options.addOption(OptionBuilder.withArgName("identifier") .hasArg() .isRequired() .withDescription(getProperty("info.GetRecord.identifier")) .create("identifier")); options.addOption(OptionBuilder.withArgName("metadataPrefix") .hasArg() .isRequired() .withDescription(getProperty("info.GetRecord.metadataPrefix")) .create("metadataPrefix")); options.addOption(OptionBuilder.withArgName("file") .hasArg() .withDescription(getProperty("info.GetRecord.file")) .create("file")); options.addOption(OptionBuilder.withArgName("'record-only'|'both'") .hasArg() .withDescription(getProperty("info.GetRecord.detail")) .create("detail")); return options; } @Override protected void process(CommandLine line, PrintStream print) throws Throwable { Properties props = getProperties(line, "identifier", "metadataPrefix"); //Get Record long elapsed = System.currentTimeMillis(); OAIHarvester h = new OAIHarvesterImpl(line.getOptionValue("host")); OAIRecord record = h.getRecord(props); elapsed = System.currentTimeMillis() - elapsed; //Print result to output ModelPrinter printer = new ModelPrinter(); printer.print(record, print); if(line.hasOption("file")) { String path = line.getOptionValue("file"); File out = new File(path).getAbsoluteFile(); ensureDir(out.getParentFile()); String detail = line.getOptionValue("detail", "record-only") .toLowerCase(); if(detail.equals("both")) { new OAIWriter().write(record, h.identify() , new StreamResult(out)); } else if(record.hasMetadata()) { write(record.getMetadata(), out); } } else { //Show record in the screen String detail = line.getOptionValue("detail", "record-only"); if(detail.equals("both")) { new OAIWriter().write(record, h.identify() , new StreamResult(print)); } else { if(record.hasMetadata()) { printer.print(record.getMetadata(), print); } } } print.println(); print.println("Successfuly retrieved 1 record in " + elapsed + "ms"); } public static void main(String[] args) { new GetRecordCmd().process(args); } }
6709ad13f354f6f2d93727bd8fb7e28422ba6783
e4b922044dc46fda6508952246d1a217b25aee18
/mailer/src/main/java/gr/athenarc/n4160/mailer/mailEntities/CancelBudgetEmailEntity.java
837cf8988872bf16c7c8feb2bf42bce56bb1a564
[]
no_license
madgeek-arc/arc-expenses-n4160
35d6696d8ec1f15ba775bc064b380d0851598ca1
571bd0ced490e5bf1f287b9b47b06d3e79452940
refs/heads/master
2022-11-25T08:52:18.532242
2019-12-05T12:24:06
2019-12-05T12:24:06
190,744,543
0
0
null
2022-11-16T11:47:23
2019-06-07T13:04:18
Java
UTF-8
Java
false
false
1,160
java
package gr.athenarc.n4160.mailer.mailEntities; public class CancelBudgetEmailEntity { private String request_id; private String project_acronym; private String creation_date; private String url; public CancelBudgetEmailEntity(String request_id, String project_acronym, String creation_date, String url) { this.request_id = request_id; this.project_acronym = project_acronym; this.creation_date = creation_date; this.url = url; } public String getRequest_id() { return request_id; } public void setRequest_id(String request_id) { this.request_id = request_id; } public String getProject_acronym() { return project_acronym; } public void setProject_acronym(String project_acronym) { this.project_acronym = project_acronym; } public String getCreation_date() { return creation_date; } public void setCreation_date(String creation_date) { this.creation_date = creation_date; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
62af052b899690c4d88fa3c8fae1c45558a2a8e3
83ba85f9ff5af0e814f22259b5ad8547708a493e
/pmp-android/Webservices/InfoApp-CommunicationLib/src/de/unistuttgart/ipvs/pmp/infoapp/graphs/UrlBuilder.java
6bc3224fda4bbf2dea4ab05e0401f7e7e98bafab
[ "Apache-2.0" ]
permissive
pmp-android/pmp-android
bf66778eecc66b43452c5fdceddb69975d67ec17
34456120e8a8aa3b58e9dd6befb4ea2fd7e6fc53
refs/heads/master
2021-01-02T22:57:46.301284
2012-06-10T21:09:03
2012-06-10T21:09:03
32,090,593
0
0
null
null
null
null
UTF-8
Java
false
false
8,924
java
/* * Copyright 2012 pmp-android development team * Project: InfoApp-CommunicationLib * Project-Site: http://code.google.com/p/pmp-android/ * * --------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.unistuttgart.ipvs.pmp.infoapp.graphs; /** * This builder accepts different information about the charts/graphs and uses this information to create the URL to the * available chart-scripts * * @author Patrick Strobel */ public class UrlBuilder { public static String DEFAULT_URL = "https://infoapp.no-ip.org/graphs"; private String url; private int day = 0; private int month = 0; private int year = 0; public enum Scales { DAY, WEEK, MONTH, YEAR }; private Scales scale = Scales.DAY; private boolean showAnnotations = true; public enum Views { DYNAMIC, STATIC } private Views view = Views.DYNAMIC; private String deviceId; /** * Creates a new builder-instance used to create URLs to the available charts * * @param url * URL to where all scripts are located. * @param deviceId * 16-bit (32 characters) HEX-value used the uniquely identify the Android device */ public UrlBuilder(String url, String deviceId) { this.url = url; this.deviceId = deviceId; } /** * Sets the day in month for which the charts should be displayed. * This need only to be set if a day other than the current day should be used. * If not set or set to "0" the current day will be used.<br> * <b>Note: </b>If the year ({@link setYear()}) or month ({@link setMonth()}) is not set or set to 0, the script * will always use the current day * * @param day * A value between 0 and 31 */ public void setDay(int day) { if (day >= 1 && day <= 31) { this.day = day; } } /** * Sets the month for which the charts should be displayed. * This need only to be set if a month other than the current month should be used. * If not set or set to "0" the current month will be used.<br> * <b>Note: </b>If the year ({@link setYear()}) is not set or set to 0, the script will * always use the current month * * @param month * A value between 0 and 12 */ public void setMonth(int month) { if (month >= 1 && month <= 12) { this.month = month; } } /** * Sets the year for which the charts should be displayed. * This need only to be set if a year other than the current year should be used. * If not set or set to "0" the current year will be used * * @param year * A non-negative year */ public void setYear(int year) { if (year >= 0) { this.year = year; } } /** * Sets the scale that should be used for the charts displayed by the script. * If not set {@code Scales.DAY} will be used * * @param scale * Scale used for the charts */ public void setScale(Scales scale) { this.scale = scale; } /** * If set to true, annotations will be shown in the dynamic charts. * If not set, annotations will be visible * * @param show * True, when annotations should be shown */ public void setShowAnnotations(boolean show) { this.showAnnotations = show; } /** * Set the view-mode that will be used by the scripts. * If set to {@code Views.DYNAMIC}), interactive charts will be used. These charts require enabled Java-Script and a * SVG capable browser. As SVG-capabilities are only available in Android's default browser since version 3.0, this * should be set to {@code Views.static} when running on a device having an older Android version installed * * @param view * View mode used to render the charts */ public void setView(Views view) { this.view = view; } /** * Generates a string that contains all parameters that have been set to a non-default value and appends it to the * base URL * * @param scriptName * The script name that will inserted between the base URL and the parameters * @return String that can be used to be directly attached to the URL */ private String getParameterizedUrl(String scriptName) { StringBuilder url = new StringBuilder(this.url); url.append("/"); url.append(scriptName); url.append("?"); // Date if (this.year > 0) { url.append("year="); url.append(this.year); if (this.month > 0) { url.append("&month="); url.append(this.month); if (this.day > 0) { url.append("&day="); url.append(this.day); } } } // Scale if (this.scale != Scales.DAY) { url.append("&scale="); switch (this.scale) { case WEEK: url.append("week"); break; case MONTH: url.append("month"); break; case YEAR: url.append("year"); break; } } //Remaining parameters if (!this.showAnnotations) { url.append("&annotations=hide"); } if (this.view != Views.DYNAMIC) { url.append("&view=static"); } url.append("&device="); url.append(this.deviceId); return url.toString(); } /** * Gets the URL to the device specific battery graphs * * @return The URL */ public String getBatteryGraphUrl() { return getParameterizedUrl("battery.php"); } /** * Gets the URL to the device specific cellular connection graphs * * @return The URL */ public String getCellularConnectionGraphUrl() { return getParameterizedUrl("connectioncellular.php"); } /** * Gets the URL to the device specific near-field connection graphs * * @return The URL */ public String getConnectionGraphUrl() { return getParameterizedUrl("connection.php"); } /** * Gets the URL to the device specific activity and standby graphs * * @return The URL */ public String getStandbyGraphUrl() { return getParameterizedUrl("connection.php"); } /** * Gets the URL to the statistical battery graphs * * @return The URL */ public String getBatteryPropGraphUrl() { return getParameterizedUrl("battery_properties.php"); } /** * Gets the URL to the statistical connection graphs * * @return The URL */ public String getConnctionPropGraphUrl() { return getParameterizedUrl("connection_properties.php"); } /** * Gets the URL to the statistical hardware graphs * * @return The URL */ public String getHardwarePropGraphUrl() { return getParameterizedUrl("hardware_properties.php"); } /** * Gets the URL to the statistical profile graphs * * @return The URL */ public String getProfilePropGraphUrl() { return getParameterizedUrl("profile_properties.php"); } /** * Gets the URL to the statistical software graphs * * @return The URL */ public String getSoftwarePropGraphUrl() { return getParameterizedUrl("software_properties.php"); } }
d3ddc3458fed5c68df9c26a170dfbf80e6c2cda4
fea42c69863dbd85ab894e62310e91a013bd2277
/src/main/java/com/github/sinsinpub/doc/hint/SPI.java
191797a2579030ab0bd56d9b7c8aa8bc23cdba46
[ "Apache-2.0" ]
permissive
sinsinpub/doc-share
f8783ca2946b286a6b05270e2e3f22d8677a8822
ff65c6c626d53174fdb52edccc780be1af6218a3
refs/heads/master
2021-01-10T03:22:39.458888
2016-03-11T06:17:35
2016-03-11T06:17:35
43,936,461
2
1
null
null
null
null
UTF-8
Java
false
false
2,368
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package com.github.sinsinpub.doc.hint; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 一个目标被定义为SPI(Service Provider Interface,服务提供者接口)意味着它将是 * 能够以后<b>被开发者扩展</b>,为了<b>实现某种功能</b>的公开接口。<br> * SPI用于告诉别的开发者(大多为自然人)这段目标程序应该怎么做,要遵守什么约定。 * <p> * 声明为SPI可以理解为这段程序被设计者定义为“扩展点”,以后这里可以按照定义的约定有序扩展; * API则是程序设计者定义的“功能点”,为了告诉别人这里有这样的现成功能可以使用。<br> * SPI和API大多会被自然区分开来,例如JDBC驱动本身是SPI,驱动使用者并不会直接去调用驱动的任何接口;而驱动开发者根据统一的约定 * 为不同的数据库实现不同的具体驱动方法。<br> * 不过也存在同时既为API也是SPI的情况,例如JDBC的{@link java.sql.Connection}, * 开发者使用它的API与数据库进行连接,另一方面驱动的开发者按照它的SPI约定实现特定数据库相应的连接方法。 * * @see API * @author sin_sin * @since 1.0.0 * @version $Date: 2015-01-21 $ */ @Documented @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.CLASS) public @interface SPI { }
a90016508e316d193ee11daacf00b1cf08a43f68
2b1a19030c67079291deedd94a5d1bcb5400f050
/gen/com/example/sailsandroid/BuildConfig.java
0c08c273797df30811e85dcc70e943f87ced804d
[]
no_license
PBRT/Sails-Android-Native
bfb6c99b4ad204ba54aa0e00ecffdc0541041d02
da7ea323e47a48aadbdf295cb1aba58f1b677885
refs/heads/master
2021-01-19T09:25:20.526319
2014-05-20T20:45:00
2014-05-20T20:45:00
19,996,478
1
0
null
null
null
null
UTF-8
Java
false
false
166
java
/** Automatically generated file. DO NOT MODIFY */ package com.example.sailsandroid; public final class BuildConfig { public final static boolean DEBUG = true; }
6b8a503153c286dffc906fa77f382322c45afe50
dcfb6e88efe38fd32b80ff33c1049dbcaa453cac
/TeamCode/src/main/java/org/baconeers/Tasks/TankDriveTask.java
a56277cd7c3f5f89476f1e2a67c45c96f7d81af5
[ "BSD-3-Clause" ]
permissive
Paladins-of-St-Pauls/SkyStone
efbb3a7649c2f7b1639acc815c0ac5245a9ca521
007e5d38aabe5394f0cb43485c489fec8c42da7d
refs/heads/master
2023-05-03T04:45:52.518372
2021-06-03T09:36:47
2021-06-03T09:36:47
271,449,600
0
0
null
2020-06-11T04:16:50
2020-06-11T04:16:50
null
UTF-8
Java
false
false
936
java
package org.baconeers.Tasks; import org.baconeers.SkystoneDrive.NormalisedMecanumDrive; import org.baconeers.common.BaconOpMode; import org.baconeers.common.TankDrive; public class TankDriveTask extends BaseTask implements Task { private final TankDrive drive; private final double leftSpeed; private final double rightSpeed; public TankDriveTask(BaconOpMode opMode, double time, TankDrive drive, double leftSpeed, double rightSpeed) { super(opMode, time); this.drive = drive; this.leftSpeed = leftSpeed; this.rightSpeed = rightSpeed; } @Override public void init() { super.init(); drive.setEncoderMode(false); } @Override public void run() { if (isFinished()) { drive.setPower(0,0); drive.update(); return; } drive.setPower(leftSpeed, rightSpeed); drive.update(); } }
bdaab3216c1ba7396da0a998ecd493d266413261
838b89d8aab2c11ea0f0f52515e7d50b7e7045de
/src/main/java/com/example/bmicalculator/Analyse.java
77ba05ad99b138925dbab4202ab1e6667bc8c9ba
[]
no_license
SaaraInkinen/Application_Inkinen_Pakarinen
2a28108e0644ca33e6004cb06ee8e699e9ebf057
9c9c6bb6ac1b7fc442a509ba876670df0dbc5cd2
refs/heads/main
2023-04-23T00:21:10.748168
2021-05-07T10:39:36
2021-05-07T10:39:36
361,422,026
0
0
null
null
null
null
UTF-8
Java
false
false
1,049
java
package com.example.bmicalculator; public class Analyse { public static String analysis(String bmi) { float BMI = Float.valueOf(bmi); String analyse; if (BMI < 16.0) { analyse = "it is considered severely thin"; } else if (BMI >= 16 && BMI <= 17) { analyse = "it is considered moderate thin"; } else if (BMI >= 17 && BMI <= 18.5) { analyse = "it is considered mildly thin"; } else if (BMI >= 18.5 && BMI <= 25) { analyse = "it is considered normal."; } else if (BMI >= 25 && BMI <= 30) { analyse = "it is considered overweight"; } else if (BMI >= 30 && BMI <= 35) { analyse = "it is considered obese class 1"; } else if (BMI >= 35 && BMI <= 40) { analyse = "it is considered obese class 2"; } else if (BMI >= 40) { analyse = "it is considered obese class 3"; } else analyse = "Error"; return analyse; } }
9f778e18dd597ff143230bc4e7106e1d97c0855d
9d053772b771c32047c3eb9818d59e35ab9cfa99
/src/edu/iu/grid/oim/servlet/MetricServlet.java
bfa230ae1f91aa97b215efc7718888da6f90a8ac
[ "Apache-2.0" ]
permissive
opensciencegrid/oim
8451e1a80f367c7be74cbd26f9b5d33739bca96f
f46d835f3c0f6898817d69be91fb054b713ffaf7
refs/heads/master
2021-01-24T06:17:47.675362
2018-05-01T19:38:24
2018-05-01T19:38:24
21,243,262
0
3
null
2016-11-01T19:50:49
2014-06-26T14:21:28
Java
UTF-8
Java
false
false
5,401
java
package edu.iu.grid.oim.servlet; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Set; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import com.divrep.DivRep; import com.divrep.DivRepEvent; import com.divrep.DivRepRoot; import com.divrep.common.DivRepButton; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.lib.StaticConfig; import edu.iu.grid.oim.lib.AuthorizationException; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.db.AuthorizationTypeModel; import edu.iu.grid.oim.model.db.ContactTypeModel; import edu.iu.grid.oim.model.db.ContactModel; import edu.iu.grid.oim.model.db.DNAuthorizationTypeModel; import edu.iu.grid.oim.model.db.MetricModel; import edu.iu.grid.oim.model.db.SCModel; import edu.iu.grid.oim.model.db.SiteModel; import edu.iu.grid.oim.model.db.FacilityModel; import edu.iu.grid.oim.model.db.DNModel; import edu.iu.grid.oim.model.db.record.AuthorizationTypeRecord; import edu.iu.grid.oim.model.db.record.ContactTypeRecord; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.model.db.record.MetricRecord; import edu.iu.grid.oim.model.db.record.SCRecord; import edu.iu.grid.oim.model.db.record.SiteRecord; import edu.iu.grid.oim.model.db.record.FacilityRecord; import edu.iu.grid.oim.model.db.record.DNRecord; import edu.iu.grid.oim.view.BootBreadCrumbView; import edu.iu.grid.oim.view.BootMenuView; import edu.iu.grid.oim.view.BootPage; import edu.iu.grid.oim.view.BreadCrumbView; import edu.iu.grid.oim.view.ContentView; import edu.iu.grid.oim.view.DivRepWrapper; import edu.iu.grid.oim.view.HtmlView; import edu.iu.grid.oim.view.IView; import edu.iu.grid.oim.view.MenuView; import edu.iu.grid.oim.view.Page; import edu.iu.grid.oim.view.RecordTableView; import edu.iu.grid.oim.view.SideContentView; import edu.iu.grid.oim.view.TableView; import edu.iu.grid.oim.view.Utils; import edu.iu.grid.oim.view.TableView.Row; public class MetricServlet extends ServletBase implements Servlet { private static final long serialVersionUID = 1L; static Logger log = Logger.getLogger(MetricServlet.class); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserContext context = new UserContext(request); Authorization auth = context.getAuthorization(); auth.check("admin"); try { //construct view BootMenuView menuview = new BootMenuView(context, "admin"); ContentView contentview = createContentView(context); //setup crumbs BootBreadCrumbView bread_crumb = new BootBreadCrumbView(); bread_crumb.addCrumb("Administration", "admin"); bread_crumb.addCrumb("RSV Metric", null); contentview.setBreadCrumb(bread_crumb); BootPage page = new BootPage(context, menuview, contentview, createSideView()); page.render(response.getWriter()); } catch (SQLException e) { log.error(e); throw new ServletException(e); } } protected ContentView createContentView(UserContext context) throws ServletException, SQLException { ContentView contentview = new ContentView(context); //contentview.add(new HtmlView("<h1>RSV Metric</h1>")); MetricModel model = new MetricModel(context); for(MetricRecord rec : model.getAll()) { contentview.add(new HtmlView("<h2>"+StringEscapeUtils.escapeHtml(rec.name)+"</h2>")); RecordTableView table = new RecordTableView(); contentview.add(table); table.addRow("Common Name", rec.common_name); table.addRow("Abbreviation", rec.abbrev); table.addRow("Description", rec.description); table.addRow("Time Interval", rec.time_interval.toString() + " Seconds"); table.addRow("Fresh For", rec.fresh_for.toString() + " Seconds"); table.addRow("Help URL", rec.help_url); table.addRow("WLCG Metric Type", rec.wlcg_metric_type); /* class EditButtonDE extends DivRepButton { String url; public EditButtonDE(DivRep parent, String _url) { super(parent, "Edit"); url = _url; } protected void onEvent(DivRepEvent e) { redirect(url); } }; table.add(new DivRepWrapper(new EditButtonDE(context.getPageRoot(), StaticConfig.getApplicationBase()+"/metricedit?id=" + rec.id))); */ table.add(new HtmlView("<a class=\"btn\" href=\"metricedit?id=" + rec.id +"\">Edit</a>")); } return contentview; } private SideContentView createSideView() { SideContentView view = new SideContentView(); /* class NewButtonDE extends DivRepButton { String url; public NewButtonDE(DivRep parent, String _url) { super(parent, "Add New Metric"); url = _url; } protected void onEvent(DivRepEvent e) { redirect(url); } }; view.add("Operation", new NewButtonDE(context.getPageRoot(), "metricedit")); */ view.add(new HtmlView("<a class=\"btn\" href=\"metricedit\">Add New Metric</a>")); //view.add("About", new HtmlView("Todo..")); return view; } }
1fccc58b13b3c7f78af3a8313cd37db06959ee00
3d73db4a7c9a81a2ea614a05a342be50ba0502f9
/project/src/test/java/junit5/Test2.java
4bd20020697fb79c66a22f1c614522f17180a49b
[]
no_license
Ummnaa/javatest
5455314dbfd162869a05e0109eed187dda41e0f3
26b3eb48ac998b4473ff4779f753f30b443975e1
refs/heads/master
2023-07-17T22:45:58.616542
2021-09-03T01:31:27
2021-09-03T01:31:27
402,609,162
0
0
null
null
null
null
UTF-8
Java
false
false
850
java
package junit5; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.junit.jupiter.api.Test; public class Test2 { /* Assertions : 성공/실패 검증 - assertEquals(a,b) : a와 b가 같은지 검증 - assertTrue(a) : a가 true인지 검증 - assertFalse(b) : false인지 - assertNull(b) : null인지 - assertNotNull(b) : null이 아닌지 - assertArrayEquals(a,b) : 배열이 같은지 Assumptions : 성공일때만 테스트 진행 - assumeTrue() - assumeFalse() - assumeEquals() */ @Test void test1() { String a = "홍길동"; String b = "홍길동1"; String c=null; System.out.println(a); //System.out.println(c.toString()); //assertEquals(a,b); } @Test void test2() { assumeTrue(1==2); assertEquals("a", "a"); } }
56be80397ff96f83703e52222e8ec9d1cbc6504b
ab2fd960a295be52786b8d9394a7fd63e379b340
/dao/src/test/java/org/thingsboard/server/dao/service/BaseDeviceServiceTest.java
c925902f6fb1dfc3cff77819d630eb9715bf365a
[ "Apache-2.0" ]
permissive
ltcong1411/SmartDeviceFrameworkV2
654f7460baa00d8acbc483dddf46b62ce6657eea
6f1bbbf3a2a15d5c0527e68feebea370967bce8a
refs/heads/master
2020-04-22T02:46:44.240516
2019-02-25T08:19:43
2019-02-25T08:19:43
170,062,547
0
0
null
null
null
null
UTF-8
Java
false
false
27,258
java
/** * Copyright © 2016-2019 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.dao.service; import com.datastax.driver.core.utils.UUIDs; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.TextPageData; import org.thingsboard.server.common.data.page.TextPageLink; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.exception.DataValidationException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID; public abstract class BaseDeviceServiceTest extends AbstractServiceTest { private IdComparator<Device> idComparator = new IdComparator<>(); private TenantId tenantId; @Before public void before() { Tenant tenant = new Tenant(); tenant.setTitle("My tenant"); Tenant savedTenant = tenantService.saveTenant(tenant); Assert.assertNotNull(savedTenant); tenantId = savedTenant.getId(); } @After public void after() { tenantService.deleteTenant(tenantId); } @Test public void testSaveDevice() { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); Assert.assertNotNull(savedDevice); Assert.assertNotNull(savedDevice.getId()); Assert.assertTrue(savedDevice.getCreatedTime() > 0); Assert.assertEquals(device.getTenantId(), savedDevice.getTenantId()); Assert.assertNotNull(savedDevice.getCustomerId()); Assert.assertEquals(NULL_UUID, savedDevice.getCustomerId().getId()); Assert.assertEquals(device.getName(), savedDevice.getName()); DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertNotNull(deviceCredentials); Assert.assertNotNull(deviceCredentials.getId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); Assert.assertEquals(DeviceCredentialsType.ACCESS_TOKEN, deviceCredentials.getCredentialsType()); Assert.assertNotNull(deviceCredentials.getCredentialsId()); Assert.assertEquals(20, deviceCredentials.getCredentialsId().length()); savedDevice.setName("My new device"); deviceService.saveDevice(savedDevice); Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertEquals(foundDevice.getName(), savedDevice.getName()); deviceService.deleteDevice(tenantId, savedDevice.getId()); } @Test(expected = DataValidationException.class) public void testSaveDeviceWithEmptyName() { Device device = new Device(); device.setType("default"); device.setTenantId(tenantId); deviceService.saveDevice(device); } @Test(expected = DataValidationException.class) public void testSaveDeviceWithEmptyTenant() { Device device = new Device(); device.setName("My device"); device.setType("default"); deviceService.saveDevice(device); } @Test(expected = DataValidationException.class) public void testSaveDeviceWithInvalidTenant() { Device device = new Device(); device.setName("My device"); device.setType("default"); device.setTenantId(new TenantId(UUIDs.timeBased())); deviceService.saveDevice(device); } @Test(expected = DataValidationException.class) public void testAssignDeviceToNonExistentCustomer() { Device device = new Device(); device.setName("My device"); device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); try { deviceService.assignDeviceToCustomer(tenantId, device.getId(), new CustomerId(UUIDs.timeBased())); } finally { deviceService.deleteDevice(tenantId, device.getId()); } } @Test(expected = DataValidationException.class) public void testAssignDeviceToCustomerFromDifferentTenant() { Device device = new Device(); device.setName("My device"); device.setType("default"); device.setTenantId(tenantId); device = deviceService.saveDevice(device); Tenant tenant = new Tenant(); tenant.setTitle("Test different tenant"); tenant = tenantService.saveTenant(tenant); Customer customer = new Customer(); customer.setTenantId(tenant.getId()); customer.setTitle("Test different customer"); customer = customerService.saveCustomer(customer); try { deviceService.assignDeviceToCustomer(tenantId, device.getId(), customer.getId()); } finally { deviceService.deleteDevice(tenantId, device.getId()); tenantService.deleteTenant(tenant.getId()); } } @Test public void testFindDeviceById() { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNotNull(foundDevice); Assert.assertEquals(savedDevice, foundDevice); deviceService.deleteDevice(tenantId, savedDevice.getId()); } @Test public void testFindDeviceTypesByTenantId() throws Exception { List<Device> devices = new ArrayList<>(); try { for (int i=0;i<3;i++) { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device B"+i); device.setType("typeB"); devices.add(deviceService.saveDevice(device)); } for (int i=0;i<7;i++) { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device C"+i); device.setType("typeC"); devices.add(deviceService.saveDevice(device)); } for (int i=0;i<9;i++) { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device A"+i); device.setType("typeA"); devices.add(deviceService.saveDevice(device)); } List<EntitySubtype> deviceTypes = deviceService.findDeviceTypesByTenantId(tenantId).get(); Assert.assertNotNull(deviceTypes); Assert.assertEquals(3, deviceTypes.size()); Assert.assertEquals("typeA", deviceTypes.get(0).getType()); Assert.assertEquals("typeB", deviceTypes.get(1).getType()); Assert.assertEquals("typeC", deviceTypes.get(2).getType()); } finally { devices.forEach((device) -> { deviceService.deleteDevice(tenantId, device.getId()); }); } } @Test public void testDeleteDevice() { Device device = new Device(); device.setTenantId(tenantId); device.setName("My device"); device.setType("default"); Device savedDevice = deviceService.saveDevice(device); Device foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNotNull(foundDevice); deviceService.deleteDevice(tenantId, savedDevice.getId()); foundDevice = deviceService.findDeviceById(tenantId, savedDevice.getId()); Assert.assertNull(foundDevice); DeviceCredentials foundDeviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertNull(foundDeviceCredentials); } @Test public void testFindDevicesByTenantId() { Tenant tenant = new Tenant(); tenant.setTitle("Test tenant"); tenant = tenantService.saveTenant(tenant); TenantId tenantId = tenant.getId(); List<Device> devices = new ArrayList<>(); for (int i=0;i<178;i++) { Device device = new Device(); device.setTenantId(tenantId); device.setName("Device"+i); device.setType("default"); devices.add(deviceService.saveDevice(device)); } List<Device> loadedDevices = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(23); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); loadedDevices.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devices, idComparator); Collections.sort(loadedDevices, idComparator); Assert.assertEquals(devices, loadedDevices); deviceService.deleteDevicesByTenantId(tenantId); pageLink = new TextPageLink(33); pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertTrue(pageData.getData().isEmpty()); tenantService.deleteTenant(tenantId); } @Test public void testFindDevicesByTenantIdAndName() { String title1 = "Device title 1"; List<Device> devicesTitle1 = new ArrayList<>(); for (int i=0;i<143;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title1+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); devicesTitle1.add(deviceService.saveDevice(device)); } String title2 = "Device title 2"; List<Device> devicesTitle2 = new ArrayList<>(); for (int i=0;i<175;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title2+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); devicesTitle2.add(deviceService.saveDevice(device)); } List<Device> loadedDevicesTitle1 = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(15, title1); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); loadedDevicesTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesTitle1, idComparator); Collections.sort(loadedDevicesTitle1, idComparator); Assert.assertEquals(devicesTitle1, loadedDevicesTitle1); List<Device> loadedDevicesTitle2 = new ArrayList<>(); pageLink = new TextPageLink(4, title2); do { pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); loadedDevicesTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesTitle2, idComparator); Collections.sort(loadedDevicesTitle2, idComparator); Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); for (Device device : loadedDevicesTitle1) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title1); pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesTitle2) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title2); pageData = deviceService.findDevicesByTenantId(tenantId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @Test public void testFindDevicesByTenantIdAndType() { String title1 = "Device title 1"; String type1 = "typeA"; List<Device> devicesType1 = new ArrayList<>(); for (int i=0;i<143;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title1+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type1); devicesType1.add(deviceService.saveDevice(device)); } String title2 = "Device title 2"; String type2 = "typeB"; List<Device> devicesType2 = new ArrayList<>(); for (int i=0;i<175;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title2+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type2); devicesType2.add(deviceService.saveDevice(device)); } List<Device> loadedDevicesType1 = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(15); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantIdAndType(tenantId, type1, pageLink); loadedDevicesType1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesType1, idComparator); Collections.sort(loadedDevicesType1, idComparator); Assert.assertEquals(devicesType1, loadedDevicesType1); List<Device> loadedDevicesType2 = new ArrayList<>(); pageLink = new TextPageLink(4); do { pageData = deviceService.findDevicesByTenantIdAndType(tenantId, type2, pageLink); loadedDevicesType2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesType2, idComparator); Collections.sort(loadedDevicesType2, idComparator); Assert.assertEquals(devicesType2, loadedDevicesType2); for (Device device : loadedDevicesType1) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); pageData = deviceService.findDevicesByTenantIdAndType(tenantId, type1, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesType2) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); pageData = deviceService.findDevicesByTenantIdAndType(tenantId, type2, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @Test public void testFindDevicesByTenantIdAndCustomerId() { Tenant tenant = new Tenant(); tenant.setTitle("Test tenant"); tenant = tenantService.saveTenant(tenant); TenantId tenantId = tenant.getId(); Customer customer = new Customer(); customer.setTitle("Test customer"); customer.setTenantId(tenantId); customer = customerService.saveCustomer(customer); CustomerId customerId = customer.getId(); List<Device> devices = new ArrayList<>(); for (int i=0;i<278;i++) { Device device = new Device(); device.setTenantId(tenantId); device.setName("Device"+i); device.setType("default"); device = deviceService.saveDevice(device); devices.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List<Device> loadedDevices = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(23); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); loadedDevices.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devices, idComparator); Collections.sort(loadedDevices, idComparator); Assert.assertEquals(devices, loadedDevices); deviceService.unassignCustomerDevices(tenantId, customerId); pageLink = new TextPageLink(33); pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertTrue(pageData.getData().isEmpty()); tenantService.deleteTenant(tenantId); } @Test public void testFindDevicesByTenantIdCustomerIdAndName() { Customer customer = new Customer(); customer.setTitle("Test customer"); customer.setTenantId(tenantId); customer = customerService.saveCustomer(customer); CustomerId customerId = customer.getId(); String title1 = "Device title 1"; List<Device> devicesTitle1 = new ArrayList<>(); for (int i=0;i<175;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title1+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); device = deviceService.saveDevice(device); devicesTitle1.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } String title2 = "Device title 2"; List<Device> devicesTitle2 = new ArrayList<>(); for (int i=0;i<143;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title2+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); device = deviceService.saveDevice(device); devicesTitle2.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List<Device> loadedDevicesTitle1 = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(15, title1); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); loadedDevicesTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesTitle1, idComparator); Collections.sort(loadedDevicesTitle1, idComparator); Assert.assertEquals(devicesTitle1, loadedDevicesTitle1); List<Device> loadedDevicesTitle2 = new ArrayList<>(); pageLink = new TextPageLink(4, title2); do { pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); loadedDevicesTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesTitle2, idComparator); Collections.sort(loadedDevicesTitle2, idComparator); Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); for (Device device : loadedDevicesTitle1) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title1); pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesTitle2) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4, title2); pageData = deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); customerService.deleteCustomer(tenantId, customerId); } @Test public void testFindDevicesByTenantIdCustomerIdAndType() { Customer customer = new Customer(); customer.setTitle("Test customer"); customer.setTenantId(tenantId); customer = customerService.saveCustomer(customer); CustomerId customerId = customer.getId(); String title1 = "Device title 1"; String type1 = "typeC"; List<Device> devicesType1 = new ArrayList<>(); for (int i=0;i<175;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title1+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type1); device = deviceService.saveDevice(device); devicesType1.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } String title2 = "Device title 2"; String type2 = "typeD"; List<Device> devicesType2 = new ArrayList<>(); for (int i=0;i<143;i++) { Device device = new Device(); device.setTenantId(tenantId); String suffix = RandomStringUtils.randomAlphanumeric(15); String name = title2+suffix; name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type2); device = deviceService.saveDevice(device); devicesType2.add(deviceService.assignDeviceToCustomer(tenantId, device.getId(), customerId)); } List<Device> loadedDevicesType1 = new ArrayList<>(); TextPageLink pageLink = new TextPageLink(15); TextPageData<Device> pageData = null; do { pageData = deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type1, pageLink); loadedDevicesType1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesType1, idComparator); Collections.sort(loadedDevicesType1, idComparator); Assert.assertEquals(devicesType1, loadedDevicesType1); List<Device> loadedDevicesType2 = new ArrayList<>(); pageLink = new TextPageLink(4); do { pageData = deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type2, pageLink); loadedDevicesType2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageData.getNextPageLink(); } } while (pageData.hasNext()); Collections.sort(devicesType2, idComparator); Collections.sort(loadedDevicesType2, idComparator); Assert.assertEquals(devicesType2, loadedDevicesType2); for (Device device : loadedDevicesType1) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); pageData = deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type1, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); for (Device device : loadedDevicesType2) { deviceService.deleteDevice(tenantId, device.getId()); } pageLink = new TextPageLink(4); pageData = deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type2, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); customerService.deleteCustomer(tenantId, customerId); } }
6093db47a4bbcddb0d88695d16511e014cfc9260
3f00542fe73c21cd1364bbbd85c5c885537a82c7
/src/user_reg.java
b8035960040b531ad7adf4faac75f01733e98522
[]
no_license
juvs98/juvs
78f5cec0b8a9a49566ec27eb6e77a517d1e9cc04
7419e888e200abac79a82bbe64fcf33f476b9ed7
refs/heads/master
2020-07-22T05:51:22.129144
2019-09-08T09:58:35
2019-09-08T09:58:35
207,092,733
0
0
null
null
null
null
UTF-8
Java
false
false
4,187
java
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 hp */ public class user_reg extends javax.swing.JFrame { registration r = new registration(); /** * Creates new form user_reg */ public user_reg() { 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() { jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Register"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addContainerGap(317, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(250, Short.MAX_VALUE) .addComponent(jButton1) .addGap(27, 27, 27)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.setVisible(false); new registrationframe().setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(user_reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(user_reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(user_reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(user_reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new user_reg().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; // End of variables declaration//GEN-END:variables }
[ "hp@Traci" ]
hp@Traci
03473648a5a97c57ad80a659b973a99697e40808
f24dc586b9be071e80931bb614f40bdcebe74781
/src/com/example/activity/LinearLayoutActivity.java
fc5681fc7e6da7f47bba895d2fd972bb6241f2f1
[]
no_license
handezhao/MyTest
df39cd40debbc10b9ccbe4875afe4b2084394922
c28cc3a6bc02fb82312c41ad6d9108c9d9250349
refs/heads/master
2020-04-12T08:14:17.996079
2017-04-21T11:34:56
2017-04-21T11:34:56
64,116,600
0
1
null
null
null
null
UTF-8
Java
false
false
306
java
package com.example.activity; import com.example.mytest.R; import android.os.Bundle; public class LinearLayoutActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_linearlayout); } }
b47fd6d6a79d479779f536382bf39a474cbb4e2a
f755fea078eef901ad92f5107799eea7c4d82e3b
/app/src/main/java/com/template/design/IPC/Messenger/MessengerService.java
69913120f289ea7cb172e78bcdab7348d86bcf2a
[]
no_license
wkboys/DesignAndIPC
4f613b7538b8367fd4b7c82dc6f7f2edfedfd736
4268a01cf7d287e063396d6154e1b45e352f8247
refs/heads/master
2023-02-22T17:29:13.897826
2021-01-25T07:53:40
2021-01-25T07:53:40
331,824,601
0
0
null
null
null
null
UTF-8
Java
false
false
1,637
java
package com.template.design.IPC.Messenger; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class MessengerService extends Service { public static final String TAG="MoonMessenger"; public static final int MSG_FROMCLIENT=1000; @SuppressLint("HandlerLeak") private Handler mHandler =new Handler(){ @Override public void handleMessage(@NonNull Message msg) { // super.handleMessage(msg); switch (msg.what){ case MSG_FROMCLIENT: Log.e(TAG,"收到客户端信息-----------"+msg.getData().get("msg")); Messenger mMessenger=msg.replyTo; Message mMessage=Message.obtain(null,MessengerService.MSG_FROMCLIENT); Bundle mBundle=new Bundle(); mBundle.putString("rep","这里是服务端,我们收到消息了"); mMessage.setData(mBundle); try { mMessenger.send(mMessage); } catch (RemoteException e) { e.printStackTrace(); } break; } } }; @Nullable @Override public IBinder onBind(Intent intent) { return new Messenger(mHandler).getBinder(); } }
8c65f94b189c275884605ddf3b2928b3f54c2981
c6c8cfe846284bba92e0874b5bb4305a9aca4c6f
/src/main/java/com/laamella/bitmask/BitmaskModifier.java
16001d8f4274adccb4934199633f85fb2a42cf66
[]
no_license
gitter-badger/bitmask
2311d0bfc45d12c6e3e5e476cde40e601ef6727b
63e280d8835f13d7c99b5dd0f60bb28b94d9228a
refs/heads/master
2021-01-15T17:59:48.742886
2016-01-27T12:14:32
2016-01-27T12:14:32
50,590,798
0
0
null
2016-01-28T15:05:40
2016-01-28T15:05:38
Java
UTF-8
Java
false
false
4,628
java
package com.laamella.bitmask; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; /** * Various drawing tools that were separated from Bitmask to prevent bloat. */ public final class BitmaskModifier { private BitmaskModifier() { // can't instantiate } private static final int AND = 0; private static final int ERASE = 1; /** * Apply some function to the bits in a with the bits in b that overlap them * using an offset. * * @param b * @param xOffset * @param yOffset * @param operation */ private static final void apply(final Bitmask a, final Bitmask b, final int xOffset, final int yOffset, final int operation) { if (!a.overlapsBoundingRectangleOf(b, xOffset, yOffset)) { return; } // Find out what area in this bitmask will be combined with b int left = xOffset; int right = xOffset + b.getWidth(); int top = yOffset; int bottom = yOffset + b.getHeight(); if (left < 0) { left = 0; } if (right > a.getWidth()) { right = a.getWidth(); } if (top < 0) { top = 0; } if (bottom > a.getHeight()) { bottom = a.getHeight(); } for (int x = left; x < right; x++) { for (int y = top; y < bottom; y++) { final boolean aBit = a.getBit(x, y); final boolean bBit = b.getBit(x - xOffset, y - yOffset); boolean resultBit; switch (operation) { case AND: resultBit = aBit | bBit; break; case ERASE: resultBit = aBit ^ bBit; break; default: throw new IllegalArgumentException("Don't know operation " + operation); } if (resultBit) { a.setBit(x, y); } else { a.clearBit(x, y); } } } } /** * Draws mask b onto mask a (bitwise OR). Can be used to compose large (game * background?) mask from several submasks, which may speed up the testing. * * @param bitmaskModifier */ public final static void draw(final Bitmask a, final Bitmask b, final int xOffset, final int yOffset) { apply(a, b, xOffset, yOffset, AND); } /** * @see Bitmask#draw(Bitmask, int, int) */ public final static void draw(final Bitmask a, final Bitmask b, final Point2D offset) { draw(a, b, (int) offset.getX(), (int) offset.getY()); } /** * Erase any set bits on this bitmask that are set in bitmask b. */ public final static void erase(final Bitmask a, final Bitmask b, final int xOffset, final int yOffset) { apply(a, b, xOffset, yOffset, ERASE); } /** * @see Bitmask#erase(Bitmask, int, int) */ public final static void erase(final Bitmask a, final Bitmask b, final Point2D offset) { erase(a, b, (int) offset.getX(), (int) offset.getY()); } /** * Return a new scaled Bitmask, with dimensions w x h. The algorithm makes * no attempt at smoothing the result. If either w or h is less than one, a * clear 1x1 mask is returned. */ public final static Bitmask scale(final Bitmask source, final int scaledWidth, final int scaledHeight) { if (scaledWidth < 1 || scaledHeight < 1) { return new Bitmask(1, 1); } final Bitmask newMask = new Bitmask(scaledWidth, scaledHeight); final double xFactor = (double) source.getWidth() / scaledWidth; final double yFactor = (double) source.getHeight() / scaledHeight; for (int x = 0; x < scaledWidth; x++) { for (int y = 0; y < scaledHeight; y++) { if (source.getBit((int) ((x + 0.5) * xFactor), (int) ((y + 0.5) * yFactor))) { newMask.setBit(x, y); } } } return newMask; } /** * @see Bitmask#scale(int, int) */ public static Bitmask scale(final Bitmask source, final Dimension2D size) { return scale(source, (int) size.getWidth(), (int) size.getHeight()); } /** * Convolve b into a, drawing the output into o, shifted by offset. If * offset is 0, then the (x,y) bit will be set if and only if * Bitmask_overlap(a, b, x - b->w - 1, y - b->h - 1) returns true. * * <pre> * Modifies bits o[xoffset ... xoffset + a->w + b->w - 1) * [yoffset ... yoffset + a->h + b->h - 1). * </pre> */ public static void convolve(final Bitmask a, final Bitmask b, final Bitmask o, int xoffset, int yoffset) { xoffset += b.getWidth() - 1; yoffset += b.getHeight() - 1; for (int y = 0; y < b.getHeight(); y++) { for (int x = 0; x < b.getWidth(); x++) { if (b.getBit(x, y)) { // FIXME not sure what this is supposed to do draw(a, o, xoffset - x, yoffset - y); } } } } /** * @see Bitmask#convolve(Bitmask, Bitmask, int, int) */ public static void convolve(final Bitmask a, final Bitmask b, final Bitmask o, final Point2D offset) { convolve(a, b, o, (int) offset.getX(), (int) offset.getY()); } }
[ "danny@werklaptop.(none)" ]
danny@werklaptop.(none)
62f84809b9841b588ecfcd0c51da0527452bb384
03f609ca4950205204fda660c3db9c8c3e6ad448
/algorithm/src/main/java/cn/edu/wj/sign/DESedeCoder.java
148ef2cda8e9393099286770531a8af4d4de787f
[]
no_license
wujianlovewy/dubbo-study
545fcdd71c188c5f490d3a4c480713dfab4867d1
a7e2d92f1d3d47a542f923c89ae21bfe6367e4a0
refs/heads/master
2021-01-15T16:10:14.113534
2018-03-30T08:48:37
2018-03-30T08:48:37
99,710,348
0
0
null
null
null
null
GB18030
Java
false
false
2,877
java
package cn.edu.wj.sign; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import org.apache.commons.codec.binary.Base64; public class DESedeCoder { /** * 密钥算法 * */ public static final String KEY_ALGORITHM="DESede"; /** * 加密/解密算法/工作模式/填充方式 * */ public static final String CIPHER_ALGORITHM="DESede/ECB/PKCS5Padding"; /** * @return byte[] 二进制密钥 * */ public static byte[] initkey() throws Exception{ //实例化密钥生成器 KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM); //初始化密钥生成器 kg.init(112); //生成密钥 SecretKey secretKey=kg.generateKey(); //获取二进制密钥编码形式 return secretKey.getEncoded(); } /** * 转换密钥 * @param key 二进制密钥 * @return Key 密钥 * */ public static Key toKey(byte[] key) throws Exception{ //实例化Des密钥 DESedeKeySpec dks=new DESedeKeySpec(key); //实例化密钥工厂 SecretKeyFactory keyFactory=SecretKeyFactory.getInstance(KEY_ALGORITHM); //生成密钥 SecretKey secretKey=keyFactory.generateSecret(dks); return secretKey; } /** * 加密数据 * @param data 待加密数据 * @param key 密钥 * @return byte[] 加密后的数据 * */ public static byte[] encrypt(byte[] data,byte[] key) throws Exception{ //还原密钥 Key k=toKey(key); //实例化 Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM); //初始化,设置为加密模式 cipher.init(Cipher.ENCRYPT_MODE, k); //执行操作 return cipher.doFinal(data); } /** * 解密数据 * @param data 待解密数据 * @param key 密钥 * @return byte[] 解密后的数据 * */ public static byte[] decrypt(byte[] data,byte[] key) throws Exception{ //欢迎密钥 Key k =toKey(key); //实例化 Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM); //初始化,设置为解密模式 cipher.init(Cipher.DECRYPT_MODE, k); //执行操作 return cipher.doFinal(data); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { String str="DESede"; System.out.println("原文:"+str); //初始化密钥 byte[] key=DESedeCoder.initkey(); System.out.println("密钥:"+Base64.encodeBase64String(key)+", 秘钥长度:"+key.length); //加密数据 byte[] data=DESedeCoder.encrypt(str.getBytes(), key); System.out.println("加密后:"+Base64.encodeBase64String(data)); //解密数据 data=DESedeCoder.decrypt(data, key); System.out.println("解密后:"+new String(data)); } }
74f23004d897da9555b86e5da632e8d355ae9951
e5fdd57b9e77c61a506e64ecfb78d04fc008260c
/app/src/androidTest/java/com/example/reservasdeportivas/ExampleInstrumentedTest.java
b35630e93c3f0dc9e93889d0fdd285c74a766623
[]
no_license
johnhenao10/ReservasDeportivas
90bc1aab4243a393ce7fbf19b4e1810779d98d60
b37a1c2679d240ca5db48969d89ddba06bba8456
refs/heads/master
2023-09-04T10:41:34.876074
2021-10-16T17:24:35
2021-10-16T17:24:35
416,586,949
0
0
null
null
null
null
UTF-8
Java
false
false
774
java
package com.example.reservasdeportivas; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.reservasdeportivas", appContext.getPackageName()); } }
8a3a3a6cc33b0d5b431c87f638c08fb6e40afb43
f7c0d1659a8008c2456ee4c0541501735f030232
/src/main/java/com/insight/web/controller/WelcomeController.java
633df33fe907a76b1b8226de90488c396c38af15
[]
no_license
lovjitbedi/Server
81677a788c4d45561a33201a5c1c5d3a4ead10c4
e612a6b8d3d50d900431105b1d6b9dd220b94227
refs/heads/master
2020-07-04T18:57:34.816619
2016-01-26T19:20:15
2016-01-26T19:20:28
50,452,599
0
0
null
null
null
null
UTF-8
Java
false
false
531
java
package com.insight.web.controller; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; //import com.insight.job.services.BulkDocumentUpload; import com.insight.security.SiteManUserDetails; @Controller public class WelcomeController extends BaseController {}
5b90266dae538091bc1cce1ff42c2071df3e3ad3
4f1b3b797feb068c81f3dac97d7b84872185c919
/smart_student/src/main/java/org/seusl/dto/email/EmailConfigurationImpl.java
5e04236990cb7667a891a19c8a83bbb1ec942375
[]
no_license
jmhmjayamaha/Student-Management-System
c9553e65346a693bab92429a2711ab5d9d32e3e0
1b0eabe43e03d88d62566026c36397954049de1c
refs/heads/master
2021-01-13T04:35:54.595398
2017-03-18T15:50:53
2017-03-18T15:50:53
79,515,602
0
0
null
null
null
null
UTF-8
Java
false
false
1,745
java
package org.seusl.dto.email; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; import org.seusl.configuration.project.PropertyConfiguration; public class EmailConfigurationImpl implements EmailConfiguration { private Logger log = Logger.getLogger(EmailConfigurationImpl.class); public void sendEmail(String to, String subject) { final Mailer mailer = new Mailer(); EmailTemplateCreation template = new EmailTemplateCreation(); PropertyConfiguration instance = new PropertyConfiguration(); mailer.setFrom(instance.getEmail()); mailer.setUsername(instance.getEmailUsername()); mailer.setPassword(instance.getEmailPassword()); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "25"); try { Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailer.getUsername(), mailer.getPassword()); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(mailer.getFrom())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(template.getEmailText()); Transport.send(message); } catch (MessagingException e) { log.error(e.getMessage()); } } }
c803dd3816caa19fec36ee63e03f2e711a77028f
77a7120c33201c984153c93eeec5b5dc1d943e60
/src/main/java/com/ippse/web/IppseWebApplication.java
d0f5da7fb1f828894b1d10aa2259281f06dab5f1
[]
no_license
mahaorong/ippse-web
2bdfb3d9c7515ec3bdd8c78e2d035626eae412c3
54833ec84b23845f6f11e820a7c8a64b8d117793
refs/heads/master
2023-05-12T15:30:22.918264
2019-06-24T02:22:11
2019-06-24T02:22:11
193,419,358
0
0
null
2023-05-06T03:18:52
2019-06-24T02:21:19
JavaScript
UTF-8
Java
false
false
4,616
java
package com.ippse.web; import java.util.Locale; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer; import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.core.annotation.Order; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.MultipartFilter; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import lombok.extern.slf4j.Slf4j; @Slf4j @SpringBootApplication(scanBasePackages = "com.ippse.web") @EnableJpaRepositories(basePackages = { "com.ippse.web" }) @EntityScan(basePackages = { "com.ippse.web" }) @ComponentScan(basePackages = { "com.ippse.web" }) @EnableFeignClients @Configuration @EnableOAuth2Client @EnableAutoConfiguration(exclude = { MultipartAutoConfiguration.class }) public class IppseWebApplication { public static void main(String[] args) { SpringApplication.run(IppseWebApplication.class, args); } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.CHINA); return slr; } @Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:i18n/messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setCacheSeconds(3600); // refresh cache once per hour return messageSource; } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("123"); converter.setAccessTokenConverter(new JwtConverter()); return converter; } @Bean @Primary public DefaultTokenServices tokenServices() { DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } public static class JwtConverter extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer { @Override public void configure(JwtAccessTokenConverter converter) { converter.setAccessTokenConverter(this); } @Override public OAuth2Authentication extractAuthentication(Map<String, ?> map) { OAuth2Authentication auth = super.extractAuthentication(map); log.info("JwtConverter" + map); auth.setDetails(map); // this will get spring to copy JWT content // into Authentication return auth; } } @Bean @Order(0) public MultipartFilter multipartFilter() { MultipartFilter multipartFilter = new MultipartFilter(); multipartFilter.setMultipartResolverBeanName("multipartResolver"); return multipartFilter; } // 显式声明CommonsMultipartResolver为mutipartResolver @Bean(name = "multipartResolver") public MultipartResolver mutipartResolver() { CustomMultipartResolver com = new CustomMultipartResolver(); com.setDefaultEncoding("utf-8"); // com.setUploadTempDir(uploadTempDir);//TODO 完善对每用户的临时文件夹大小的控制 return com; } }
ad12ef66327bd2239ed1c23f193fa04e5643feea
891a3485edf6a1b6473423b9cdf3c3c37884af19
/src/Dog.java
b6a297eeac95fe062bfbc141421982742f0678f5
[]
no_license
cCraBb1538/Lab1_Dyuko
e627cedc2c775124d2d1875113eba5504aeb355f
a1ecd7ff087e54570aaac053cfb44bbd92ff1eb2
refs/heads/master
2022-12-29T23:24:27.187824
2020-10-16T20:54:00
2020-10-16T20:54:00
304,736,611
0
0
null
null
null
null
UTF-8
Java
false
false
776
java
import java.lang.System; public class Dog { private String name; private int age; public Dog(String n, int a) { name = n; age = a; } public Dog(String n) { name = n; age = 0; } public Dog() { name = "CraB"; age = 6; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } public String getName(String name) { return name; } public int getAge() { return age; } public String toString() { return this.name + ", age " + this.age; } public void intoHumanAge() { System.out.println(name + "'s age in human years is " + age * 13 + " years"); } }
1a765b4a409967097b596eaf840254db2ec4e01a
488c74bf97574547d01ce6c330f51bc8f78352d3
/src/java_study_0130/CompositeMain.java
0e2f0f2230fb119871170c742abde2a9e9271d93
[]
no_license
hiwony7933/JavaApp
365b8a74354f658504d89233e05a04a51272e564
36b6ca58be0308f9378621184dc7dc88e4e2c0ae
refs/heads/master
2021-03-30T01:28:52.387021
2020-03-18T07:37:33
2020-03-18T07:37:33
248,001,856
0
0
null
null
null
null
UTF-8
Java
false
false
693
java
package java_study_0130; public class CompositeMain { public static void main(String[] args) { File f1 = new File("파일1"); File f2 = new File("파일2"); File f3 = new File("파일3"); Directory subDirectory = new Directory("하위 디렉토리"); subDirectory.add(f1); subDirectory.add(f2); Directory superDirectory = new Directory("상위 디렉토리"); superDirectory.add(subDirectory); superDirectory.add(f3);; superDirectory.remove(); // 다지워짐 //자료형 이름 출력 System.out.println(superDirectory.getClass().getName()); Entry entry = new Directory("디렉토리"); System.out.println(entry.getClass().getName()); } }
e9750dd2ab0740d9e4945acb7bb990e81711867d
129f58086770fc74c171e9c1edfd63b4257210f3
/src/testcases/CWE483_Incorrect_Block_Delimitation/CWE483_Incorrect_Block_Delimitation__semicolon_04.java
c43053330ab074f54676af37f28df3430cd9e38c
[]
no_license
glopezGitHub/Android23
1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba
6215d0684c4fbdc7217ccfbedfccfca69824cc5e
refs/heads/master
2023-03-07T15:14:59.447795
2023-02-06T13:59:49
2023-02-06T13:59:49
6,856,387
0
3
null
2023-02-06T18:38:17
2012-11-25T22:04:23
Java
UTF-8
Java
false
false
4,948
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE483_Incorrect_Block_Delimitation__semicolon_04.java Label Definition File: CWE483_Incorrect_Block_Delimitation.label.xml Template File: point-flaw-04.tmpl.java */ /* * @description * CWE: 483 Incorrect Block Delimitation * Sinks: semicolon * GoodSink: Absence of suspicious semicolon * BadSink : Suspicious semicolon before the if statement brace * Flow Variant: 04 Control flow: if(private_final_t) and if(private_final_f) * * */ package testcases.CWE483_Incorrect_Block_Delimitation; import testcasesupport.*; import java.security.SecureRandom; public class CWE483_Incorrect_Block_Delimitation__semicolon_04 extends AbstractTestCase { /* The two variables below are declared "final", so a tool should be able to identify that reads of these will always return their initialized values. */ private final boolean private_final_t = true; private final boolean private_final_f = false; public void bad() throws Throwable { if (private_final_t) { int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FLAW: Suspicious semicolon before the if statement brace */ if (x == 0); { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FIX: Remove the suspicious semicolon before the if statement brace */ if (x == 0) { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } } /* good1() changes private_final_t to private_final_f */ private void good1() throws Throwable { if(private_final_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FLAW: Suspicious semicolon before the if statement brace */ if (x == 0); { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } else { int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FIX: Remove the suspicious semicolon before the if statement brace */ if (x == 0) { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } } /* good2() reverses the bodies in the if statement */ private void good2() throws Throwable { if(private_final_t) { int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FIX: Remove the suspicious semicolon before the if statement brace */ if (x == 0) { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ int x; int y; SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); x = (rand.nextInt() % 3); y = 0; /* FLAW: Suspicious semicolon before the if statement brace */ if (x == 0); { IO.writeLine("x == 0"); y = 1; /* do something other than just printing in block */ } IO.writeLine(y); } } public void good() throws Throwable { good1(); good2(); } /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
5e14068fee120268d2baa6e3212ec3d78c18777a
5bec604b105dbb48aa9a50a9edf76bb1ce76b6df
/src/main/java/com/mycompany/myapp/web/rest/GeoCoordinateResource.java
04700d1db7d94dff46a2134a392d1c6300d4fe36
[]
no_license
vin-node/jhipster
f320deb82e22edd21fdbd22c0fb9b794d53738c9
ad9668e34242048841682bb0b7e16d8619fb1f4e
refs/heads/master
2021-07-02T22:16:04.237075
2017-09-25T03:37:24
2017-09-25T03:37:24
104,521,156
1
1
null
null
null
null
UTF-8
Java
false
false
5,477
java
package com.mycompany.myapp.web.rest; import com.codahale.metrics.annotation.Timed; import com.mycompany.myapp.domain.GeoCoordinate; import com.mycompany.myapp.service.GeoCoordinateService; import com.mycompany.myapp.web.rest.util.HeaderUtil; import com.mycompany.myapp.web.rest.util.PaginationUtil; import io.swagger.annotations.ApiParam; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing GeoCoordinate. */ @RestController @RequestMapping("/api") public class GeoCoordinateResource { private final Logger log = LoggerFactory.getLogger(GeoCoordinateResource.class); private static final String ENTITY_NAME = "geoCoordinate"; private final GeoCoordinateService geoCoordinateService; public GeoCoordinateResource(GeoCoordinateService geoCoordinateService) { this.geoCoordinateService = geoCoordinateService; } /** * POST /geo-coordinates : Create a new geoCoordinate. * * @param geoCoordinate the geoCoordinate to create * @return the ResponseEntity with status 201 (Created) and with body the new geoCoordinate, or with status 400 (Bad Request) if the geoCoordinate has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/geo-coordinates") @Timed public ResponseEntity<GeoCoordinate> createGeoCoordinate(@RequestBody GeoCoordinate geoCoordinate) throws URISyntaxException { log.debug("REST request to save GeoCoordinate : {}", geoCoordinate); if (geoCoordinate.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new geoCoordinate cannot already have an ID")).body(null); } GeoCoordinate result = geoCoordinateService.save(geoCoordinate); return ResponseEntity.created(new URI("/api/geo-coordinates/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /geo-coordinates : Updates an existing geoCoordinate. * * @param geoCoordinate the geoCoordinate to update * @return the ResponseEntity with status 200 (OK) and with body the updated geoCoordinate, * or with status 400 (Bad Request) if the geoCoordinate is not valid, * or with status 500 (Internal Server Error) if the geoCoordinate couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/geo-coordinates") @Timed public ResponseEntity<GeoCoordinate> updateGeoCoordinate(@RequestBody GeoCoordinate geoCoordinate) throws URISyntaxException { log.debug("REST request to update GeoCoordinate : {}", geoCoordinate); if (geoCoordinate.getId() == null) { return createGeoCoordinate(geoCoordinate); } GeoCoordinate result = geoCoordinateService.save(geoCoordinate); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, geoCoordinate.getId().toString())) .body(result); } /** * GET /geo-coordinates : get all the geoCoordinates. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of geoCoordinates in body */ @GetMapping("/geo-coordinates") @Timed public ResponseEntity<List<GeoCoordinate>> getAllGeoCoordinates(@ApiParam Pageable pageable) { log.debug("REST request to get a page of GeoCoordinates"); Page<GeoCoordinate> page = geoCoordinateService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/geo-coordinates"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /geo-coordinates/:id : get the "id" geoCoordinate. * * @param id the id of the geoCoordinate to retrieve * @return the ResponseEntity with status 200 (OK) and with body the geoCoordinate, or with status 404 (Not Found) */ @GetMapping("/geo-coordinates/{id}") @Timed public ResponseEntity<GeoCoordinate> getGeoCoordinate(@PathVariable Long id) { log.debug("REST request to get GeoCoordinate : {}", id); GeoCoordinate geoCoordinate = geoCoordinateService.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(geoCoordinate)); } /** * DELETE /geo-coordinates/:id : delete the "id" geoCoordinate. * * @param id the id of the geoCoordinate to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/geo-coordinates/{id}") @Timed public ResponseEntity<Void> deleteGeoCoordinate(@PathVariable Long id) { log.debug("REST request to delete GeoCoordinate : {}", id); geoCoordinateService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
3952e872112c878b792f255dd26b5f10b200e89a
ad605e50c86de5b91c23ce47a8b79100bfa4cf6d
/org.talend.mdm.core/src/com/amalto/core/webservice/WSPutBusinessConcept.java
a9ddc7f9e08e3265d39179cad72baca019f03424
[]
no_license
marclx/tmdm-server-se
85e56728718f131e54b786518b58aee4f2b3b794
6c234c0f7ed467e7e1a8b76e80831db25ed6ff71
refs/heads/master
2021-01-18T15:12:30.154475
2015-03-20T12:56:25
2015-03-20T12:56:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,271
java
// This class was generated by the JAXRPC SI, do not edit. // Contents subject to change without notice. // JAX-RPC Standard Implementation (1.1.2_01,编译版 R40) // Generated source version: 1.1.2 package com.amalto.core.webservice; public class WSPutBusinessConcept { protected com.amalto.core.webservice.WSDataModelPK wsDataModelPK; protected com.amalto.core.webservice.WSBusinessConcept businessConcept; public WSPutBusinessConcept() { } public WSPutBusinessConcept(com.amalto.core.webservice.WSDataModelPK wsDataModelPK, com.amalto.core.webservice.WSBusinessConcept businessConcept) { this.wsDataModelPK = wsDataModelPK; this.businessConcept = businessConcept; } public com.amalto.core.webservice.WSDataModelPK getWsDataModelPK() { return wsDataModelPK; } public void setWsDataModelPK(com.amalto.core.webservice.WSDataModelPK wsDataModelPK) { this.wsDataModelPK = wsDataModelPK; } public com.amalto.core.webservice.WSBusinessConcept getBusinessConcept() { return businessConcept; } public void setBusinessConcept(com.amalto.core.webservice.WSBusinessConcept businessConcept) { this.businessConcept = businessConcept; } }
[ "achen@f6f1c999-d317-4740-80b0-e6d1abc6f99e" ]
achen@f6f1c999-d317-4740-80b0-e6d1abc6f99e
2912ce8f6bd3008325829f0d353d35e2d8cdc78a
700ed5ee07c596a027856552f1eb0bf90a6130a0
/JavaSE/src/Java_More/IO/ByteStream/OutputStream.java
50093c9e18e3ece592d8b621a7310dda1f133a61
[]
no_license
Dreamer0089/Java
8fcb0cb105aa9c98b196ca850d9a20f46b753491
bef37eab45e0fb39823947eeef08414158433a75
refs/heads/master
2020-09-09T14:12:18.179439
2019-12-20T16:12:49
2019-12-20T16:12:49
221,468,104
0
0
null
null
null
null
UTF-8
Java
false
false
4,948
java
package Java_More.IO.ByteStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; /* 字节输出流:OutputStream 输入输出是相对于内存来说的;读写是相对于硬盘的 输入:从硬盘到内存,读 输出:从内存到硬盘,写 java.io.OutputStream 字节输出流所有类的超类 一些子类共性的成员方法: public void close() 关闭此输出流并释放与此流有关的所有系统资源。 public void flush() 刷新此输出流并强制写出所有缓冲的输出字节。 public void write(byte[] b) 将 b.length 个字节从指定的 byte 数组写入此输出流。 public void write(byte[] b, int off, int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。 public abstract void write(int b) 将指定的字节写入此输出流。 java.io.FileOutputStream extends OutputStream FileOutputStream:文件字节输出流 作用:把内存中的数据写入硬盘文件中 构造方法: FileOutputStream(File file) 创建一个向指定 File 对象表示的文件中写入数据的文件输出流。 FileOutputStream(String name) 创建一个向具有指定名称的文件中写入数据的输出文件流。 参数: File file:目的地是一个文件 String name:目的地是一个路径 作用: 1.创建一个FileOutputStream对象 2.会根据构造方法传递的文件/文件路径,创建一个空的文件 3.会把FileOutputStream对象指向创建好的文件 追加写:使用两个参数的构造方法 FileOutputStream(File file, boolean append) 创建一个向指定 File 对象表示的文件中写入数据的文件输出流。 FileOutputStream(String name, boolean append) 创建一个向具有指定 name 的文件中写入数据的输出文件流。 boolean append:追加写开关(是不是在源文件的后面继续写) true:创建的对象不会覆盖原文件,继续在文件的末尾追加写数据 false:创建新文件,覆盖原文件 换行写: 在要写入文件的字符末尾添加换行符 Windows: \r\n Linux: /n mac: /r 写入数据的原理(内存->硬盘) Java程序-->JVM-->OS-->OS调用写数据的方法-->把数据写到文件中 字节输出流的步骤: 1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地 2.调用FileOutputStream对象中的方法write,把数据写入到文件中 3.释放资源(流使用会占用一定的内存,使用完毕释放,可以提高程序执行效率) */ public class OutputStream { public static void main(String[] args) throws IOException { //1.创建一个FileOutputStream对象,构造方法中传递写入数据的目的地 // FileOutputStream fos = new FileOutputStream("F:\\test\\b.txt"); //2.调用FileOutputStream对象中的方法write,把数据写入到文件中 //100指的是字符的ASCII值,代表的字符是d //0——127,使用的是 ASCII码表 //其他值,使用的是 GBK码表(中文系统默认码表) //fos.write(100); //3.释放资源(流使用会占用一定的内存,使用完毕释放,可以提高程序执行效率) /* public void write(byte[] b) 将 b.length 个字节从指定的 byte 数组写入此输出流。 一次写多个字节; 如果写的第一个字节是正数(0-127),显示时会查询ASCII表 如果写的第一个字节是负数,第一个、第二个字节组成一个中文显示,查询GBK表 */ //byte[] b = {65,66,67,68,69,49,48,48}; //fos.write(b);//ABCDE100 //byte[] b = {-65,-66,-67,-68,69,49,48,48}; //fos.write(b);//烤郊E100 //byte[] b = {-65,-66,-67,-68,69,49,48,48}; //fos.write(b,2,5);//郊E10 /* String类中的方法; String str; */ // byte[] bytes = "你好!".getBytes(); // System.out.println(Arrays.toString(bytes)); // fos.write(bytes); //追加写 FileOutputStream fos = new FileOutputStream("F:\\test\\b.txt", true); for (int i = 0; i < 10; i++) { //fos.write("你好!\r\n".getBytes()); fos.write("你好!".getBytes()); fos.write("\r\n".getBytes()); } fos.close(); } }
a0877b146bf3405376ed368a7fdb41cbec017ac0
2c0004276a6bddbb66c0ddfc6d0b1528ccafa321
/jascut/src/main/java/jascut/xml/ArgumentXml.java
a8101a32c556ce8709ba06c30700f323b81e0432
[]
no_license
SoffidIAM/tools
95e78ab1f8f196b875f27383d492798dd55a3535
7f39a223ff263dffb7ada7aca136cbc6b6041381
refs/heads/master
2023-04-07T10:11:48.457811
2023-04-01T16:07:32
2023-04-01T16:07:32
20,801,807
0
0
null
2023-01-29T14:49:10
2014-06-13T11:15:53
Java
UTF-8
Java
false
false
1,438
java
/* * Copyright(c) Zdenek Tronicek, FIT CTU in Prague. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License (CDDL). You can obtain a copy of the CDDL at * http://www.netbeans.org/cddl.html. * */ package jascut.xml; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * The JAXB class that represents an argument of method call. * * @author tronicek */ @XmlType(name = "arg", propOrder = {"ref", "name", "type", "value"}) public class ArgumentXml { private Integer ref; private String name; private String type; private ArgumentValueXml value; public ArgumentXml() { } @XmlElement(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlAttribute(name = "ref") public Integer getRef() { return ref; } public void setRef(Integer ref) { this.ref = ref; } @XmlElement(name = "type") public String getType() { return type; } public void setType(String type) { this.type = type; } @XmlElement(name = "value") public ArgumentValueXml getValue() { return value; } public void setValue(ArgumentValueXml value) { this.value = value; } }
8f5ff94f7fdaa91bfae15af2ea79a5d68b9bcf90
25de7355e1fd741e5d8f50f9a13a9afc99222fab
/SeleccionFutbol/src/modelo/Persona.java
8f09d7e6c972f2078420afe2cb47448df65f8391
[]
no_license
Developer85/Cursos
28d6b2988e912aa97b5cec79b14bd7542a4298a7
f3864b220bc64aef81e4848565aadc2679e45098
refs/heads/master
2021-01-17T06:44:44.502588
2016-06-15T18:57:23
2016-06-15T18:57:23
61,227,451
0
0
null
null
null
null
UTF-8
Java
false
false
2,879
java
/* * Clase Padre de Entrenador y Jugador */ package modelo; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.util.Date; import java.util.Objects; /** * * @author mfontana */ public class Persona implements Serializable, Comparable { private String nombre; private String nacionalidad; private Date nacimiento; public static final String PROP_NOMBRE = "nombre"; public static final String PROP_NACIONALIDAD = "nacionalidad"; public static final String PROP_NACIMIENTO = "nacimiento"; private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public Persona() { nombre = ""; nacionalidad = ""; nacimiento = new Date(); } @Override public int hashCode() { int hash = 7; hash = 37 * hash + Objects.hashCode(this.nombre); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Persona other = (Persona) obj; return nombre.equalsIgnoreCase(other.getNombre()); } @Override public int compareTo(Object o) { Persona p = (Persona) o; return this.nombre.compareTo(p.getNombre()); } @Override public String toString() { return nombre; } public String getNombre() { return nombre; } public void setNombre(String nombre) { String oldNombre = this.nombre; this.nombre = nombre; propertyChangeSupport.firePropertyChange(PROP_NOMBRE, oldNombre, nombre); } public String getNacionalidad() { return nacionalidad; } public void setNacionalidad(String nacionalidad) { String oldNacionalidad = this.nacionalidad; this.nacionalidad = nacionalidad; propertyChangeSupport.firePropertyChange(PROP_NACIONALIDAD, oldNacionalidad, nacionalidad); } public Date getNacimiento() { return nacimiento; } public void setNacimiento(Date nacimiento) { Date oldNacimiento = this.nacimiento; this.nacimiento = nacimiento; propertyChangeSupport.firePropertyChange(PROP_NACIMIENTO, oldNacimiento, nacimiento); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } }
[ "usuari@DebianPC" ]
usuari@DebianPC
38aad29c3fb6e85033938db8c4885f7263a49ce1
e08a57885cb3a7f09b631e116ddb8dbbb9e454ff
/app/src/main/java/com/weique/overhaul/v2/mvp/model/entity/ContradictionItemBean.java
8114ae4a4aae8cb19c050a7414245b2cb3c3d552
[ "Apache-2.0" ]
permissive
coypanglei/zongzhi
b3fbdb3bb283778b49cba1e56b9955fd19dc17d4
bc31d496533a342f0b6804ad6f7dc81c7314690b
refs/heads/main
2023-02-28T07:20:18.249292
2021-02-07T07:04:17
2021-02-07T07:04:17
336,143,136
0
1
null
null
null
null
UTF-8
Java
false
false
4,029
java
package com.weique.overhaul.v2.mvp.model.entity; import java.util.List; /** * @author GreatKing */ public class ContradictionItemBean { /** * pageCount : 1 * list : [{"Id":"817820a8-d1e1-495d-b9ff-44ed40e744a8","STANDARDADDRESSID":"8397accf-797e-40bb-9bce-184597ab9176","Address":"御山雅苑网格","Code":"MDD000003","EnumResolveType":0,"FullPath":"御山雅苑网格","Memo":"哈哈","Time":"2020/01/03 14:04","EnumCAEventOrderSaveStatus":1},{"Id":"a03a0237-2c30-41be-88e6-4974ba88dc7f","STANDARDADDRESSID":"7be40274-924a-4d3e-9799-1c55644e0eb9","Address":"静香园","Code":"MDD000002","EnumResolveType":1,"FullPath":"静香园","Memo":"打架","Time":"2020/01/03 13:49","EnumCAEventOrderSaveStatus":1},{"Id":"39c8d95a-58a2-4a0f-b13d-c4ce44f59df0","STANDARDADDRESSID":"8397accf-797e-40bb-9bce-184597ab9176","Address":"御山雅苑网格","Code":"MDD000001","EnumResolveType":0,"FullPath":"御山雅苑网格","Memo":"21212","Time":"2020/01/03 10:37","EnumCAEventOrderSaveStatus":1}] */ private int pageCount; private List<ListBean> list; public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * Id : 817820a8-d1e1-495d-b9ff-44ed40e744a8 * STANDARDADDRESSID : 8397accf-797e-40bb-9bce-184597ab9176 * Address : 御山雅苑网格 * Code : MDD000003 * EnumResolveType : 0 * FullPath : 御山雅苑网格 * Memo : 哈哈 * Time : 2020/01/03 14:04 * EnumCAEventOrderSaveStatus : 1 */ private String Id; private String StandardAddressId; private String Address; private String Code; private int EnumResolveType; private String FullPath; private String Memo; private String Time; private int EnumCAEventOrderSaveStatus; private String PointsInJSON; public String getPointsInJSON() { return PointsInJSON; } public void setPointsInJSON(String pointsInJSON) { PointsInJSON = pointsInJSON; } public String getId() { return Id; } public void setId(String Id) { this.Id = Id; } public String getStandardAddressId() { return StandardAddressId; } public void setStandardAddressId(String StandardAddressId) { this.StandardAddressId = StandardAddressId; } public String getAddress() { return Address; } public void setAddress(String Address) { this.Address = Address; } public String getCode() { return Code; } public void setCode(String Code) { this.Code = Code; } public int getEnumResolveType() { return EnumResolveType; } public void setEnumResolveType(int EnumResolveType) { this.EnumResolveType = EnumResolveType; } public String getFullPath() { return FullPath; } public void setFullPath(String FullPath) { this.FullPath = FullPath; } public String getMemo() { return Memo; } public void setMemo(String Memo) { this.Memo = Memo; } public String getTime() { return Time; } public void setTime(String Time) { this.Time = Time; } public int getEnumCAEventOrderSaveStatus() { return EnumCAEventOrderSaveStatus; } public void setEnumCAEventOrderSaveStatus(int EnumCAEventOrderSaveStatus) { this.EnumCAEventOrderSaveStatus = EnumCAEventOrderSaveStatus; } } }
2c071840dbc01dca72862ae5aba24d6aca2e4441
9b45ff5d545aa9eda394ed4255b0962d55931827
/Selenium/src/Package/JavaTutorial/InterfaceExampleTwo.java
555abd515b83f59f8a63a262d228afe0bd62242c
[]
no_license
anand16/Download_Classes_V1
b5987d4a8aaa51901db2323473d167913bf1eb3f
706c611731edc3db8cf736d5ad321af56cab1637
refs/heads/master
2020-12-25T14:38:58.468057
2016-07-30T13:12:53
2016-07-30T13:12:53
64,544,854
0
0
null
null
null
null
UTF-8
Java
false
false
710
java
package Package.JavaTutorial; interface HumanEyes{ void EyesCount(); } interface HumanLegs{ void LegCount(); } class Actions implements HumanEyes,HumanLegs{ public void LegCount() { // TODO Auto-generated method stub System.out.println("2"); } public void EyesCount() { // TODO Auto-generated method stub System.out.println("2"); } } /*class C7 implements Printable,Showable{ public void print(){System.out.println("Hello");} public void show(){System.out.println("Welcome");} */ public class InterfaceExampleTwo { public static void main(String[] args) { // TODO Auto-generated method stub Actions c2=new Actions(); c2.EyesCount(); c2.LegCount(); } }
e1e0c5b5308819031f7c3903569fff1a85e56d41
999a5e33d8f4ac263b796c135e463bfa8c96fda2
/src/me/kernelfreeze/uhc/cmds/StartGameCMD.java
246f62b428c942b7164677de84838c798a59db0f
[]
no_license
foxkdev/UHC
f29e26ec854b04ac5f703497cc0d3a91aab3db7d
0c11e2985a48efd0cf2104c2b92b2c2cee55c448
refs/heads/master
2021-06-16T03:45:47.464804
2017-05-03T01:51:54
2017-05-03T01:52:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,007
java
package me.kernelfreeze.uhc.cmds; import me.kernelfreeze.uhc.UHC; import me.kernelfreeze.uhc.game.GRunnable; import me.kernelfreeze.uhc.game.GameManager; import me.kernelfreeze.uhc.game.ScoreboardM; import me.kernelfreeze.uhc.scenarios.ScenarioManager; import me.kernelfreeze.uhc.teams.TeamManager; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; public class StartGameCMD implements CommandExecutor { private final GameManager gameManager; private int i; private int an; public StartGameCMD() { this.gameManager = GameManager.getGameManager(); this.an = 300; } public boolean onCommand(final CommandSender commandSender, final Command command, final String s, final String[] array) { if (!commandSender.hasPermission("uhc.start") && !this.gameManager.getHostName().equalsIgnoreCase(commandSender.getName())) { commandSender.sendMessage("§cNo Permission!"); return true; } if (this.gameManager.isScattering() || this.gameManager.isGameRunning()) { commandSender.sendMessage("§cA UHC is already running!"); return true; } commandSender.sendMessage("§aStarting UHC..."); if (ScenarioManager.getInstance().getScenarioExact("RiskyRetrieval").isEnabled()) { this.gameManager.getUHCWorld().getHighestBlockAt(0, 0).getLocation().add(0.0, 1.0, 0.0).getBlock().setType(Material.ENDER_CHEST); } for (Player p : Bukkit.getServer().getOnlinePlayers()) { p.setWhitelisted(true); } this.start(); commandSender.sendMessage("§aScatter started..."); return false; } private void start() { this.gameManager.setCanBorderShrink(true); this.gameManager.setScattering(true); if (TeamManager.getInstance().isTeamsEnabled()) { TeamManager.getInstance().autoPlace(); } final ArrayList<Player> list = new ArrayList<Player>(); for (final Player player : this.gameManager.getSpawnLocation().getWorld().getPlayers()) { if (player != null && !this.gameManager.getModerators().contains(player)) { list.add(player); } } this.i = list.size() - 1; Bukkit.broadcastMessage(this.gameManager.getPrefix() + this.gameManager.getMainColor() + "UHC starts in " + this.startsIn(this.i + 1) + " seconds!"); new BukkitRunnable() { public void run() { if (StartGameCMD.this.i < 0) { this.cancel(); StartGameCMD.this.gameManager.setWorldWasUsed(true); StartGameCMD.this.gameManager.setScattering(false); for (final Player player : Bukkit.getServer().getOnlinePlayers()) { if (player != null) { player.setFoodLevel(20); player.setLevel(0); player.setHealth(20.0); if (ScenarioManager.getInstance().getScenarioExact("GoneFishing").isEnabled() && !StartGameCMD.this.gameManager.getModerators().contains(player)) { final ItemStack itemStack = new ItemStack(Material.FISHING_ROD); itemStack.addUnsafeEnchantment(Enchantment.DURABILITY, 150); itemStack.addUnsafeEnchantment(Enchantment.LUCK, 250); player.getInventory().addItem(itemStack); player.getInventory().addItem(new ItemStack(Material.ANVIL, 64)); player.setLevel(999999); } for (PotionEffect pot : player.getActivePotionEffects()) { player.removePotionEffect(pot.getType()); } new ScoreboardM().newScoreboard(player); } } StartGameCMD.this.gameManager.getUHCWorld().setPVP(false); StartGameCMD.this.gameManager.setGameRunning(true); new GRunnable().runTaskTimerAsynchronously((Plugin) UHC.getInstance(), 20L, 20L); Bukkit.getServer().broadcastMessage(StartGameCMD.this.gameManager.getPrefix() + StartGameCMD.this.gameManager.getMainColor() + " The game has started!"); } else { StartGameCMD.this.an -= StartGameCMD.this.gameManager.getScatterTicks(); if (StartGameCMD.this.an <= 0) { StartGameCMD.this.an = 300; Bukkit.broadcastMessage(StartGameCMD.this.gameManager.getPrefix() + StartGameCMD.this.gameManager.getMainColor() + "UHC starts in " + StartGameCMD.this.startsIn(StartGameCMD.this.i + 1) + " seconds!"); } try { list.get(StartGameCMD.this.i); } catch (ArrayIndexOutOfBoundsException ex) { try { list.remove(StartGameCMD.this.i); } catch (ArrayIndexOutOfBoundsException ex2) { System.out.println("Null remove player scatter."); } } try { final Player player2 = list.get(StartGameCMD.this.i); if (player2 != null) { if (player2.getWorld().equals(StartGameCMD.this.gameManager.getSpawnLocation().getWorld())) { StartGameCMD.this.gameManager.scatterPlayer(player2); player2.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 999999, 999)); player2.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 999999, 999)); } else { list.remove(StartGameCMD.this.i); } StartGameCMD.this.i--; } } catch (ArrayIndexOutOfBoundsException ex3) { System.out.println("Null player scatter."); } } } }.runTaskTimer((Plugin) UHC.getInstance(), (long) this.gameManager.getScatterTicks(), (long) this.gameManager.getScatterTicks()); } private int startsIn(final int n) { return n * this.gameManager.getScatterTicks() / 20; } }
06210640193bbdf92db4510c15b6e9ecf86c7102
0127db3ee7e5b79045348ae8f7f282272faba496
/src/cn/xmlanno/BookDao.java
e5b3d3170ed15c4e83ba0f327280330752defaee
[]
no_license
christivin/Sspring2
2c7e16180c0d7e89aad45269ab6d3a7711bcc9c5
ca75b05d1181b8a50ebdcfb78a03c2b6dbcabd9f
refs/heads/master
2020-03-09T22:03:32.063862
2018-04-28T00:27:00
2018-04-28T00:27:00
129,025,734
0
0
null
null
null
null
UTF-8
Java
false
false
214
java
package cn.xmlanno; import org.springframework.stereotype.Component; /** * Created by Sheng on 2018/4/11. */ public class BookDao { public void book(){ System.out.println("BookDao....."); } }
e312fa51223c4eb8d74701c8aacc4521f3dd6c77
8458751f4ec92e6c1481aa2122fb166339a736bf
/project-pattern/02-Singleton/src/port/IConnection.java
c98172ff5d0361daca1bc427b7c2be8683b49e59
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
caiolucena/geeklab
d28cf1e870a7405c53ad972aef595f379df1a960
3cd76177c317e1af2080836e25f98c153b38795b
refs/heads/master
2023-02-21T23:09:12.433843
2021-01-28T01:11:44
2021-01-28T01:11:44
310,440,887
1
0
null
null
null
null
UTF-8
Java
false
false
135
java
package port; public interface IConnection { public void connect(); public boolean isConnected(); public void disconnect(); }
91cd70cd525e102c2707380db3f7a95103e7e3d8
df87a2294de003216de9a404c1e17d217699bac5
/src/main/java/cn/aysst/bghcs/serviceImpl/UserServiceImpl.java
834715cbdb6e0ec16ae160efc9b4f548505ad7d3
[]
no_license
mengmalgz/bghcs
918dd2bf327c5e39ef843e0f35cb9bc4d9cad03f
e2d53e30d949539dc05f7c983a450a258e94db6c
refs/heads/master
2022-03-30T10:25:31.076262
2019-12-26T01:27:47
2019-12-26T01:27:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
872
java
package cn.aysst.bghcs.serviceImpl; import cn.aysst.bghcs.dao.UserDao; import cn.aysst.bghcs.entity.User; import cn.aysst.bghcs.service.UserService; import cn.aysst.bghcs.util.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; /** * @author lcy * @version 2019-12-9 */ @Component public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Override public String insertUser(User user) { return userDao.insertUser(user); } @Override public String checkOpenId(String userOpenId) { return userDao.checkOpenId(userOpenId); } @Override public List<Map> getCheckInfo(String userOpenId, String imageUrl) { return userDao.getCheckInfo(userOpenId, imageUrl); } }
3729d73b322fc3e75f387c2ded09e5fb1df0d416
00996f7110e39861b6e07a026832a70e3e7e85e4
/labs/sem1/bank/Runner.java
18b78b1a02d2e74b16823eb8bff36e19752ae9d8
[]
no_license
arjunpat/adv-comp-sci
f26decf7c65913d263b0f05428e16fa10cbb7689
c29c0171cc3243a1c0adb3ee4b889fc8320cc604
refs/heads/master
2021-07-10T20:20:45.319388
2020-01-23T08:18:57
2020-01-23T08:18:57
145,757,313
0
0
null
null
null
null
UTF-8
Java
false
false
279
java
import javax.swing.JFrame; public class Runner { public static void main(String[] args) { JFrame frame = new JFrame("Bank"); Screen sc = new Screen(); frame.add(sc); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
8a949ceadb1ec9f42deba391db909e88a12d2b4b
013e83b707fe5cd48f58af61e392e3820d370c36
/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionValidationException.java
7c2de76e42a8496970a8b274b98749036fbd364a
[]
no_license
yuexiaoguang/spring4
8376f551fefd33206adc3e04bc58d6d32a825c37
95ea25bbf46ee7bad48307e41dcd027f1a0c67ae
refs/heads/master
2020-05-27T20:27:54.768860
2019-09-02T03:39:57
2019-09-02T03:39:57
188,770,867
0
1
null
null
null
null
UTF-8
Java
false
false
435
java
package org.springframework.beans.factory.support; import org.springframework.beans.FatalBeanException; /** * 当bean定义的验证失败时抛出. */ @SuppressWarnings("serial") public class BeanDefinitionValidationException extends FatalBeanException { public BeanDefinitionValidationException(String msg) { super(msg); } public BeanDefinitionValidationException(String msg, Throwable cause) { super(msg, cause); } }
e06b8d440ea4cbd9580640bb8de8b327dd8459f9
cbcba2664f9e81dcd71ef7d3ccdcefa89021ffb0
/alumni/alumni-common/src/main/java/com/wisdombud/alumni/vo/RemindVo.java
30012100f91b94789e402be437e3b2800c429cac
[]
no_license
NumberFairy/test
123d024280587c847bc402398d4853c1c16dcd08
0fac3117a8f44b5fcae210b5b1e8fdf27ef0c528
refs/heads/master
2021-04-12T10:31:42.041939
2017-06-16T10:18:44
2017-06-16T10:18:44
94,532,190
0
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.wisdombud.alumni.vo; import java.util.Date; /** * @DES 办工桌提醒事件 * @author xiefei */ public class RemindVo { public static final Integer ALUMNI_BIRTH = 0; public static final Integer ALUMNI_ACTIVE = 1; private String id; private Date time; // 时间 private String title; // 标题 private Integer type; // 类型 public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
b20073c7a9b99094b090e9c4a2208bd0893d2f7e
65a6345a544888bcbdbc5c04aa4942a3c201e219
/src/main/java/mayday/wapiti/experiments/generic/mapping/csv/GenericMappingImporter.java
0f99ce4f8732f02ae369506be9d4e0ec040239cf
[]
no_license
Integrative-Transcriptomics/Mayday-level2
e7dd61ba68d149bed845b173cced4db012ba55b1
46a28829e8ead11794951fbae6d61e7ff37cad4a
refs/heads/master
2023-01-11T21:57:47.943395
2016-04-25T12:59:01
2016-04-25T12:59:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
11,922
java
/* * Created on 29.11.2005 */ package mayday.wapiti.experiments.generic.mapping.csv; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.text.DecimalFormat; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Map.Entry; import javax.swing.JLabel; import javax.swing.table.TableModel; import mayday.core.gui.abstractdialogs.SimpleStandardDialog; import mayday.core.gui.columnparse.ColumnTypeDialog; import mayday.core.io.csv.CSVImportSettingComponent; import mayday.core.io.csv.ParsedLine; import mayday.core.io.csv.ParserSettings; import mayday.core.pluma.PluginInfo; import mayday.core.pluma.PluginManagerException; import mayday.core.settings.Setting; import mayday.core.settings.SettingDialog; import mayday.core.settings.generic.ComponentPlaceHolderSetting; import mayday.core.settings.generic.HierarchicalSetting; import mayday.core.settings.typed.BooleanSetting; import mayday.core.structures.maps.MultiHashMap; import mayday.core.tasks.AbstractTask; import mayday.core.tasks.TaskStateEvent; import mayday.genetics.advanced.VariableGeneticCoordinate; import mayday.genetics.basic.ChromosomeSetContainer; import mayday.genetics.importer.DefaultLocusSetting; import mayday.genetics.importer.SelectableDefaultLocusSetting; import mayday.wapiti.experiments.base.Experiment; import mayday.wapiti.experiments.generic.mapping.AbstractMappingImportPlugin; import mayday.wapiti.experiments.generic.mapping.MappingData; import mayday.wapiti.experiments.generic.mapping.MappingExperiment; import mayday.wapiti.experiments.generic.mapping.csv.MappingColumnTypes.CTYPE; import mayday.wapiti.transformations.matrix.TransMatrix; public class GenericMappingImporter<DialogType extends ColumnTypeDialog<MappingColumnTypes>> extends AbstractMappingImportPlugin { protected HierarchicalSetting mySetting; protected BooleanSetting eachFileAlone; public GenericMappingImporter() { super(true, false); } public Setting getSetting() { if (mySetting == null) { eachFileAlone = new BooleanSetting("One experiment per file","Alternative: All files are one experiment",false); mySetting = new HierarchicalSetting("Mapping import").addSetting(super.getSetting()).addSetting(eachFileAlone); } return mySetting; } protected TableModel getTableModel(File f) { if (f==null) return null; CSVImportSettingComponent comp; try { LazyParsingTableModel lptm = new LazyParsingTableModel(f,100); comp = new CSVImportSettingComponent(lptm); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } SimpleStandardDialog dlg = new SimpleStandardDialog("Import Mapped Reads",comp,false); dlg.setVisible(true); if(!dlg.okActionsCalled()) return null; return comp.getTableModel(); } @Override public PluginInfo register() throws PluginManagerException { return new PluginInfo( this.getClass(), MC+".CSV", new String[0], MC, null, "Florian Battke", "[email protected]", "Import experiments from mapped reads files", "Mapped Reads (CSV)"); } protected class SettingsBlorb { HashMap<String,SelectableDefaultLocusSetting> fileDefaultLocus; DefaultLocusSetting defaultLocus; boolean _species; boolean _chrome; boolean _strand; boolean _length; HashMap<CTYPE, Integer> asCol; ParserSettings parserSettings; } public List<Experiment> getMappingExperiments(final List<String> files, TransMatrix transMatrix) { LinkedList<Experiment> result = new LinkedList<Experiment>(); SettingsBlorb psett = new SettingsBlorb(); if (!getParserSettings(files, psett)) return Collections.emptyList(); if (eachFileAlone.getBooleanValue()) { for (String file : files) { getMappingExperiments0(Arrays.asList(new String[]{file}), transMatrix, result, psett); } } else { getMappingExperiments0(files, transMatrix, result, psett); } return result; } protected boolean getParserSettings(List<String> files, SettingsBlorb rv) { // configure columns, but read only a few lines of the first file final TableModel tm = getTableModel(new File(files.get(0))); if (tm==null) return false; MappingColumnDialog mcd = new MappingColumnDialog(tm); mcd.setModal(true); mcd.setVisible(true); if (mcd.canceled()) return false; // check for missing columns and ask user accordingly // I need Species, Chromosome, Start, Strand, Length/End for all Set<CTYPE> foundTypes = ((MappingColumnTypeValidator)mcd.getValidator()).getTypes(); final boolean _species = foundTypes.contains(CTYPE.Species); final boolean _chrome = foundTypes.contains(CTYPE.Chromosome); final boolean _strand = foundTypes.contains(CTYPE.Strand); final boolean _length = foundTypes.contains(CTYPE.Length) || foundTypes.contains(CTYPE.To); final DefaultLocusSetting defaultLocus; final HashMap<String,SelectableDefaultLocusSetting> fileDefaultLocus = new HashMap<String,SelectableDefaultLocusSetting>(); if (!_species || !_chrome || !_strand || !_length) { HierarchicalSetting topSet = new HierarchicalSetting("Fill in missing locus information"); String istr = "<html>The input file does not contain all the needed information<br>" + "Please supply the missing information below.<br>" + (files.size()>1?"You can also supply per-file information.":""); defaultLocus = new DefaultLocusSetting(); defaultLocus.hideElements(_species, _chrome, _strand, _length); topSet.addSetting(new ComponentPlaceHolderSetting("info", new JLabel(istr))); topSet.addSetting(defaultLocus); if (files.size()>1) { HierarchicalSetting perFileLocus = new HierarchicalSetting("Per-file settings"); perFileLocus.setLayoutStyle(HierarchicalSetting.LayoutStyle.TREE); topSet.addSetting(perFileLocus); for (String f : files) { SelectableDefaultLocusSetting ns = new SelectableDefaultLocusSetting(f); ns.hideElements(_species, _chrome, _strand, _length); fileDefaultLocus.put(f,ns); perFileLocus.addSetting(ns); } } SettingDialog sd = new SettingDialog(null, "Locus completion", topSet).showAsInputDialog(); if (sd.canceled()) return false; } else { defaultLocus = null; } final HashMap<CTYPE, Integer> asCol = new HashMap<CTYPE, Integer>(); for (int i=0; i!=tm.getColumnCount(); ++i) { asCol.put(mcd.getColumnType(i), i); } ParserSettings parserSettings = ((LazyParsingTableModel)tm).getSettings(); rv.fileDefaultLocus = fileDefaultLocus; rv.defaultLocus = defaultLocus; rv._chrome = _chrome; rv._species = _species; rv._strand = _strand; rv._length = _length; rv.asCol = asCol; rv.parserSettings = parserSettings; return true; } protected List<Experiment> getMappingExperiments0( final List<String> files, TransMatrix transMatrix, LinkedList<Experiment> result, SettingsBlorb sv ) { final HashMap<String,SelectableDefaultLocusSetting> fileDefaultLocus = sv.fileDefaultLocus; final DefaultLocusSetting defaultLocus = sv.defaultLocus; final boolean _species = sv._species; final boolean _chrome = sv._chrome; final boolean _strand = sv._strand; final boolean _length = sv._length; final HashMap<CTYPE, Integer> asCol = sv.asCol; final ParserSettings parserSettings = sv.parserSettings; // parse the files with the given settings, line per line, use locus completion final MappingData md = new MappingData(); AbstractTask parserTask = new AbstractTask("Parsing mapped reads") { @Override protected void doWork() throws Exception { ChromosomeSetContainer csc=new ChromosomeSetContainer(); VariableGeneticCoordinate tmp = new VariableGeneticCoordinate(csc); for (int i=0; i!=files.size(); ++i) { int perc = (i*10000) / files.size(); String progresstext = "Parsing file "+new File(files.get(i)).getName(); this.setProgress(perc, progresstext); // build the default locus HashMap<CTYPE, Object> ret = new MultiHashMap<CTYPE, Object>(); SelectableDefaultLocusSetting sdls = fileDefaultLocus.get(files.get(i)); if (defaultLocus!=null) { if (!_length) { if (sdls!=null && sdls.overrideLength()) ret.put(CTYPE.Length, sdls.getLength()); else ret.put(CTYPE.Length, defaultLocus.getLength()); } if (!_chrome) { if (sdls!=null && sdls.overrideChromosome()) ret.put(CTYPE.Chromosome, sdls.getChromosome()); else ret.put(CTYPE.Chromosome, defaultLocus.getChromosome()); } if (!_species) { if (sdls!=null && sdls.overrideSpecies()) ret.put(CTYPE.Species, sdls.getSpecies()); else ret.put(CTYPE.Species, defaultLocus.getSpecies()); } if (!_strand) { if (sdls!=null && sdls.overrideStrand()) ret.put(CTYPE.Strand, sdls.getStrand()); else ret.put(CTYPE.Strand, defaultLocus.getStrand()); } } for (Entry<CTYPE,Object> e : ret.entrySet()) { tmp.update(e.getKey().vgce(),e.getValue()); } // now read and add elements DecimalFormat df = new DecimalFormat("###,###,###,###,###"); ParsedLine pl = new ParsedLine("",parserSettings); String line=null; int linesParsed=0; try { BufferedReader br = new BufferedReader(new FileReader(files.get(i))); CTYPE[] colTypes = asCol.keySet().toArray(new CTYPE[0]); Integer[] colIndices = asCol.values().toArray(new Integer[0]); // skip lines before header for (int skip=0; skip!=parserSettings.skipLines; ++skip) br.readLine(); // skip header itself if (parserSettings.hasHeader) br.readLine(); // now start parsing while (br.ready()) { line = br.readLine(); pl.replaceLine(line); if (!pl.isCommentLine()) { tmp.setFrom(-1); tmp.setTo(-1); for (int k=0; k!=colIndices.length; ++k) { if (colTypes[k]!=null) tmp.update(colTypes[k].vgce(), pl.getOptimized(colIndices[k])); } md.addRead(tmp); linesParsed++; } if (linesParsed % 10000 == 0) { this.setProgress(perc, progresstext+": " +df.format(linesParsed)+" reads, " +df.format(md.getReadCount())+" total"); if (hasBeenCancelled()) { setTaskState(TaskStateEvent.TASK_CANCELLED); return; } } } } catch (Exception e) { RuntimeException rte = new RuntimeException("Could not parse reads from "+files.get(i)+"\nLine number: "+(linesParsed+1)+"\nLine content: "+line, e); throw rte; } } md.compact(); setProgress(10000,""); } @Override protected void initialize() { } }; long t1 = System.currentTimeMillis(); parserTask.start(); parserTask.waitFor(); long t2 = System.currentTimeMillis(); System.out.println("Parsed reads in "+(t2-t1)+" ms"); if (parserTask.getTaskState()!=TaskStateEvent.TASK_FINISHED) return Collections.emptyList(); String names; if (files.size()==1) names = new File(files.get(0)).getName(); else { names = files.size()+" files ("+new File(files.get(0)).getName(); for (int i=1; i!=files.size(); ++i) names+=", "+files.get(i); if (names.length()>45) names = names.substring(0, 42)+"..."; names += ")"; } String suggestedName = new File(files.get(0)).getName(); if (suggestedName.contains(".")) suggestedName = suggestedName.substring(0, suggestedName.lastIndexOf('.')); MappingExperiment me = new MappingExperiment(suggestedName,"Reads from "+names,transMatrix); me.setInitialData(md); result.add(me); return result; } }
2efc467e90574d9800ca49baa0938b7ef7659b5e
9b0567a5db5d377c92f0397310ef64501357e9cd
/src/com/programmers/study/CollatzGuess.java
779921c775d35adfa6d05fad1c31cd2921424800
[]
no_license
2dh2wdk/programmersStudy
3d4a5b368bf414efb0e6adcbf2ee31d880dbfd39
ef6b6cb026367e05c161181665911523cb5fa263
refs/heads/main
2023-07-05T04:06:36.434720
2021-08-31T08:57:35
2021-08-31T08:57:35
385,146,704
0
0
null
null
null
null
UTF-8
Java
false
false
773
java
package com.programmers.study; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CollatzGuess { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(solution(Integer.parseInt(br.readLine()))); br.close(); } public static int solution(long num) { int answer = 0; while(num!=1) { if(num%2==0) { num/=2; answer++; } else { num=num*3+1; answer++; } System.out.println(num); if(answer==500 && num!=1) { answer=-1; break; } } return answer; } }
086f0d4066400797d3645da27430441ed9b469be
1a5fd4f42a016b493ed5d7f03c2e2819a512c1be
/src/main/java/cz/sharee/backend/dto/profile/VoteDTO.java
7a8a3b2ee79a37217de8ef92a4474b80b64d954c
[ "MIT" ]
permissive
sharee-app/veverka-backend
81135b9a7ca2e45736fd6858138192eb16952825
1a9c79361b5e1baf2ee482eb31542625c29c53e5
refs/heads/main
2023-02-28T19:29:48.177846
2021-02-04T22:05:17
2021-02-04T22:05:17
282,027,410
0
0
null
null
null
null
UTF-8
Java
false
false
231
java
package cz.sharee.backend.dto.profile; import lombok.Getter; import lombok.Setter; @Getter @Setter public class VoteDTO { private Long id; private Boolean value; private UserDTO user; private PostDTO votedPost; }
7fae2eef2f4c6eae1e86d5308ff1925a6554a69f
6d08aac3915ca5f7bd2911bf2044811a6fa6dd48
/camp/src/exam3/mazepath2.java
4059296dac5a9c073fff2969477ed060577eba3c
[]
no_license
catherinecho/USACO
e0543f72f92563793fba284306695e591f4d45bd
133d3afde94f5be9ddd9d859b46e490bba06759c
refs/heads/master
2020-06-01T21:15:33.190296
2020-04-01T18:43:33
2020-04-01T18:43:33
190,306,204
0
0
null
null
null
null
UTF-8
Java
false
false
1,803
java
package exam3; import java.util.*; public class mazepath2 { static Scanner in = new Scanner(System.in); static int n = in.nextInt(); static int[][] grid = new int[n][n]; static String ans = ""; static int end = 0; static int[] dr = {0,0,-1,1}; static int[] dc = {1, -1, 0,0}; public static void main(String[] args) { for(int i = 0;i < n; i++) { for(int j = 0; j < n; j++) { grid[i][j] = in.nextInt(); if(i == n-1 && j == n-1) { end = grid[i][j]; } } } for(int i = 0; i< n; i++) { for(int j = 0; j < n; j++ ) { } } path(0, 0); for(int i = 0; i < ans.length(); i++) { System.out.println(ans.charAt(i)); } } public static void path(int x, int y) { Queue <m> q = new LinkedList<m>(); q.add(new m(x, y)); int a = grid[x][y]; grid[x][y] = 0; while(!q.isEmpty()) { m cur = q.remove(); if(grid[cur.x][cur.y] == end) { return; } for(int i = 0; i < 4; i++) { int nr = cur.x+ dr[i]; int nc = cur.y + dc[i]; if(valid(nr,nc) && gcd(a, grid[nr][nc]) == 1 ) { System.out.println(grid[nr][nc]); if(dr[i] == 0 && dc[i] == 1) { ans += "L"; }else if(dr[i] == -1 && dc[i] == 0) { ans+="U"; }else if (dr[i] == 1 && dc[i] == 0) { ans+="D"; }else { ans+= "R"; } a= grid[nr][nc]; grid[nr][nc] = 0; q.add(new m(nr,nc)); break; } } } } public static int gcd(int x, int y) { if(y == 0) { return x; } return gcd(y, x%y); } public static boolean valid(int nr, int nc) { if(nr <0 || nc < 0 || nr >= n || nc >= n) { return false; }else if(grid[nr][nc] == 0) { return false; } return true; } } class m{ int x; int y; public m(int X, int Y) { this.x = X; this.y = Y; } }
bd1439b3301cbd282992b57ae0ecd29de246a874
5cad59b093f6be43057e15754ad0edd101ed4f67
/src/Interview/Google/Array/NextClosestTime.java
a153564509c360639918699d8b9673ea41f933e3
[]
no_license
GeeKoders/Algorithm
fe7e58687bbbca307e027558f6a1b4907ee338db
fe5c2fca66017b0a278ee12eaf8107c79aef2a14
refs/heads/master
2023-04-01T16:31:50.820152
2021-04-21T23:55:31
2021-04-21T23:55:31
276,102,037
0
0
null
null
null
null
UTF-8
Java
false
false
1,212
java
package Interview.Google.Array; public class NextClosestTime { /* * 681. Next Closest Time (Medium) * * https://leetcode.com/problems/next-closest-time/ * * solution: https://leetcode.com/problems/next-closest-time/solution/ * * reference: * * https://www.youtube.com/watch?v=YYtQrH-aPXI&ab_channel=sheetalnikam * * Runtime: 34 ms, faster than 5.22% of Java online submissions for Next Closest Time. * * Memory Usage: 39.7 MB, less than 6.23% of Java online submissions for Next Closest Time. * * Time complexity: Time Complexity: O(1)O(1). We try up to 24 * 60 possible times until we find the correct time. e.g.: 00:00 -> 00:00 * Space complexity: O(1) * */ public String nextClosestTime(String time) { int hour = Integer.parseInt(time.substring(0, 2)); int mins = Integer.parseInt(time.substring(3)); while (true) { if (++mins == 60) { mins = 0; hour++; hour %= 24; } String curr = String.format("%02d:%02d", hour, mins); boolean isValid = true; for (int i = 0; i < curr.length(); i++) { if (time.indexOf(curr.charAt(i)) < 0) { isValid = false; break; } } if (isValid) return curr; } } }
23040ab839d014bfb04094b1ec0612f4c9c57ff6
b583a5ce252b8ecdabef2e35a56be5e4563542c3
/src/com/app/example/baidutranslateapp/bean/trans_result.java
6d2c29ddcc6f7aa2a156efccf0fe50338731218c
[]
no_license
lishenshang/BaiduTranslate
6bec9cf3f879c5c27f4b30043aaf070bd0c71910
fe1db8d164d31910cc1803d406bd83e1b1d57192
refs/heads/master
2021-01-19T03:48:24.391289
2016-07-06T09:03:29
2016-07-06T09:03:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package com.app.example.baidutranslateapp.bean; public class trans_result { String src; String dst; public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public String getDst() { return dst; } public void setDst(String dst) { this.dst = dst; } }
c925dfc31a944e351a0d01cad23aaab26917d9df
ce4226d5d869625648f3c9f67e8d3bac222cc59a
/app/src/main/java/app/amrelmasry/capstone_project/features/notes/ToolbarPhotoAsyncTask.java
d3eb9c180b02ffa09c485cd10a247f3a7e35c3c2
[]
no_license
AmrElmasry/Capstone-Project
815b5165de079ac0528c89fe4210c87e2fdf5011
4e2d7cd24e339454af722ccf7f25413fb87e4a86
refs/heads/master
2021-01-20T13:21:49.679017
2017-05-14T21:36:41
2017-05-14T21:36:41
90,476,695
0
0
null
null
null
null
UTF-8
Java
false
false
1,497
java
package app.amrelmasry.capstone_project.features.notes; import android.os.AsyncTask; import android.text.TextUtils; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.io.IOException; import java.lang.ref.WeakReference; import app.amrelmasry.capstone_project.common.DataManager; import app.amrelmasry.capstone_project.common.model.PhotosResponse; import retrofit2.Call; /** * Created by Amr on 14/05/17. */ public class ToolbarPhotoAsyncTask extends AsyncTask<Void, Void, String> { private WeakReference<ImageView> imageView; public ToolbarPhotoAsyncTask(ImageView imageView) { this.imageView = new WeakReference<>(imageView); } @Override protected String doInBackground(Void... params) { Call<PhotosResponse> call = DataManager.getRestApi().getInspirationalPhotos(); PhotosResponse photosResponse; try { photosResponse = call.execute().body(); String image_url = photosResponse.getPhotos().get(0).getImage_url(); if (TextUtils.isEmpty(image_url)) { return null; } return image_url; } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String url) { ImageView imageView = this.imageView.get(); if (imageView != null) { Picasso.with(imageView.getContext()).load(url).into(imageView); } } }