blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f343fa26a1bfe4dcc43a8e49ecccd4c8755749e
| 30,794,915,576,211 |
e6d73a033b444c02ff0cbb37cf30bfb4ebebebf4
|
/src/main/java/com/demo/gof/simpleFactory/ChineseFood.java
|
73e9f53a36b61aafd70b811b962b40e67062afb3
|
[] |
no_license
|
k292112/springboot-demo
|
https://github.com/k292112/springboot-demo
|
c5860871a5ce316ef9758f691971fc6581504874
|
601266f314db6794f98f9dcd166b477c8e7fc6b6
|
refs/heads/master
| 2022-12-26T11:59:48.993000 | 2020-09-29T10:40:26 | 2020-09-29T10:40:26 | 297,017,586 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.gof.simpleFactory;
public class ChineseFood implements Food{
@Override
public void disc() {
System.out.println("中国食物!!!");
}
public ChineseFood() {
System.out.println("中国食物!!!");
}
}
|
UTF-8
|
Java
| 267 |
java
|
ChineseFood.java
|
Java
|
[] | null |
[] |
package com.demo.gof.simpleFactory;
public class ChineseFood implements Food{
@Override
public void disc() {
System.out.println("中国食物!!!");
}
public ChineseFood() {
System.out.println("中国食物!!!");
}
}
| 267 | 0.606695 | 0.606695 | 13 | 17.384615 | 16.021805 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false |
7
|
25171b3f90a2e9a3a372ffb6c52ea8c51b20ad15
| 38,697,655,363,425 |
4fc219fdd92c9a32722a9eb99b8939f8082c12e3
|
/src/main/java/ru/tehcode/permissions/bukkit/PermissionUser.java
|
7fb3d4252e763344cc1ef384daa76eccadae7999
|
[
"WTFPL"
] |
permissive
|
rymate1234/PermissionsEXBridge
|
https://github.com/rymate1234/PermissionsEXBridge
|
e160b9952880ef3c8e13cffb3ed6dd9b79b23fdf
|
59768e9e646444b87cb1e6b78c3132960d46db0d
|
refs/heads/master
| 2021-01-01T17:00:31.774000 | 2012-06-08T17:20:29 | 2012-06-08T17:20:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* PermissionsEXBridge by rymate1234 (http://ryate.co.uk)
*
* THIS PLUGIN IS LICENSED UNDER THE WTFPL - (Do What The Fuck You Want To Public License)
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
package ru.tehcode.permissions.bukkit;
import org.bukkit.entity.Player;
/**
*
* @author Ryan
*/
public class PermissionUser {
Player player;
public PermissionUser(Player player) {
this.player = player;
}
}
|
UTF-8
|
Java
| 850 |
java
|
PermissionUser.java
|
Java
|
[
{
"context": "/*\n * PermissionsEXBridge by rymate1234 (http://ryate.co.uk)\n *\n * THIS PLUGIN IS LICENSE",
"end": 39,
"score": 0.9996978044509888,
"start": 29,
"tag": "USERNAME",
"value": "rymate1234"
},
{
"context": "mport org.bukkit.entity.Player;\n\n/**\n *\n * @author Ryan\n */\npublic class PermissionUser {\n Player play",
"end": 704,
"score": 0.9996957778930664,
"start": 700,
"tag": "NAME",
"value": "Ryan"
}
] | null |
[] |
/*
* PermissionsEXBridge by rymate1234 (http://ryate.co.uk)
*
* THIS PLUGIN IS LICENSED UNDER THE WTFPL - (Do What The Fuck You Want To Public License)
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
package ru.tehcode.permissions.bukkit;
import org.bukkit.entity.Player;
/**
*
* @author Ryan
*/
public class PermissionUser {
Player player;
public PermissionUser(Player player) {
this.player = player;
}
}
| 850 | 0.701176 | 0.694118 | 34 | 24 | 27.189964 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | false | false |
7
|
ef16ef17dbd9e61146001148399946ef71ff428a
| 38,354,057,986,004 |
eb916fd9e872e6bd13c39e0d79c5f79866797080
|
/cougar-framework/cougar-api/src/main/java/com/betfair/cougar/api/security/IdentityResolver.java
|
13def447f7fc5f74cf62d4d76dbdac0630aaad03
|
[
"Apache-2.0"
] |
permissive
|
betfair/cougar
|
https://github.com/betfair/cougar
|
c4cb227024402a19da217150b99f7d73d75d7cce
|
08d1fe338fbd0e8572a9c2305bb5796402d5b1f5
|
refs/heads/master
| 2023-08-26T16:44:20.538000 | 2016-03-21T15:10:27 | 2016-03-21T15:10:27 | 13,865,967 | 21 | 12 |
Apache-2.0
| false | 2022-10-03T22:39:04 | 2013-10-25T16:30:18 | 2022-07-11T13:27:04 | 2022-09-09T03:00:46 | 49,594 | 28 | 21 | 40 |
Java
| false | false |
/*
* Copyright 2014, The Sporting Exchange Limited
*
* 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.betfair.cougar.api.security;
import com.betfair.cougar.api.DehydratedExecutionContext;
import java.util.List;
/**
* The IdentityResolver resolves a set of credentials into an IdentityChain.
*
* @see IdentityChain
*
*/
public interface IdentityResolver {
/**
* Given a set of credentials, resolves those credentials into
* an IdentityChain. The identity chain to add the result(s) to is passed in.
* @param chain the identity chain to add resolved identities to
* @param ctx the execution context resolved so far including identity tokens resolved by the {@link IdentityTokenResolver} (IdentityChain on this context will be null).
* @throws InvalidCredentialsException
*/
public void resolve(IdentityChain chain, DehydratedExecutionContext ctx) throws InvalidCredentialsException;
/**
* Given an identity chain, resolve back into a set of writable tokens
* @param chain an identity chain
* @return a list of tokens that may be written, which may be null.
* @throws InvalidCredentialsException
*/
public List<IdentityToken> tokenise(IdentityChain chain);
}
|
UTF-8
|
Java
| 1,763 |
java
|
IdentityResolver.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2014, The Sporting Exchange Limited
*
* 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.betfair.cougar.api.security;
import com.betfair.cougar.api.DehydratedExecutionContext;
import java.util.List;
/**
* The IdentityResolver resolves a set of credentials into an IdentityChain.
*
* @see IdentityChain
*
*/
public interface IdentityResolver {
/**
* Given a set of credentials, resolves those credentials into
* an IdentityChain. The identity chain to add the result(s) to is passed in.
* @param chain the identity chain to add resolved identities to
* @param ctx the execution context resolved so far including identity tokens resolved by the {@link IdentityTokenResolver} (IdentityChain on this context will be null).
* @throws InvalidCredentialsException
*/
public void resolve(IdentityChain chain, DehydratedExecutionContext ctx) throws InvalidCredentialsException;
/**
* Given an identity chain, resolve back into a set of writable tokens
* @param chain an identity chain
* @return a list of tokens that may be written, which may be null.
* @throws InvalidCredentialsException
*/
public List<IdentityToken> tokenise(IdentityChain chain);
}
| 1,763 | 0.740216 | 0.735678 | 47 | 36.510639 | 36.893101 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.319149 | false | false |
7
|
366f573d90b484d68f6887b9fdd3865e57bb5c73
| 11,888,469,510,952 |
3f9f391c3658a732ae60c3d879665897b0019b64
|
/src/main/java/objectRepositiry/ChekoutPage.java
|
1134ce21165b3d64e0e209d66411c897fad11010
|
[] |
no_license
|
ashwini7483/Work
|
https://github.com/ashwini7483/Work
|
bf89eb8c5e3812a6cc40a57fc9af5bdf296ea762
|
95127a5a282e503ef08050706964beecc69d1b56
|
refs/heads/master
| 2023-07-22T16:06:09.072000 | 2021-08-31T20:59:18 | 2021-08-31T20:59:18 | 400,753,888 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package objectRepositiry;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ChekoutPage {
public ChekoutPage(WebDriver driver) {
PageFactory.initElements(driver,this);
}
@FindBy(id="termsofservice")
private WebElement checkBox;
public WebElement getCheckBox() {
return checkBox;
}
@FindBy(id="checkout")
private WebElement checkoutButton;
@FindBy(id="BillingNewAddress_City")
private WebElement bilingCity;
@FindBy(id="BillingNewAddress_Address1")
private WebElement billingAddress;
@FindBy(id="BillingNewAddress_ZipPostalCode")
private WebElement billingZipCode;
@FindBy(id="BillingNewAddress_PhoneNumber")
private WebElement billingPhoneNumber;
@FindBy(xpath="//input[@onclick='Billing.save()']")
private WebElement billingButton;
@FindBy(xpath="//input[@onclick='Shipping.save()']")
private WebElement shippingContinueButton;
@FindBy(xpath="//input[@onclick='ShippingMethod.save()']")
private WebElement shippingMethodContinueButton;
@FindBy(xpath="//input[@onclick='PaymentMethod.save()']")
private WebElement paymentMethodcontinueButton;
@FindBy(xpath="//input[@onclick='PaymentInfo.save()']")
private WebElement paymentInfoContinueButton;
@FindBy(xpath="//input[@onclick='ConfirmOrder.save()']")
private WebElement confirmOrderButton;
@FindBy(xpath="//h1[text()='Thank you']")
private WebElement thankYouMessage;
public WebElement getCheckoutButton() {
return checkoutButton;
}
public WebElement getBilingCity() {
return bilingCity;
}
public WebElement getBillingAddress() {
return billingAddress;
}
public WebElement getBillingZipCode() {
return billingZipCode;
}
public WebElement getBillingPhoneNumber() {
return billingPhoneNumber;
}
public WebElement getBillingButton() {
return billingButton;
}
public WebElement getShippingContinueButton() {
return shippingContinueButton;
}
public WebElement getShippingMethodContinueButton() {
return shippingMethodContinueButton;
}
public WebElement getPaymentMethodcontinueButton() {
return paymentMethodcontinueButton;
}
public WebElement getPaymentInfoContinueButton() {
return paymentInfoContinueButton;
}
public WebElement getConfirmOrderButton() {
return confirmOrderButton;
}
public WebElement getThankYouMessage() {
return thankYouMessage;
}
@FindBy(xpath="//table[@class='cart']/..//a[text()='14.1-inch Laptop']")
private WebElement prodctInCart;
public WebElement getProdctInCart() {
return prodctInCart;
}
@FindBy(xpath="//input[@title='Continue']")
private WebElement billingcontinueButton;
public WebElement getBillingcontinueButton() {
return billingcontinueButton;
}
@FindBy(name="BillingNewAddress.CountryId")
private WebElement countrylistbox;
public WebElement getCountrylistbox() {
return countrylistbox;
}
}
|
UTF-8
|
Java
| 3,089 |
java
|
ChekoutPage.java
|
Java
|
[] | null |
[] |
package objectRepositiry;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ChekoutPage {
public ChekoutPage(WebDriver driver) {
PageFactory.initElements(driver,this);
}
@FindBy(id="termsofservice")
private WebElement checkBox;
public WebElement getCheckBox() {
return checkBox;
}
@FindBy(id="checkout")
private WebElement checkoutButton;
@FindBy(id="BillingNewAddress_City")
private WebElement bilingCity;
@FindBy(id="BillingNewAddress_Address1")
private WebElement billingAddress;
@FindBy(id="BillingNewAddress_ZipPostalCode")
private WebElement billingZipCode;
@FindBy(id="BillingNewAddress_PhoneNumber")
private WebElement billingPhoneNumber;
@FindBy(xpath="//input[@onclick='Billing.save()']")
private WebElement billingButton;
@FindBy(xpath="//input[@onclick='Shipping.save()']")
private WebElement shippingContinueButton;
@FindBy(xpath="//input[@onclick='ShippingMethod.save()']")
private WebElement shippingMethodContinueButton;
@FindBy(xpath="//input[@onclick='PaymentMethod.save()']")
private WebElement paymentMethodcontinueButton;
@FindBy(xpath="//input[@onclick='PaymentInfo.save()']")
private WebElement paymentInfoContinueButton;
@FindBy(xpath="//input[@onclick='ConfirmOrder.save()']")
private WebElement confirmOrderButton;
@FindBy(xpath="//h1[text()='Thank you']")
private WebElement thankYouMessage;
public WebElement getCheckoutButton() {
return checkoutButton;
}
public WebElement getBilingCity() {
return bilingCity;
}
public WebElement getBillingAddress() {
return billingAddress;
}
public WebElement getBillingZipCode() {
return billingZipCode;
}
public WebElement getBillingPhoneNumber() {
return billingPhoneNumber;
}
public WebElement getBillingButton() {
return billingButton;
}
public WebElement getShippingContinueButton() {
return shippingContinueButton;
}
public WebElement getShippingMethodContinueButton() {
return shippingMethodContinueButton;
}
public WebElement getPaymentMethodcontinueButton() {
return paymentMethodcontinueButton;
}
public WebElement getPaymentInfoContinueButton() {
return paymentInfoContinueButton;
}
public WebElement getConfirmOrderButton() {
return confirmOrderButton;
}
public WebElement getThankYouMessage() {
return thankYouMessage;
}
@FindBy(xpath="//table[@class='cart']/..//a[text()='14.1-inch Laptop']")
private WebElement prodctInCart;
public WebElement getProdctInCart() {
return prodctInCart;
}
@FindBy(xpath="//input[@title='Continue']")
private WebElement billingcontinueButton;
public WebElement getBillingcontinueButton() {
return billingcontinueButton;
}
@FindBy(name="BillingNewAddress.CountryId")
private WebElement countrylistbox;
public WebElement getCountrylistbox() {
return countrylistbox;
}
}
| 3,089 | 0.737132 | 0.735513 | 126 | 22.515873 | 20.257366 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.253968 | false | false |
7
|
a72be5f45d4c10c3aa431d9b52329bef30307b76
| 24,335,284,736,907 |
47ffc2cf36f78b08f5ea2bf996a437d558c08e1d
|
/src/top/yhj1/designpattern/strategy/stimulateduck/quackbehaviour/QuackBehaviour.java
|
dacedbee31eb9f327cb317420889f491a759b650
|
[] |
no_license
|
haijunY/design
|
https://github.com/haijunY/design
|
506655d662bb199bad4c9d980f5f605e746fcd3c
|
c2ed2e2da4cf31f5f09b75185cef4987ea160b4e
|
refs/heads/master
| 2020-03-15T03:59:30.874000 | 2018-08-09T06:09:16 | 2018-08-09T06:09:16 | 131,954,966 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package top.yhj1.designpattern.strategy.stimulateduck.quackbehaviour;
public interface QuackBehaviour {
void quack();
}
|
UTF-8
|
Java
| 127 |
java
|
QuackBehaviour.java
|
Java
|
[] | null |
[] |
package top.yhj1.designpattern.strategy.stimulateduck.quackbehaviour;
public interface QuackBehaviour {
void quack();
}
| 127 | 0.787402 | 0.779528 | 7 | 17.142857 | 24.150887 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
7
|
21005502b1157c4fdde1558e72a776b815824ebd
| 28,449,863,376,704 |
8c7a5e48a91349afd109f2e7df8036d3c0434ad2
|
/src/main/java/com/example/demo/domain/UserDemo.java
|
54918cd2f63d3de3f8e321b00dbfc7cec187c4f3
|
[] |
no_license
|
snakeeeeeeeee/shardingsphere-demo2
|
https://github.com/snakeeeeeeeee/shardingsphere-demo2
|
513341941d20227c67404f1eb531bab3cec5986e
|
584a7fcc38d9e0c77042f0ec3a180af09f2c81b0
|
refs/heads/master
| 2020-11-23T20:37:22.334000 | 2019-12-13T10:52:33 | 2019-12-13T10:52:33 | 227,811,041 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.domain;
import lombok.Data;
/**
* @version 1.0 created on 2019/12/11 16:13
*/
@Data
public class UserDemo {
private Integer id;
private String name;
}
|
UTF-8
|
Java
| 190 |
java
|
UserDemo.java
|
Java
|
[] | null |
[] |
package com.example.demo.domain;
import lombok.Data;
/**
* @version 1.0 created on 2019/12/11 16:13
*/
@Data
public class UserDemo {
private Integer id;
private String name;
}
| 190 | 0.678947 | 0.605263 | 13 | 13.615385 | 14.112397 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
7
|
0de389eeec78ac748132afe1f2b7934127f38a9a
| 9,380,208,615,640 |
fff87bb581ee26fa92f6018723700d52ad376aad
|
/src/main/java/br/com/wm/mvc/resources/FuncionariosResource.java
|
1c540d6b2ca742649a2fe570e9875be77e122b40
|
[] |
no_license
|
williammian/spring-mvc
|
https://github.com/williammian/spring-mvc
|
662be4790617ed1dac326f59fa234bc695d2b3e2
|
8119ac1988782dbed53f61ebed17991a224f47d7
|
refs/heads/master
| 2020-03-25T00:32:56.280000 | 2018-08-01T18:13:22 | 2018-08-01T18:13:22 | 143,191,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.wm.mvc.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.wm.mvc.model.Funcionario;
import br.com.wm.mvc.repository.Funcionarios;
@RestController
@RequestMapping("/api/funcionarios")
public class FuncionariosResource {
@Autowired
private Funcionarios funcionarios;
@GetMapping
public List<Funcionario> todos() {
return funcionarios.findAll();
}
@GetMapping("/{id}")
public Funcionario buscar(@PathVariable Long id) {
return funcionarios.findOne(id);
}
}
|
UTF-8
|
Java
| 829 |
java
|
FuncionariosResource.java
|
Java
|
[] | null |
[] |
package br.com.wm.mvc.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.wm.mvc.model.Funcionario;
import br.com.wm.mvc.repository.Funcionarios;
@RestController
@RequestMapping("/api/funcionarios")
public class FuncionariosResource {
@Autowired
private Funcionarios funcionarios;
@GetMapping
public List<Funcionario> todos() {
return funcionarios.findAll();
}
@GetMapping("/{id}")
public Funcionario buscar(@PathVariable Long id) {
return funcionarios.findOne(id);
}
}
| 829 | 0.769602 | 0.769602 | 31 | 24.741936 | 22.192657 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.870968 | false | false |
7
|
53664019b36c3979e95a453cf7676d64635a5791
| 22,814,866,280,243 |
49116a737c5cf1ce7d6fc7abafaee0e0028edbcb
|
/app/src/main/java/org/asu/cse535/recipemaker/rest/RecipeServiceEndPoint.java
|
9f3eed77716f2d94f99572de24315dacd9cbc7a0
|
[] |
no_license
|
aakash55555/Android-Recipe-Maker-App
|
https://github.com/aakash55555/Android-Recipe-Maker-App
|
2b5444ffce5b6ec4cd3aabaeee03645266bec880
|
b4335c5bf7f581f984a6d2d2661bb42a1fa75857
|
refs/heads/master
| 2022-10-25T13:42:46.220000 | 2020-06-09T03:59:51 | 2020-06-09T03:59:51 | 270,884,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.asu.cse535.recipemaker.rest;
import org.asu.cse535.recipemaker.model.response.RecipePublisherResponse;
import org.asu.cse535.recipemaker.model.response.RecipeResponse;
import org.asu.cse535.recipemaker.model.response.SearchResult;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;
public interface RecipeServiceEndPoint {
@GET("/api/search")
Call<RecipePublisherResponse> searchRecipePublisher(@Query("key") String key,
@Query("q") String q);
@GET("/api/get")
Call<RecipeResponse> searchRecipe(@Query("key") String key,
@Query("rId") String rId);
}
|
UTF-8
|
Java
| 738 |
java
|
RecipeServiceEndPoint.java
|
Java
|
[] | null |
[] |
package org.asu.cse535.recipemaker.rest;
import org.asu.cse535.recipemaker.model.response.RecipePublisherResponse;
import org.asu.cse535.recipemaker.model.response.RecipeResponse;
import org.asu.cse535.recipemaker.model.response.SearchResult;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;
public interface RecipeServiceEndPoint {
@GET("/api/search")
Call<RecipePublisherResponse> searchRecipePublisher(@Query("key") String key,
@Query("q") String q);
@GET("/api/get")
Call<RecipeResponse> searchRecipe(@Query("key") String key,
@Query("rId") String rId);
}
| 738 | 0.674797 | 0.653117 | 24 | 29.75 | 28.615627 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
7
|
daf5562ac1851c2ef14bc727bd589aa9a92e0d3b
| 22,351,009,852,387 |
0a1a82cb0d95fc75576b06c66a7d5455c188e1fb
|
/account-service/src/main/java/com/antifake/gzzx/accountservice/model/vo/AuthenticationResult.java
|
33a8baa96b8b4f4a1694949564fb4b4299fff013
|
[] |
no_license
|
Alexander-Zero/anti-fake
|
https://github.com/Alexander-Zero/anti-fake
|
848785773cb15aeabd239e9a0f149b71d8d75c5c
|
130ab8007775aef2fcf514c3eff266743980ff09
|
refs/heads/master
| 2022-12-29T02:09:28.568000 | 2020-10-14T15:59:45 | 2020-10-14T15:59:45 | 302,865,277 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.antifake.gzzx.accountservice.model.vo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* Author : Zero
* Version: 1.0.0
* Date : 2020/10/14
* 认证成功后返回Token和菜单信息
*/
@Getter
@Setter
@AllArgsConstructor
public class AuthenticationResult {
private String token;
private List<ResourceVO> menu;
}
|
UTF-8
|
Java
| 403 |
java
|
AuthenticationResult.java
|
Java
|
[
{
"context": "k.Setter;\n\nimport java.util.List;\n\n/**\n * Author : Zero\n * Version: 1.0.0\n * Date : 2020/10/14\n * 认证成功后",
"end": 175,
"score": 0.9986490607261658,
"start": 171,
"tag": "USERNAME",
"value": "Zero"
}
] | null |
[] |
package com.antifake.gzzx.accountservice.model.vo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* Author : Zero
* Version: 1.0.0
* Date : 2020/10/14
* 认证成功后返回Token和菜单信息
*/
@Getter
@Setter
@AllArgsConstructor
public class AuthenticationResult {
private String token;
private List<ResourceVO> menu;
}
| 403 | 0.738786 | 0.709763 | 23 | 15.478261 | 13.764698 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false |
7
|
03aea1696ec60b10312652e1feba72c2cb763f1e
| 11,287,174,111,517 |
3b25392d96961d7b3e8ff503c959430cb2746654
|
/最后一公里代码/最后一公里自写算法/ComputerDistance/src/main/java/bao/distance/MapSortByValue.java
|
e69ed7fcaac2701930c88944ea4092c690a83311
|
[] |
no_license
|
KEVINYZY/MLCompetition
|
https://github.com/KEVINYZY/MLCompetition
|
cbd356049bce5c98741cff94e230e217af07e584
|
0b899e7bc210d94f3b401bb065c3df0d164db6eb
|
refs/heads/master
| 2020-03-30T02:14:43.834000 | 2019-11-21T12:29:43 | 2019-11-21T12:29:43 | 150,621,360 | 0 | 0 | null | true | 2018-09-27T17:07:04 | 2018-09-27T17:07:04 | 2018-08-01T01:47:04 | 2016-10-24T09:51:10 | 41,089 | 0 | 0 | 0 | null | false | null |
package bao.distance;
import java.util.*;
/**
* 根据 HashMap 的 value 进行排序
*
*/
public class MapSortByValue {
/**
* 对根据value值进行降序排序
*/
public static Map<String, Double> sortByValue(Map<String, Double> datas) {
Map<String, Double> res=new LinkedHashMap<String, Double>();
ByValueComparator bvc = new ByValueComparator(datas);
List<String> keys = new ArrayList<String>(datas.keySet());
Collections.sort(keys, bvc);
for (String key : keys) {
res.put(key, datas.get(key));
}
return res;
}
private static class ByValueComparator implements Comparator<String> {
Map<String, Double> base_map;
public ByValueComparator(Map<String, Double> base_map) {
this.base_map = base_map;
}
public int compare(String arg0, String arg1) {
if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {
return 0;
}
if (base_map.get(arg0) > base_map.get(arg1)) {
return 1;
} else if (base_map.get(arg0) == base_map.get(arg1)) {
return 0;
} else {
return -1;
}
}
}
}
|
GB18030
|
Java
| 1,090 |
java
|
MapSortByValue.java
|
Java
|
[] | null |
[] |
package bao.distance;
import java.util.*;
/**
* 根据 HashMap 的 value 进行排序
*
*/
public class MapSortByValue {
/**
* 对根据value值进行降序排序
*/
public static Map<String, Double> sortByValue(Map<String, Double> datas) {
Map<String, Double> res=new LinkedHashMap<String, Double>();
ByValueComparator bvc = new ByValueComparator(datas);
List<String> keys = new ArrayList<String>(datas.keySet());
Collections.sort(keys, bvc);
for (String key : keys) {
res.put(key, datas.get(key));
}
return res;
}
private static class ByValueComparator implements Comparator<String> {
Map<String, Double> base_map;
public ByValueComparator(Map<String, Double> base_map) {
this.base_map = base_map;
}
public int compare(String arg0, String arg1) {
if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {
return 0;
}
if (base_map.get(arg0) > base_map.get(arg1)) {
return 1;
} else if (base_map.get(arg0) == base_map.get(arg1)) {
return 0;
} else {
return -1;
}
}
}
}
| 1,090 | 0.638258 | 0.626894 | 51 | 19.725491 | 22.667311 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.980392 | false | false |
7
|
5ca21073a615cd72132314e95ba08e9f51af7c46
| 28,054,726,437,417 |
c4ccc38a55114e231bfce1dd6431d6a88470bbc5
|
/team_management/src/com/ssm/entity/Tuser.java
|
eb4058018ab7bd793f925f84a78f314e50fc7e39
|
[] |
no_license
|
ULTRAFCB/Football-Club-Management-System
|
https://github.com/ULTRAFCB/Football-Club-Management-System
|
bcba8951a92db28724e36d8a237651b50cca6826
|
33ceda509280098c5641f170fbc251ead04b371d
|
refs/heads/master
| 2023-06-08T18:21:51.743000 | 2021-06-26T10:40:27 | 2021-06-26T10:40:27 | 380,416,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ssm.entity;
public class Tuser {
private int tuserID;
private String username;
private String password;
private String realname;
private String nationality;
private int age;
private String experience;
private String weight;
private String height;
private String tel;
private String sex;
public int getTuserID() {
return tuserID;
}
public void setTuserID(int tuserID) {
this.tuserID = tuserID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
|
UTF-8
|
Java
| 1,642 |
java
|
Tuser.java
|
Java
|
[
{
"context": "serID;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n",
"end": 478,
"score": 0.576214611530304,
"start": 470,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn pass",
"end": 554,
"score": 0.9538595080375671,
"start": 546,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.ssm.entity;
public class Tuser {
private int tuserID;
private String username;
private String password;
private String realname;
private String nationality;
private int age;
private String experience;
private String weight;
private String height;
private String tel;
private String sex;
public int getTuserID() {
return tuserID;
}
public void setTuserID(int tuserID) {
this.tuserID = tuserID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
| 1,642 | 0.70341 | 0.70341 | 104 | 14.788462 | 14.09765 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.278846 | false | false |
7
|
ed0f3f9b89cc5bdbf16e922f6c10d5499e38913e
| 1,597,727,868,060 |
c689ce6bc781104acf7483eac674a028d13d655e
|
/core/src/fr/tommarx/gameengine/Net/SocketHandler.java
|
1f1a4fad327649e114fbf76a6464d01f49142552
|
[] |
no_license
|
t0mm4rx/GameEngine-v.2
|
https://github.com/t0mm4rx/GameEngine-v.2
|
48efe7ccb8efc1bd55c08034b6ef45ab0ed73260
|
55e9ccfb3b37dae09ae12ed04689c958fafda789
|
refs/heads/master
| 2021-01-13T13:42:07.462000 | 2017-09-12T17:03:04 | 2017-09-12T17:03:04 | 76,384,539 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.tommarx.gameengine.Net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.concurrent.Callable;
public class SocketHandler {
BufferedReader reader;
Thread t1, t2;
boolean running = true;
public SocketHandler(final Socket socket, final SocketListener listener, final Callable onDisconnected) {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
t1 = new Thread(new Runnable() {
public void run() {
while (running) {
try {
String message = reader.readLine();
if (listener != null) {
if (running && message != null) {
if (message.split("&&::!!").length > 1) {
listener.onMessage(message.split("&&::!!")[0], message.split("&&::!!")[1], socket);
} else {
listener.onMessage(message.split("&&::!!")[0], "", socket);
}
}
}
} catch (IOException e) {
listener.onDisconnection(socket);
stop();
try {
onDisconnected.call();
} catch (Exception e1) {
e1.printStackTrace();
}
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
});
t2 = new Thread(new Runnable() {
public void run() {
while (running) {
try {
if (reader.read() == -1) {
listener.onDisconnection(socket);
stop();
try {
onDisconnected.call();
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
private void stop() {
t1.interrupt();
t2.interrupt();
running = false;
}
}
|
UTF-8
|
Java
| 2,671 |
java
|
SocketHandler.java
|
Java
|
[] | null |
[] |
package fr.tommarx.gameengine.Net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.concurrent.Callable;
public class SocketHandler {
BufferedReader reader;
Thread t1, t2;
boolean running = true;
public SocketHandler(final Socket socket, final SocketListener listener, final Callable onDisconnected) {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
t1 = new Thread(new Runnable() {
public void run() {
while (running) {
try {
String message = reader.readLine();
if (listener != null) {
if (running && message != null) {
if (message.split("&&::!!").length > 1) {
listener.onMessage(message.split("&&::!!")[0], message.split("&&::!!")[1], socket);
} else {
listener.onMessage(message.split("&&::!!")[0], "", socket);
}
}
}
} catch (IOException e) {
listener.onDisconnection(socket);
stop();
try {
onDisconnected.call();
} catch (Exception e1) {
e1.printStackTrace();
}
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
});
t2 = new Thread(new Runnable() {
public void run() {
while (running) {
try {
if (reader.read() == -1) {
listener.onDisconnection(socket);
stop();
try {
onDisconnected.call();
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
private void stop() {
t1.interrupt();
t2.interrupt();
running = false;
}
}
| 2,671 | 0.387121 | 0.380756 | 79 | 32.810127 | 23.504955 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493671 | false | false |
7
|
abaca3374b401cc0f84fe9e943b6940d794df76b
| 19,378,892,464,978 |
31e1640281f52d5227632770ce4965419fcf64d0
|
/model/test/uk/co/itstherules/model/format/DecimalFormatPatternTest.java
|
201c3d10684452d633de579d8dcba5ab64d3978e
|
[] |
no_license
|
bobhoskinsbrother/the_evolution_game
|
https://github.com/bobhoskinsbrother/the_evolution_game
|
0dbec414935d90793629e641442fd0dbed700d87
|
b978694e3048eec0a386061da7c607242ecb0f29
|
refs/heads/master
| 2016-06-07T01:07:58.132000 | 2016-06-02T20:06:54 | 2016-06-02T20:06:54 | 39,675,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uk.co.itstherules.model.format;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class DecimalFormatPatternTest {
@Test(expected = IllegalArgumentException.class) public void cannotFormatTo0() {
DecimalFormatPattern.make(0);
}
@Test public void canFormatTo1() {
final String made = DecimalFormatPattern.make(1);
assertThat(made, is("0.0"));
}
@Test public void canFormatTo7() {
final String made = DecimalFormatPattern.make(7);
assertThat(made, is("0.0000000"));
}
@Test public void canFormatTo10() {
final String made = DecimalFormatPattern.make(10);
assertThat(made, is("0.0000000000"));
}
}
|
UTF-8
|
Java
| 773 |
java
|
DecimalFormatPatternTest.java
|
Java
|
[] | null |
[] |
package uk.co.itstherules.model.format;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class DecimalFormatPatternTest {
@Test(expected = IllegalArgumentException.class) public void cannotFormatTo0() {
DecimalFormatPattern.make(0);
}
@Test public void canFormatTo1() {
final String made = DecimalFormatPattern.make(1);
assertThat(made, is("0.0"));
}
@Test public void canFormatTo7() {
final String made = DecimalFormatPattern.make(7);
assertThat(made, is("0.0000000"));
}
@Test public void canFormatTo10() {
final String made = DecimalFormatPattern.make(10);
assertThat(made, is("0.0000000000"));
}
}
| 773 | 0.677878 | 0.637775 | 29 | 25.655172 | 23.929892 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false |
7
|
68366a66e90784af3fb391747a0a34db2fc6e950
| 33,715,493,295,007 |
8d9b461300552624e76e7f0beca37190708fafdc
|
/Baraati-Android-master/app/src/main/java/com/nectarbits/baraati/Singletone/EventTypesSingletone.java
|
543aee17520b26f43d32889f14b327997ba8631a
|
[] |
no_license
|
opmaurya83/Baraati
|
https://github.com/opmaurya83/Baraati
|
7ae6b5649508a63e9e1236be16a4d679822888b4
|
d77542f83669ffdf001ccf58af3127d9c73cb421
|
refs/heads/master
| 2020-12-03T05:14:38.361000 | 2017-06-29T06:56:29 | 2017-06-29T06:56:29 | 95,748,235 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.nectarbits.baraati.Singletone;
import com.nectarbits.baraati.Models.UserEvent.EventType;
import java.util.ArrayList;
import java.util.List;
/**
* Created by root on 9/9/16.
*/
public class EventTypesSingletone {
public List<EventType> getEventTypeList() {
return eventTypeList;
}
public void setEventTypeList(List<EventType> eventTypeList) {
this.eventTypeList = eventTypeList;
}
public List<EventType> eventTypeList=new ArrayList<>();
public List<EventType> eventTypeList_assigned=new ArrayList<>();
private static EventTypesSingletone ourInstance = new EventTypesSingletone();
public static EventTypesSingletone getInstance() {
return ourInstance;
}
private EventTypesSingletone() {
}
public List<EventType> getEventTypeList_assigned() {
return eventTypeList_assigned;
}
public void setEventTypeList_assigned(List<EventType> eventTypeList_assigned) {
this.eventTypeList_assigned = eventTypeList_assigned;
}
public static EventTypesSingletone getOurInstance() {
return ourInstance;
}
public static void setOurInstance(EventTypesSingletone ourInstance) {
EventTypesSingletone.ourInstance = ourInstance;
}
}
|
UTF-8
|
Java
| 1,267 |
java
|
EventTypesSingletone.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by root on 9/9/16.\n */\npublic class EventTypesSingletone ",
"end": 177,
"score": 0.9767990708351135,
"start": 173,
"tag": "USERNAME",
"value": "root"
}
] | null |
[] |
package com.nectarbits.baraati.Singletone;
import com.nectarbits.baraati.Models.UserEvent.EventType;
import java.util.ArrayList;
import java.util.List;
/**
* Created by root on 9/9/16.
*/
public class EventTypesSingletone {
public List<EventType> getEventTypeList() {
return eventTypeList;
}
public void setEventTypeList(List<EventType> eventTypeList) {
this.eventTypeList = eventTypeList;
}
public List<EventType> eventTypeList=new ArrayList<>();
public List<EventType> eventTypeList_assigned=new ArrayList<>();
private static EventTypesSingletone ourInstance = new EventTypesSingletone();
public static EventTypesSingletone getInstance() {
return ourInstance;
}
private EventTypesSingletone() {
}
public List<EventType> getEventTypeList_assigned() {
return eventTypeList_assigned;
}
public void setEventTypeList_assigned(List<EventType> eventTypeList_assigned) {
this.eventTypeList_assigned = eventTypeList_assigned;
}
public static EventTypesSingletone getOurInstance() {
return ourInstance;
}
public static void setOurInstance(EventTypesSingletone ourInstance) {
EventTypesSingletone.ourInstance = ourInstance;
}
}
| 1,267 | 0.721389 | 0.718232 | 49 | 24.857143 | 26.529921 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
7
|
64c63c89d600880905fcde44b5bca2acd0204b4a
| 35,098,472,758,349 |
153365d7a770faa68fc70e5298aea60237d22837
|
/ManejoTransaccionesUdemy/src/manejopersonas/ManejoMysql.java
|
134f45adf31e5cbd617e000ab802d64468459b67
|
[] |
no_license
|
CristhianFonseca/JAVAPractice
|
https://github.com/CristhianFonseca/JAVAPractice
|
809dddb7a5a5e07e02acc1c71662ab99f565ec8a
|
f4de5067ec3c8d2dde179ed17af0b9374f2916f2
|
refs/heads/master
| 2020-05-18T04:01:48.610000 | 2019-04-29T23:47:53 | 2019-04-29T23:47:53 | 184,159,714 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package manejopersonas;
import java.sql.*;
import datos.Conexion;
import datos.PersonasJDBC;
import domain.Persona;
public class ManejoMysql {
public static void main(String[] args) {
PersonasJDBC personaJDBC = new PersonasJDBC();
Connection conn = null;
try {
conn = Conexion.getConnection();
if (conn.getAutoCommit()) {
conn.setAutoCommit(false);
}
// proporcionamos la conexion
PersonasJDBC personas = new PersonasJDBC(conn);
personas.update(4, "Cristhian", "Fonseca");
// personas.insert("Miguel2",
// "Ayala12341234123412341234123412341234123412341234123412341234123412341234123412344");
personas.insert("JUAN", "Miguel");
conn.commit();
} catch (SQLException e) {
// TODO: handle exception
// hacemos rollback
try {
System.out.println("Entramos al rollback");
e.printStackTrace(System.out);
conn.rollback();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace(System.out);
}
}
}
}
|
UTF-8
|
Java
| 1,016 |
java
|
ManejoMysql.java
|
Java
|
[
{
"context": " = new PersonasJDBC(conn);\n\t\t\tpersonas.update(4, \"Cristhian\", \"Fonseca\");\n//\t\t\t personas.insert(\"Miguel2\",\n//",
"end": 496,
"score": 0.9998400807380676,
"start": 487,
"tag": "NAME",
"value": "Cristhian"
},
{
"context": "asJDBC(conn);\n\t\t\tpersonas.update(4, \"Cristhian\", \"Fonseca\");\n//\t\t\t personas.insert(\"Miguel2\",\n//\t ",
"end": 507,
"score": 0.9998183250427246,
"start": 500,
"tag": "NAME",
"value": "Fonseca"
},
{
"context": ", \"Cristhian\", \"Fonseca\");\n//\t\t\t personas.insert(\"Miguel2\",\n//\t \"Ayala123412341234123412",
"end": 541,
"score": 0.973963737487793,
"start": 534,
"tag": "NAME",
"value": "Miguel2"
},
{
"context": "ersonas.insert(\"Miguel2\",\n//\t \"Ayala12341234123412341234123412341234123412341234123412",
"end": 573,
"score": 0.9945629239082336,
"start": 568,
"tag": "NAME",
"value": "Ayala"
},
{
"context": "41234123412341234123412344\");\n\t\t\tpersonas.insert(\"JUAN\", \"Miguel\");\n\t\t\tconn.commit();\n\t\t} catch (SQLExce",
"end": 678,
"score": 0.9997481107711792,
"start": 674,
"tag": "NAME",
"value": "JUAN"
},
{
"context": "412341234123412344\");\n\t\t\tpersonas.insert(\"JUAN\", \"Miguel\");\n\t\t\tconn.commit();\n\t\t} catch (SQLException e) {",
"end": 688,
"score": 0.9997305870056152,
"start": 682,
"tag": "NAME",
"value": "Miguel"
}
] | null |
[] |
package manejopersonas;
import java.sql.*;
import datos.Conexion;
import datos.PersonasJDBC;
import domain.Persona;
public class ManejoMysql {
public static void main(String[] args) {
PersonasJDBC personaJDBC = new PersonasJDBC();
Connection conn = null;
try {
conn = Conexion.getConnection();
if (conn.getAutoCommit()) {
conn.setAutoCommit(false);
}
// proporcionamos la conexion
PersonasJDBC personas = new PersonasJDBC(conn);
personas.update(4, "Cristhian", "Fonseca");
// personas.insert("Miguel2",
// "Ayala12341234123412341234123412341234123412341234123412341234123412341234123412344");
personas.insert("JUAN", "Miguel");
conn.commit();
} catch (SQLException e) {
// TODO: handle exception
// hacemos rollback
try {
System.out.println("Entramos al rollback");
e.printStackTrace(System.out);
conn.rollback();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace(System.out);
}
}
}
}
| 1,016 | 0.679134 | 0.599409 | 46 | 21.086956 | 20.50008 | 109 | false | false | 0 | 0 | 0 | 0 | 82 | 0.080709 | 2.23913 | false | false |
7
|
0bfc42a2c37cfcc06a6d22e92e0fe25a620a2c1a
| 22,505,628,690,981 |
c7f0b854cdde82cf116ecc56eda2a435f5105bf1
|
/subo/src/main/java/Menu/State.java
|
24476c1e8a09e32cab45722ccf8f5f57e20d2c51
|
[] |
no_license
|
invoker333/suboStudio
|
https://github.com/invoker333/suboStudio
|
e50e61a8e4d78b7909606a864d6621ea2c28de60
|
a6807c18597cd52761bc80f83d63dbacf6f428c1
|
refs/heads/master
| 2021-09-02T08:16:41.953000 | 2017-12-31T21:08:20 | 2017-12-31T21:08:20 | 109,478,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Menu;
public class State extends Square {
protected float x1;
protected float y1;
protected float x2;
protected float y2;
public State(){
}
public State(float x1,float y1,float x2,float y2){
setPosition(x1, y1, x2, y2);
}
public void setPosition(float x1,float y1,float x2,float y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void syncTextureSize(){//ȫ������
fbSpi.clear();
fbSpi.put(new float[]{
x1,y1,getDepth(),
x2,y1,getDepth(),
x2,y2,getDepth(),
x1,y2,getDepth(),
x1,y1,getDepth()
}
);
fbSpi.flip();
}
public void setFrameCount(int i, int j) {
setxCount(i);
setyCount(j);
}
public void animation(float dr, float dg, float db) {
// TODO Auto-generated method stub
}
public float getY2() {
return y2;
}
public void setY2(float y2) {
this.y2 = y2;
}
public float getY1() {
return y1;
}
public void setY1(float y1) {
this.y1 = y1;
}
public float getX2() {
return x2;
}
public void setX2(float x2) {
this.x2 = x2;
}
public float getX1() {
return x1;
}
public void setX1(float x1) {
this.x1 = x1;
}
}
|
UTF-8
|
Java
| 1,158 |
java
|
State.java
|
Java
|
[] | null |
[] |
package Menu;
public class State extends Square {
protected float x1;
protected float y1;
protected float x2;
protected float y2;
public State(){
}
public State(float x1,float y1,float x2,float y2){
setPosition(x1, y1, x2, y2);
}
public void setPosition(float x1,float y1,float x2,float y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void syncTextureSize(){//ȫ������
fbSpi.clear();
fbSpi.put(new float[]{
x1,y1,getDepth(),
x2,y1,getDepth(),
x2,y2,getDepth(),
x1,y2,getDepth(),
x1,y1,getDepth()
}
);
fbSpi.flip();
}
public void setFrameCount(int i, int j) {
setxCount(i);
setyCount(j);
}
public void animation(float dr, float dg, float db) {
// TODO Auto-generated method stub
}
public float getY2() {
return y2;
}
public void setY2(float y2) {
this.y2 = y2;
}
public float getY1() {
return y1;
}
public void setY1(float y1) {
this.y1 = y1;
}
public float getX2() {
return x2;
}
public void setX2(float x2) {
this.x2 = x2;
}
public float getX1() {
return x1;
}
public void setX1(float x1) {
this.x1 = x1;
}
}
| 1,158 | 0.619214 | 0.568559 | 69 | 15.594203 | 14.012747 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.231884 | false | false |
7
|
d79900efa617946fa9520c704b26940c7f5572a8
| 36,910,948,969,464 |
2c73c93220c49bac451ceb2bf1c821deb7389bad
|
/ucsal-App-italo/src/br/ucsal/servlet/OlaMundo.java
|
69118cc0f48debbd2ff98cad3868159a58aa6cd3
|
[] |
no_license
|
linzera/list-2-webapp-tag-hsql
|
https://github.com/linzera/list-2-webapp-tag-hsql
|
1f18e04cdbdcce2dc71a5d58a604acab412e8882
|
195486c089f40e06df78100ad516f3636cd5efa5
|
refs/heads/master
| 2020-04-01T16:19:20.011000 | 2018-10-17T01:12:44 | 2018-10-17T01:12:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.ucsal.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/OlaMundo")
public class OlaMundo extends HttpServlet {
private static final long serialVersionUID = 1L;
public OlaMundo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("<html><body><h1>Eae galera</h1></body></html>");
}
}
|
UTF-8
|
Java
| 734 |
java
|
OlaMundo.java
|
Java
|
[] | null |
[] |
package br.ucsal.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/OlaMundo")
public class OlaMundo extends HttpServlet {
private static final long serialVersionUID = 1L;
public OlaMundo() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("<html><body><h1>Eae galera</h1></body></html>");
}
}
| 734 | 0.743869 | 0.739782 | 29 | 23.310345 | 22.563478 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.172414 | false | false |
7
|
5ba3f1078ac569f27bf670a3917e17ec23655a28
| 36,335,423,358,399 |
63002596d5382001f3cb5ceb92b5b5d9db5c089e
|
/app/src/main/java/com/edu/nikita/progamerdota2watcher/model/FriendsModelImpl.java
|
91269d0718ff635bc372e74b5890248f5a15b84d
|
[] |
no_license
|
ussernamenikita/Dota2Wather
|
https://github.com/ussernamenikita/Dota2Wather
|
0a73c45afbffced815e7f85b40131dfb83c91979
|
206fad6e1c03d0f0a1ec056dbbbaa5ac10d088e7
|
refs/heads/master
| 2017-11-19T17:55:47.527000 | 2016-07-30T20:25:40 | 2016-07-30T20:25:40 | 62,994,452 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.edu.nikita.progamerdota2watcher.model;
import android.app.SharedElementCallback;
import android.util.Log;
import com.edu.nikita.progamerdota2watcher.BuildConfig;
import com.edu.nikita.progamerdota2watcher.CONST;
import com.edu.nikita.progamerdota2watcher.dependencyInjection.module.AppWithDagger;
import com.edu.nikita.progamerdota2watcher.network.ApiFactory;
import com.edu.nikita.progamerdota2watcher.model.pojo.Friend;
import com.edu.nikita.progamerdota2watcher.model.pojo.ResponseGetFriendList;
import com.edu.nikita.progamerdota2watcher.model.pojo.ResponseGetPlayerSummaries;
import com.edu.nikita.progamerdota2watcher.network.RetrofitApiInterface;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Nikita on 23.06.2016.
* Model layer for friends list
*/
public class FriendsModelImpl implements Model {
/**
* Retrofit service for requests methods
*/
@Inject
RetrofitApiInterface retrofitApiService;
/**
* UI sheduler
*/
@Inject
@Named(CONST.NAME_UI_THREAD)
Scheduler uiThread;
/**
* Sheduler for background tasks
*/
@Inject
@Named(CONST.NAME_IO_THREAD)
Scheduler ioThread;
/**
* Steam api key
*/
@Inject
@Named(CONST.NAME_STEAM_API)
String STEAM_API_KEY;
/**
* Quatity of numbers in steam id
*/
@Inject
@Named(CONST.NAME_STEAM_ID_LENGHT)
int steamIdLenght;
public FriendsModelImpl()
{
AppWithDagger.getComponent().inject(this);
}
/**
* Observable with friends list requests
* @param steamId Steam id of player
* @return Observable with list of players friends
*/
@Override
public Observable<ResponseGetFriendList> getFriendsList(String steamId) {
return retrofitApiService.getFriends(STEAM_API_KEY,steamId).
observeOn(uiThread).
subscribeOn(ioThread);
}
/**
* Get all info about players friends
* @param key Steam api key
* @param steamId If of player
* @return Observable with list of all information about players friends
*/
@Override
public Observable<ResponseGetPlayerSummaries> getPlayersSummaries(String key,String steamId) {
return retrofitApiService.getFriends(STEAM_API_KEY,steamId).
map(response -> {
List<Friend> list = response.getFriendslist().getFriends();
StringBuilder builder = new StringBuilder(list.size()*steamIdLenght);
Observable.from(list).subscribe(item ->
builder.append(item.getSteamid()).append(",")
);
Log.d("build steamids",builder.toString());
return builder.toString();
}
).concatMap(string ->
{
Log.d("String in concatmap",string);
return retrofitApiService.getPlayersSummaries(STEAM_API_KEY,string);
}).observeOn(uiThread).subscribeOn(ioThread);
}
}
|
UTF-8
|
Java
| 3,230 |
java
|
FriendsModelImpl.java
|
Java
|
[
{
"context": "mport rx.schedulers.Schedulers;\n\n/**\n * Created by Nikita on 23.06.2016.\n * Model layer for friends list\n *",
"end": 929,
"score": 0.9978296756744385,
"start": 923,
"tag": "NAME",
"value": "Nikita"
}
] | null |
[] |
package com.edu.nikita.progamerdota2watcher.model;
import android.app.SharedElementCallback;
import android.util.Log;
import com.edu.nikita.progamerdota2watcher.BuildConfig;
import com.edu.nikita.progamerdota2watcher.CONST;
import com.edu.nikita.progamerdota2watcher.dependencyInjection.module.AppWithDagger;
import com.edu.nikita.progamerdota2watcher.network.ApiFactory;
import com.edu.nikita.progamerdota2watcher.model.pojo.Friend;
import com.edu.nikita.progamerdota2watcher.model.pojo.ResponseGetFriendList;
import com.edu.nikita.progamerdota2watcher.model.pojo.ResponseGetPlayerSummaries;
import com.edu.nikita.progamerdota2watcher.network.RetrofitApiInterface;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Nikita on 23.06.2016.
* Model layer for friends list
*/
public class FriendsModelImpl implements Model {
/**
* Retrofit service for requests methods
*/
@Inject
RetrofitApiInterface retrofitApiService;
/**
* UI sheduler
*/
@Inject
@Named(CONST.NAME_UI_THREAD)
Scheduler uiThread;
/**
* Sheduler for background tasks
*/
@Inject
@Named(CONST.NAME_IO_THREAD)
Scheduler ioThread;
/**
* Steam api key
*/
@Inject
@Named(CONST.NAME_STEAM_API)
String STEAM_API_KEY;
/**
* Quatity of numbers in steam id
*/
@Inject
@Named(CONST.NAME_STEAM_ID_LENGHT)
int steamIdLenght;
public FriendsModelImpl()
{
AppWithDagger.getComponent().inject(this);
}
/**
* Observable with friends list requests
* @param steamId Steam id of player
* @return Observable with list of players friends
*/
@Override
public Observable<ResponseGetFriendList> getFriendsList(String steamId) {
return retrofitApiService.getFriends(STEAM_API_KEY,steamId).
observeOn(uiThread).
subscribeOn(ioThread);
}
/**
* Get all info about players friends
* @param key Steam api key
* @param steamId If of player
* @return Observable with list of all information about players friends
*/
@Override
public Observable<ResponseGetPlayerSummaries> getPlayersSummaries(String key,String steamId) {
return retrofitApiService.getFriends(STEAM_API_KEY,steamId).
map(response -> {
List<Friend> list = response.getFriendslist().getFriends();
StringBuilder builder = new StringBuilder(list.size()*steamIdLenght);
Observable.from(list).subscribe(item ->
builder.append(item.getSteamid()).append(",")
);
Log.d("build steamids",builder.toString());
return builder.toString();
}
).concatMap(string ->
{
Log.d("String in concatmap",string);
return retrofitApiService.getPlayersSummaries(STEAM_API_KEY,string);
}).observeOn(uiThread).subscribeOn(ioThread);
}
}
| 3,230 | 0.668421 | 0.663158 | 111 | 28.099098 | 25.514156 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369369 | false | false |
7
|
72e6bebeeb948b434020e9cb056b29b13ff430e4
| 34,196,529,654,823 |
30125b1b6f10195fdbcc98c6a96ba6f8992668a3
|
/fabric-erp/src/main/java/com/vix/hr/trainning/controller/PlanTrainCourseController.java
|
dbc45a2813300cb24a7cb8398f42da41000fbba9
|
[] |
no_license
|
bellmit/vix_fabric
|
https://github.com/bellmit/vix_fabric
|
8756efb845fa624280edd172edb8b0fdaa6ba303
|
a55519c88c685a1b760e98a3e2e129fdc3392c8c
|
refs/heads/master
| 2022-01-11T10:28:15.814000 | 2018-06-03T04:44:58 | 2018-06-03T04:44:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vix.hr.trainning.controller;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.vix.common.base.action.BaseAction;
import com.vix.core.web.Pager;
import com.vix.hr.trainning.domain.PlanTrainCourseDomain;
import com.vix.hr.trainning.entity.Plan;
import com.vix.hr.trainning.entity.PlanTrainCourse;
@Scope("prototype")
@Controller("planTrainCourseController")
public class PlanTrainCourseController extends BaseAction {
private static final long serialVersionUID = 1L;
/** 键值从配置文件获取 */
public static String industryIdentify = "GeneralIndustry";
Logger logger = Logger.getLogger("DemandApplyController");
@Autowired
private PlanTrainCourseDomain planTrainCourseDomain;
public PlanTrainCourseDomain getPlanTrainCourseDomain() {
return planTrainCourseDomain;
}
public void setPlanTrainCourseDomain(PlanTrainCourseDomain planTrainCourseDomain) {
this.planTrainCourseDomain = planTrainCourseDomain;
}
public List<PlanTrainCourse> findPlanTrainCourseIndex() throws Exception {
return planTrainCourseDomain.findPlanTrainCourseIndex();
}
public Pager goSingleList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByHqlConditions(params, pager);
return p;
}
/** 获取搜索列表数据 */
public Pager goSearchList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByOrHqlConditions(params, pager);
return p;
}
public PlanTrainCourse doListEntityById(String id) {
PlanTrainCourse planTrainCourse = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
planTrainCourse = planTrainCourseDomain.findEntityById(id);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询计划培训课程信息成功!");
} catch (Exception ex) {
executeLogger(true, "查询计划培训课程信息失败!" + "失败原因:" + ex.getMessage());
}
return planTrainCourse;
}
// 保存
public PlanTrainCourse doSavePlanTrainCourse(PlanTrainCourse planTrainCourse) throws Exception {
PlanTrainCourse planTrainCourse2 = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行保存操作
planTrainCourse2 = planTrainCourseDomain.merge(planTrainCourse);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "保存计划培训课程:" + planTrainCourse + "成功!");
} catch (Exception ex) {
executeLogger(true, "保存计划培训课程:" + planTrainCourse + "失败!失败原因:" + ex.getMessage());
throw new Exception(ex.getMessage());
}
return planTrainCourse2;
}
public Pager doSubSingleList(Map<String, Object> params, Pager pager) {
Pager p = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
p = planTrainCourseDomain.findPagerByHqlConditions(params, pager);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "查询计划培训课程失败!" + "失败原因:" + ex.getMessage());
}
return p;
}
public void doDeleteByEntity(PlanTrainCourse planTrainCourse) {
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行删除操作
planTrainCourseDomain.deleteByEntity(planTrainCourse);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "删除计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "删除计划培训课程失败!失败原因:" + ex.getMessage());
}
}
/**
* doSaveExecute实现删除计划培训课程的业务逻辑处理
*
* @param ids
*/
public void doDeleteByIds(List<String> ids) {
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行删除操作
planTrainCourseDomain.deleteByIds(ids);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "删除计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "删除计划培训课程失败!" + "失败原因:" + ex.getMessage());
}
}
public PlanTrainCourse merge(PlanTrainCourse planTrainCourse) throws Exception {
planTrainCourseDomain.merge(planTrainCourse);
return null;
}
public void deleteByEntity(PlanTrainCourse planTrainCourse) throws Exception {
planTrainCourseDomain.deleteByEntity(planTrainCourse);
}
public void deleteByIds(List<String> ids) throws Exception {
planTrainCourseDomain.deleteByIds(ids);
}
public PlanTrainCourse findEntityById(String id) throws Exception {
return planTrainCourseDomain.findEntityById(id);
}
/*******************************************
* 填报计划
********************************************************************************/
public Plan findPlanById(String id) throws Exception {
return planTrainCourseDomain.findPlanById(id);
}
/* 培训课程明细 */
public Plan doSavePlan(Plan plan) throws Exception {
Plan plans = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行保存操作
plans = planTrainCourseDomain.merge(plan);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "保存填报计划:" + plan + "成功!");
} catch (Exception ex) {
executeLogger(true, "保存填报计划:" + plan + "失败!失败原因:" + ex.getMessage());
throw new Exception("保存填报计划失败", ex);
}
return plans;
}
/** 获取填报计划列表数据 */
public Pager goPlanList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByPlan(params, pager);
return p;
}
/** 获取填报计划明细 */
public Plan doListPlanById(String id) {
Plan detailsTemp = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
detailsTemp = planTrainCourseDomain.findPlanById(id);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询填报计划成功!");
} catch (Exception ex) {
executeLogger(true, "查询填报计划失败!" + "失败原因:" + ex.getMessage());
}
return detailsTemp;
}
public void deletePlanEntity(Plan plan) throws Exception {
planTrainCourseDomain.deletePlanEntity(plan);
}
/**
* 输入信息到日志文件中,可以考虑是用Helper类提供服务.
*
* @param message
*/
public void executeLogger(boolean isShow, String... message) {
if (isShow) {
logger.info(message);
}
}
private void beforeEventTrigger(String eventName) {
// to do something
}
/**
* afterEventTrigger 用于触发在执行业务逻辑后的事件产生, 将产生一个业务对象执行动作的after事件.
*
* @param eventName
* 根据业务对象来定义
*/
private void afterEventTrigger(String eventName) {
// to do something
}
}
|
UTF-8
|
Java
| 10,440 |
java
|
PlanTrainCourseController.java
|
Java
|
[] | null |
[] |
package com.vix.hr.trainning.controller;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.vix.common.base.action.BaseAction;
import com.vix.core.web.Pager;
import com.vix.hr.trainning.domain.PlanTrainCourseDomain;
import com.vix.hr.trainning.entity.Plan;
import com.vix.hr.trainning.entity.PlanTrainCourse;
@Scope("prototype")
@Controller("planTrainCourseController")
public class PlanTrainCourseController extends BaseAction {
private static final long serialVersionUID = 1L;
/** 键值从配置文件获取 */
public static String industryIdentify = "GeneralIndustry";
Logger logger = Logger.getLogger("DemandApplyController");
@Autowired
private PlanTrainCourseDomain planTrainCourseDomain;
public PlanTrainCourseDomain getPlanTrainCourseDomain() {
return planTrainCourseDomain;
}
public void setPlanTrainCourseDomain(PlanTrainCourseDomain planTrainCourseDomain) {
this.planTrainCourseDomain = planTrainCourseDomain;
}
public List<PlanTrainCourse> findPlanTrainCourseIndex() throws Exception {
return planTrainCourseDomain.findPlanTrainCourseIndex();
}
public Pager goSingleList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByHqlConditions(params, pager);
return p;
}
/** 获取搜索列表数据 */
public Pager goSearchList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByOrHqlConditions(params, pager);
return p;
}
public PlanTrainCourse doListEntityById(String id) {
PlanTrainCourse planTrainCourse = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
planTrainCourse = planTrainCourseDomain.findEntityById(id);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询计划培训课程信息成功!");
} catch (Exception ex) {
executeLogger(true, "查询计划培训课程信息失败!" + "失败原因:" + ex.getMessage());
}
return planTrainCourse;
}
// 保存
public PlanTrainCourse doSavePlanTrainCourse(PlanTrainCourse planTrainCourse) throws Exception {
PlanTrainCourse planTrainCourse2 = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行保存操作
planTrainCourse2 = planTrainCourseDomain.merge(planTrainCourse);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "保存计划培训课程:" + planTrainCourse + "成功!");
} catch (Exception ex) {
executeLogger(true, "保存计划培训课程:" + planTrainCourse + "失败!失败原因:" + ex.getMessage());
throw new Exception(ex.getMessage());
}
return planTrainCourse2;
}
public Pager doSubSingleList(Map<String, Object> params, Pager pager) {
Pager p = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
p = planTrainCourseDomain.findPagerByHqlConditions(params, pager);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "查询计划培训课程失败!" + "失败原因:" + ex.getMessage());
}
return p;
}
public void doDeleteByEntity(PlanTrainCourse planTrainCourse) {
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行删除操作
planTrainCourseDomain.deleteByEntity(planTrainCourse);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "删除计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "删除计划培训课程失败!失败原因:" + ex.getMessage());
}
}
/**
* doSaveExecute实现删除计划培训课程的业务逻辑处理
*
* @param ids
*/
public void doDeleteByIds(List<String> ids) {
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行删除操作
planTrainCourseDomain.deleteByIds(ids);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "删除计划培训课程成功!");
} catch (Exception ex) {
executeLogger(true, "删除计划培训课程失败!" + "失败原因:" + ex.getMessage());
}
}
public PlanTrainCourse merge(PlanTrainCourse planTrainCourse) throws Exception {
planTrainCourseDomain.merge(planTrainCourse);
return null;
}
public void deleteByEntity(PlanTrainCourse planTrainCourse) throws Exception {
planTrainCourseDomain.deleteByEntity(planTrainCourse);
}
public void deleteByIds(List<String> ids) throws Exception {
planTrainCourseDomain.deleteByIds(ids);
}
public PlanTrainCourse findEntityById(String id) throws Exception {
return planTrainCourseDomain.findEntityById(id);
}
/*******************************************
* 填报计划
********************************************************************************/
public Plan findPlanById(String id) throws Exception {
return planTrainCourseDomain.findPlanById(id);
}
/* 培训课程明细 */
public Plan doSavePlan(Plan plan) throws Exception {
Plan plans = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3. 执行保存操作
plans = planTrainCourseDomain.merge(plan);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "保存填报计划:" + plan + "成功!");
} catch (Exception ex) {
executeLogger(true, "保存填报计划:" + plan + "失败!失败原因:" + ex.getMessage());
throw new Exception("保存填报计划失败", ex);
}
return plans;
}
/** 获取填报计划列表数据 */
public Pager goPlanList(Map<String, Object> params, Pager pager) throws Exception {
Pager p = planTrainCourseDomain.findPagerByPlan(params, pager);
return p;
}
/** 获取填报计划明细 */
public Plan doListPlanById(String id) {
Plan detailsTemp = null;
try {
// 1. 处理传入参数 executeParameterProcess(); 抽象方法,需要重载;
// Map parameters = baExecutor.executeParameterProcess();
// 2. 触发事件 beforeEventSaveOrder(parameters); 抽象方法,需要重载;
beforeEventTrigger("PO_CREATE_BEFORE");
// 3.执行查询操作
detailsTemp = planTrainCourseDomain.findPlanById(id);
// 4. 触发事件 afterEventSaveOrder(parameter); 抽象方法,需要重载;
afterEventTrigger("PO_CREATE_AFTER");
// 5. 访问功能和业务对象记录操作 visitBORecord(parameter);
// 6. 日志处理 log(); 每个Action中独立定义;记录操作日志、记录性能数据;
executeLogger(true, "查询填报计划成功!");
} catch (Exception ex) {
executeLogger(true, "查询填报计划失败!" + "失败原因:" + ex.getMessage());
}
return detailsTemp;
}
public void deletePlanEntity(Plan plan) throws Exception {
planTrainCourseDomain.deletePlanEntity(plan);
}
/**
* 输入信息到日志文件中,可以考虑是用Helper类提供服务.
*
* @param message
*/
public void executeLogger(boolean isShow, String... message) {
if (isShow) {
logger.info(message);
}
}
private void beforeEventTrigger(String eventName) {
// to do something
}
/**
* afterEventTrigger 用于触发在执行业务逻辑后的事件产生, 将产生一个业务对象执行动作的after事件.
*
* @param eventName
* 根据业务对象来定义
*/
private void afterEventTrigger(String eventName) {
// to do something
}
}
| 10,440 | 0.71883 | 0.713354 | 282 | 29.432625 | 25.954216 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.138298 | false | false |
7
|
e1c034b41b332c10e3eb2d689eeb6b2dddcf0525
| 34,626,026,393,566 |
86e8ea450919705d113d73c255dbfee575ee4d4b
|
/DungeonAdventure/Character.java
|
a2a0bfbd1917115f0c8f02cf176545bbcb3a8134
|
[] |
no_license
|
blahs15/DungeonAdventure
|
https://github.com/blahs15/DungeonAdventure
|
759e18ae32218f9401df7fa71d06fd4910af7ebc
|
485faffbd7af63a93824787d9e3672e92462c3e3
|
refs/heads/master
| 2016-09-16T00:33:42.070000 | 2015-03-15T19:49:34 | 2015-03-15T19:49:34 | 32,278,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public abstract class Character implements Stats
{
private int att;
private int magicAtt;
private int def;
private int magicDef;
private int spd;
private int evasion;
private int accuracy;
private int maxHP;
private int HP;
private int maxSP;
private int SP;
private int tempAttBonus;
private int tempMagicAttBonus;
private int tempDefBonus;
private int tempMagicDefBonus;
private int tempSpdBonus;
private int tempEvasionBonus;
private int tempAccuracyBonus;
private String name;
// public abstract void chooseMove( Character defender );
// public abstract ArrayList<String> getAttacks();
// returns array of attackMove names - use for loop to choose in chooseAttack()
/**
* prints out a dodge message specific to each character
* @param the name of the attack that is being dodged
*/
public abstract void dodge( String attackName );
/**a basic attack move
* @param the enemy to be attacked
*/
public abstract void attack( Character defender );
/**
* an "attack" move that reduces defense and makes the Character gain SP
*/
public void rest()
{
setDefBonus( getDef() / -2 + getDefBonus() );
setMagicDefBonus( getMagicDef() / -2 + getMagicDefBonus() );
setEvasionBonus( getEvasion() / -2 + getEvasionBonus() );
if( getSP() > getMaxSP() )
{
setSP( getMaxSP() );
} // end if
} // end method Rest
/**
* an "attack" move that increases defense
*/
public void guard()
{
System.out.println( name + " Guarded and their defenses increased" );
setDefBonus( getBaseDef() / 2 + getDefBonus() );
setMagicDefBonus( getBaseMagicDef() / 2 + getMagicDefBonus() );
setEvasionBonus( getEvasion() / 2 + getEvasionBonus() );
} // end method Guard
/**
* gain a small amount of SP, meant to be used after every turn
*/
public void gainSP()
{
setSP( getSP() + 3 );
if( getSP() > getMaxSP() )
{
setSP( getMaxSP() );
} // end if
} // end method
/**
* resets the temporaryStatBonuses, like extra def from Guard()
*/
public void resetTempStatBonuses()
{
tempAttBonus = 0;
tempMagicAttBonus = 0;
tempDefBonus = 0;
tempMagicDefBonus = 0;
tempSpdBonus = 0;
tempEvasionBonus = 0;
tempAccuracyBonus = 0;
} // end method resetStatBonuses
/**
* Setters and getters for all Stats
* includes stat bonus getters and setters
* getters for stats add the stat bonus
*/
public void setAttBonus( int att )
{
tempAttBonus = att;
} // end method
public void setMagicAttBonus( int magAtt )
{
tempMagicAttBonus = magAtt;
} // end method
public void setDefBonus( int def )
{
tempDefBonus = def;
} // end method
public void setMagicDefBonus( int magDef )
{
tempMagicDefBonus = magDef;
} // end method
public void setSpdBonus( int spd )
{
tempSpdBonus = spd;
} // end method
public void setEvasionBonus( int evasion )
{
tempEvasionBonus = evasion;
} // end method
public void setAccuracyBonus( int acc )
{
tempAccuracyBonus = acc;
} // end method
public int getAttBonus()
{
return tempAttBonus;
} // end method
public int getMagicAttBonus()
{
return tempMagicAttBonus;
} // end method
public int getDefBonus()
{
return tempDefBonus;
} // end method
public int getMagicDefBonus()
{
return tempMagicDefBonus;
} // end method
public int getSpdBonus()
{
return tempSpdBonus;
} // end method
public int getEvasionBonus()
{
return tempEvasionBonus;
} // end method
public int getAccuracyBonus()
{
return tempAccuracyBonus;
} // end method
public void setAtt( int att )
{
this.att = att;
} // end method
public void setMagicAtt( int magAtt )
{
this.magicAtt = magAtt;
} // end method
public void setDef( int def )
{
this.def = def;
} // end method
public void setMagicDef( int magDef )
{
this.magicDef = magDef;
} // end method
public void setSpd( int spd )
{
this.spd = spd;
} // end method
public void setEvasion( int evasion )
{
this.evasion = evasion;
} // end method
public void setAccuracy( int acc )
{
this.accuracy = acc;
} // end method
public void setMaxHP( int maxHP )
{
this.maxHP = maxHP;
} // end method
public void setHP( int HP )
{
this.HP = HP;
} // end method
public void setMaxSP( int maxSP )
{
this.maxSP = maxSP;
} // end method
public void setSP( int SP )
{
this.SP = SP;
} // end method
public void setName( String name )
{
this.name = name;
} // end method
public int getAtt()
{
return att + tempAttBonus;
} // end method
public int getMagicAtt()
{
return magicAtt + tempMagicAttBonus;
} // end method
public int getDef()
{
return def + tempDefBonus;
} // end method
public int getMagicDef()
{
return magicDef + tempMagicDefBonus;
} // end method
public int getSpd()
{
return spd + tempSpdBonus;
} // end method
public int getEvasion()
{
return evasion + tempEvasionBonus;
} // end method
public int getAccuracy()
{
return accuracy + tempAccuracyBonus;
} // end method
public int getMaxHP()
{
return maxHP;
} // end method
public int getHP()
{
return HP;
} // end method
public int getMaxSP()
{
return maxSP;
} // end method
public int getSP()
{
return SP;
} // end method
public String getName()
{
return name;
} // end method
public int getBaseAtt()
{
return att;
} // end method
public int getBaseMagicAtt()
{
return magicAtt;
} // end method
public int getBaseDef()
{
return def;
} // end method
public int getBaseMagicDef()
{
return magicDef;
} // end method
public int getBaseSpd()
{
return spd;
} // end method
public int getBaseEvasion()
{
return evasion;
} // end method
public int getBaseAccuracy()
{
return accuracy;
} // end method
public String toString()
{
return name +
"\natt: " + att +
"\nmagAtt: " + magicAtt +
"\ndef: " + def +
"\nmagDef: " + magicDef +
"\nspd: " + spd +
"\neva: " + evasion +
"\nacc: " + accuracy +
"\nmaxHP: " + maxHP +
"\nHP: " + HP +
"\nmaxSP: " + maxSP +
"\nSP: " + SP;
/*return "Lvl " + lvl + " Hero: " + getName() +
"\nexp: " + exp + "\t\texpToNextLvl: " + expToLvl +
"\nHP: " + getHP() + " / " + getMaxHP() + eStat[7] +
"\nSP: " + getSP() + " / " + getMaxSP() + eStat[8] + "\n" +
"\natt: " + getAtt() + eStat[0] +
"\nmagAtt: " + getMagicAtt() + eStat[1] +
"\ndef: " + getDef() + eStat[2] +
"\nmagDef: " + getMagicDef() + eStat[3] +
"\nspd: " + getSpd() + eStat[4] +
"\neva: " + getEvasion() + eStat[5] +
"\nacc: " + getAccuracy() + eStat[6];
*/
} // end method toString
/**
* @return the name of the image file for the Character
*/
public abstract String getImage();
} // end class Character
|
UTF-8
|
Java
| 7,988 |
java
|
Character.java
|
Java
|
[] | null |
[] |
public abstract class Character implements Stats
{
private int att;
private int magicAtt;
private int def;
private int magicDef;
private int spd;
private int evasion;
private int accuracy;
private int maxHP;
private int HP;
private int maxSP;
private int SP;
private int tempAttBonus;
private int tempMagicAttBonus;
private int tempDefBonus;
private int tempMagicDefBonus;
private int tempSpdBonus;
private int tempEvasionBonus;
private int tempAccuracyBonus;
private String name;
// public abstract void chooseMove( Character defender );
// public abstract ArrayList<String> getAttacks();
// returns array of attackMove names - use for loop to choose in chooseAttack()
/**
* prints out a dodge message specific to each character
* @param the name of the attack that is being dodged
*/
public abstract void dodge( String attackName );
/**a basic attack move
* @param the enemy to be attacked
*/
public abstract void attack( Character defender );
/**
* an "attack" move that reduces defense and makes the Character gain SP
*/
public void rest()
{
setDefBonus( getDef() / -2 + getDefBonus() );
setMagicDefBonus( getMagicDef() / -2 + getMagicDefBonus() );
setEvasionBonus( getEvasion() / -2 + getEvasionBonus() );
if( getSP() > getMaxSP() )
{
setSP( getMaxSP() );
} // end if
} // end method Rest
/**
* an "attack" move that increases defense
*/
public void guard()
{
System.out.println( name + " Guarded and their defenses increased" );
setDefBonus( getBaseDef() / 2 + getDefBonus() );
setMagicDefBonus( getBaseMagicDef() / 2 + getMagicDefBonus() );
setEvasionBonus( getEvasion() / 2 + getEvasionBonus() );
} // end method Guard
/**
* gain a small amount of SP, meant to be used after every turn
*/
public void gainSP()
{
setSP( getSP() + 3 );
if( getSP() > getMaxSP() )
{
setSP( getMaxSP() );
} // end if
} // end method
/**
* resets the temporaryStatBonuses, like extra def from Guard()
*/
public void resetTempStatBonuses()
{
tempAttBonus = 0;
tempMagicAttBonus = 0;
tempDefBonus = 0;
tempMagicDefBonus = 0;
tempSpdBonus = 0;
tempEvasionBonus = 0;
tempAccuracyBonus = 0;
} // end method resetStatBonuses
/**
* Setters and getters for all Stats
* includes stat bonus getters and setters
* getters for stats add the stat bonus
*/
public void setAttBonus( int att )
{
tempAttBonus = att;
} // end method
public void setMagicAttBonus( int magAtt )
{
tempMagicAttBonus = magAtt;
} // end method
public void setDefBonus( int def )
{
tempDefBonus = def;
} // end method
public void setMagicDefBonus( int magDef )
{
tempMagicDefBonus = magDef;
} // end method
public void setSpdBonus( int spd )
{
tempSpdBonus = spd;
} // end method
public void setEvasionBonus( int evasion )
{
tempEvasionBonus = evasion;
} // end method
public void setAccuracyBonus( int acc )
{
tempAccuracyBonus = acc;
} // end method
public int getAttBonus()
{
return tempAttBonus;
} // end method
public int getMagicAttBonus()
{
return tempMagicAttBonus;
} // end method
public int getDefBonus()
{
return tempDefBonus;
} // end method
public int getMagicDefBonus()
{
return tempMagicDefBonus;
} // end method
public int getSpdBonus()
{
return tempSpdBonus;
} // end method
public int getEvasionBonus()
{
return tempEvasionBonus;
} // end method
public int getAccuracyBonus()
{
return tempAccuracyBonus;
} // end method
public void setAtt( int att )
{
this.att = att;
} // end method
public void setMagicAtt( int magAtt )
{
this.magicAtt = magAtt;
} // end method
public void setDef( int def )
{
this.def = def;
} // end method
public void setMagicDef( int magDef )
{
this.magicDef = magDef;
} // end method
public void setSpd( int spd )
{
this.spd = spd;
} // end method
public void setEvasion( int evasion )
{
this.evasion = evasion;
} // end method
public void setAccuracy( int acc )
{
this.accuracy = acc;
} // end method
public void setMaxHP( int maxHP )
{
this.maxHP = maxHP;
} // end method
public void setHP( int HP )
{
this.HP = HP;
} // end method
public void setMaxSP( int maxSP )
{
this.maxSP = maxSP;
} // end method
public void setSP( int SP )
{
this.SP = SP;
} // end method
public void setName( String name )
{
this.name = name;
} // end method
public int getAtt()
{
return att + tempAttBonus;
} // end method
public int getMagicAtt()
{
return magicAtt + tempMagicAttBonus;
} // end method
public int getDef()
{
return def + tempDefBonus;
} // end method
public int getMagicDef()
{
return magicDef + tempMagicDefBonus;
} // end method
public int getSpd()
{
return spd + tempSpdBonus;
} // end method
public int getEvasion()
{
return evasion + tempEvasionBonus;
} // end method
public int getAccuracy()
{
return accuracy + tempAccuracyBonus;
} // end method
public int getMaxHP()
{
return maxHP;
} // end method
public int getHP()
{
return HP;
} // end method
public int getMaxSP()
{
return maxSP;
} // end method
public int getSP()
{
return SP;
} // end method
public String getName()
{
return name;
} // end method
public int getBaseAtt()
{
return att;
} // end method
public int getBaseMagicAtt()
{
return magicAtt;
} // end method
public int getBaseDef()
{
return def;
} // end method
public int getBaseMagicDef()
{
return magicDef;
} // end method
public int getBaseSpd()
{
return spd;
} // end method
public int getBaseEvasion()
{
return evasion;
} // end method
public int getBaseAccuracy()
{
return accuracy;
} // end method
public String toString()
{
return name +
"\natt: " + att +
"\nmagAtt: " + magicAtt +
"\ndef: " + def +
"\nmagDef: " + magicDef +
"\nspd: " + spd +
"\neva: " + evasion +
"\nacc: " + accuracy +
"\nmaxHP: " + maxHP +
"\nHP: " + HP +
"\nmaxSP: " + maxSP +
"\nSP: " + SP;
/*return "Lvl " + lvl + " Hero: " + getName() +
"\nexp: " + exp + "\t\texpToNextLvl: " + expToLvl +
"\nHP: " + getHP() + " / " + getMaxHP() + eStat[7] +
"\nSP: " + getSP() + " / " + getMaxSP() + eStat[8] + "\n" +
"\natt: " + getAtt() + eStat[0] +
"\nmagAtt: " + getMagicAtt() + eStat[1] +
"\ndef: " + getDef() + eStat[2] +
"\nmagDef: " + getMagicDef() + eStat[3] +
"\nspd: " + getSpd() + eStat[4] +
"\neva: " + getEvasion() + eStat[5] +
"\nacc: " + getAccuracy() + eStat[6];
*/
} // end method toString
/**
* @return the name of the image file for the Character
*/
public abstract String getImage();
} // end class Character
| 7,988 | 0.538307 | 0.535428 | 320 | 23.965626 | 15.941751 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28125 | false | false |
7
|
1177fce20980c1ef5a5b8f36d7d51cf4eeb5d5b8
| 37,331,855,763,340 |
0616f78e54c783d12f48900624aa10e2484fd4a1
|
/model-display/src/main/java/cn/edu/ecust/modeldisplay/dto/PositionMessage.java
|
681c4c254376c98c5b22ff82682d4b688b39edd2
|
[] |
no_license
|
makoto1995/model-display
|
https://github.com/makoto1995/model-display
|
ac36b69a18d5397204e8217cf30ee95f3e75314f
|
756e713d01e7ad5a97aa34d43a741a6fab6373bc
|
refs/heads/master
| 2018-11-08T08:56:01.355000 | 2018-08-27T10:48:55 | 2018-08-27T10:48:55 | 121,931,333 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.edu.ecust.modeldisplay.dto;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.Serializable;
public class PositionMessage implements Serializable {
private static final long serialVersionUID = -341658452058700240L;
@JSONField(name = "position")
private float[] position = new float[5];
public PositionMessage() {
}
public PositionMessage(float[] position) {
this.position = position;
}
public float[] getPosition() {
return position;
}
public void setPosition(float[] position) {
this.position = position;
}
}
|
UTF-8
|
Java
| 611 |
java
|
PositionMessage.java
|
Java
|
[] | null |
[] |
package cn.edu.ecust.modeldisplay.dto;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.Serializable;
public class PositionMessage implements Serializable {
private static final long serialVersionUID = -341658452058700240L;
@JSONField(name = "position")
private float[] position = new float[5];
public PositionMessage() {
}
public PositionMessage(float[] position) {
this.position = position;
}
public float[] getPosition() {
return position;
}
public void setPosition(float[] position) {
this.position = position;
}
}
| 611 | 0.685761 | 0.654664 | 27 | 21.629629 | 21.147013 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.296296 | false | false |
7
|
74f231d60a7be594987433b99000e068c26da001
| 39,522,289,059,787 |
a62edf437ba798785ca2caf07661206e2cd44c5e
|
/Prog5_MulMat.java
|
ee7a14a791f7dfec63ced093e018327c1b09985e
|
[] |
no_license
|
chayabangera/javalab
|
https://github.com/chayabangera/javalab
|
e0c1ce217d81f2ead408e458d6bfa7316fb2f405
|
8167be9befebc2fbf8be250e4d276f51d655d4ae
|
refs/heads/master
| 2022-04-01T08:35:20.185000 | 2019-12-22T10:45:19 | 2019-12-22T10:45:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.*;
public class Prog5_MulMat {
Scanner sc = new Scanner(System.in);
int[][] A = new int[10][10], B = new int[10][10], prod = new int[10][10];
int r1, c1, r2, c2, k;
public Prog5_MulMat() {
System.out.printf("Enter the order of the first matrix.\n");
r1 = sc.nextInt();
c1 = sc.nextInt();
System.out.printf("Enter the order of the second matrix.\n");
r2 = sc.nextInt();
c2 = sc.nextInt();
}
void check() {
if (c1 != r2) {
System.out.printf("Matrices cannot be multiplied.\n");
System.exit(0);
}
}
void getdata(){
System.out.printf("Enter the elements of the first matrix.\n");
for(int i=0; i<r1; i++)
for (int j = 0; j < c1; j++)
A[i][j]=sc.nextInt();
System.out.printf("Enter the elements of the second matrix.\n");
for(int i=0; i<r2; i++)
for (int j = 0; j < c2; j++)
B[i][j]=sc.nextInt();
}
void display() {
System.out.printf("The first matrix is\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
System.out.printf(A[i][j] + "\t");
}
System.out.printf("\n");
}
System.out.printf("The second matrix is\n");
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
System.out.printf(B[i][j] + "\t");
}
System.out.printf("\n");
}
System.out.printf("The product matrix is\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
prod[i][j] = 0;
for (int k = 0; k < r2; k++)
prod[i][j] += (A[i][k] * B[k][j]);
System.out.printf(prod[i][j] + "\t");
}
System.out.printf("\n");
}
}
}
|
UTF-8
|
Java
| 1,930 |
java
|
Prog5_MulMat.java
|
Java
|
[] | null |
[] |
import java.util.*;
public class Prog5_MulMat {
Scanner sc = new Scanner(System.in);
int[][] A = new int[10][10], B = new int[10][10], prod = new int[10][10];
int r1, c1, r2, c2, k;
public Prog5_MulMat() {
System.out.printf("Enter the order of the first matrix.\n");
r1 = sc.nextInt();
c1 = sc.nextInt();
System.out.printf("Enter the order of the second matrix.\n");
r2 = sc.nextInt();
c2 = sc.nextInt();
}
void check() {
if (c1 != r2) {
System.out.printf("Matrices cannot be multiplied.\n");
System.exit(0);
}
}
void getdata(){
System.out.printf("Enter the elements of the first matrix.\n");
for(int i=0; i<r1; i++)
for (int j = 0; j < c1; j++)
A[i][j]=sc.nextInt();
System.out.printf("Enter the elements of the second matrix.\n");
for(int i=0; i<r2; i++)
for (int j = 0; j < c2; j++)
B[i][j]=sc.nextInt();
}
void display() {
System.out.printf("The first matrix is\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
System.out.printf(A[i][j] + "\t");
}
System.out.printf("\n");
}
System.out.printf("The second matrix is\n");
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
System.out.printf(B[i][j] + "\t");
}
System.out.printf("\n");
}
System.out.printf("The product matrix is\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
prod[i][j] = 0;
for (int k = 0; k < r2; k++)
prod[i][j] += (A[i][k] * B[k][j]);
System.out.printf(prod[i][j] + "\t");
}
System.out.printf("\n");
}
}
}
| 1,930 | 0.432642 | 0.407772 | 59 | 31.711864 | 20.060966 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.932203 | false | false |
7
|
4cbb5e4b175c3333ed6ce0f0d3ae4bc9d82f138b
| 2,516,850,898,496 |
3d2f154bde54f03892f1121eebc854cca91d06ea
|
/src/com/yhbbs/article/action/PostShow.java
|
b7670cf3711fb83ff7aa160ac8ca8fdc4e640e1b
|
[] |
no_license
|
dalinhuang/yqzuo
|
https://github.com/dalinhuang/yqzuo
|
6bb930cd47fb7cbe9bc8da20b7b3ee7ce6bccc91
|
ebf1f5c8a75831fa7bc7f889193264d9e07050eb
|
refs/heads/master
| 2018-01-08T21:17:33.846000 | 2011-08-04T00:29:08 | 2011-08-04T00:29:08 | 44,392,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yhbbs.article.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import com.yhbbs.article.biz.ArticleBiz;
import com.yhbbs.article.itface.Article;
import com.yhbbs.forum.biz.ForumBiz;
import com.yhbbs.user.itface.bean.UserSession;
import com.yhbbs.utils.Constants;
import com.yhbbs.utils.ReqUtils;
import com.yhbbs.utils.StringUtils;
import com.yhbbs.yhclass.biz.ClassBiz;
/**
* <p>Title:发表和编辑帖子Action</p>
* <li> 根据Session判断用户是否有权发表和编辑帖子
* <li> 普通用户编辑自己的帖子要检查是否在允许时间内
* <li> 编辑帖子分:编辑主题帖子和回复帖子,帖子只有管理员和发帖本人可以编辑
* <li> 该处理包括:post、replay、vote、edit、editr<br>
* <li> 处理成功或失败后分别跳转到相关页面并提示相关信息和操作<br>
* <br><b>WebSite: www.xiyouweb.com</b>
* <br><b>CopyRight: xiyouweb[西游网]</b>
* @author benson
* @version XIYOUWEB-2.0
*/
public class PostShow extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,HttpServletResponse response) {
ActionMessages errors = new ActionMessages();
HttpSession session = request.getSession(true);
UserSession bbsuser = (UserSession) session.getAttribute(Constants.bbsuser);
// 取得参数并后传
String action = ReqUtils.getString(request,"action");
int artId = ReqUtils.getInt(request,"aId");
int forumId = ReqUtils.getInt(request,"fId");
int classId = ReqUtils.getInt(request,"cId");
// begin 判断操作是否合法
boolean option = true;
boolean option2 = true;
String optionStr = "post,replay,vote,edit,editr";
if(optionStr.indexOf(action)==-1)
option = false;
if(classId<1 || forumId<1)
option = false;
else if(artId==0){
if(classId!=ForumBiz.getForumClassId(forumId))
option = false;
}
if(!option){
errors.add("article.edit.wrong.action",new ActionMessage("article.edit.wrong.action"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// end
if(action.equals("replay")||action.equals("edit")||action.equals("editr"))
request.setAttribute("ree","ree");
if(action.equals("post")||action.equals("vote")||action.equals("edit"))
request.setAttribute("pve","pve");
if(action.equals("post")||action.equals("vote")||action.equals("replay"))
request.setAttribute("pvr","pvr");
// 只有登录用户和已经审核用户才可以发表帖子
if(bbsuser==null || bbsuser.getUsertype()<2){
errors.add("article.post.no.login",new ActionMessage("article.post.no.login"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}else if(bbsuser.getIslock().equals("1")){
errors.add("article.post.user.lock",new ActionMessage("article.post.user.lock"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
if(artId!=0){
int userType = 0;
userType = bbsuser.getUsertype();
// 取得要编辑的帖子信息
Article article = null;
int ruserId = 0;
String title = "";
String isvote = "";
String content = "";
article = (Article) ArticleBiz.getArtContent(artId);
if(article==null){
errors.add("article.edit.noexist",new ActionMessage("article.edit.noexist"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// begin 检查classId forumId是否为该帖子信息
int cId = article.getClassid();
int fId = article.getForum();
if(cId!=classId || fId!=forumId)
option2 = false;
if(action.equals("editr")&& article.getParentid()==0)
option2 = false;
if(action.equals("edit")&& article.getParentid()!=0)
option2 = false;
if(!option2){
errors.add("article.edit.wrong.action",new ActionMessage("article.edit.wrong.action"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// end
ruserId = article.getUserid();
title = article.getTitle();
isvote = article.getIsvote();
content = StringUtils.unEncode(article.getContent().getContent());
request.setAttribute("title",title);
request.setAttribute("isvote",isvote);
request.setAttribute("content",content);
// 判断当前用户是否用权编辑该帖子
if(userType>3){
boolean isfAdmin = false;
boolean iscAdmin = false;
String userName = bbsuser.getUsername();
// 判断该版主是否为该论坛或区论坛的版主 ( >=6为总版主和坛主)
if(userType<6){
isfAdmin = ForumBiz.isForumAdmin(forumId,userName);
iscAdmin = ClassBiz.isClassAdmin(classId,userName);
if(!isfAdmin && !iscAdmin){
errors.add("article.edit.not.admin",new ActionMessage("article.edit.not.admin"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
}
// forward
}else if(ruserId==bbsuser.getUserId()){ // 普通用户修改自己帖子
if(!ArticleBiz.isEditAgain(artId)){ // 是否在有效编辑时间内
errors.add("article.edit.time",new ActionMessage("article.edit.time"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// forward
}else{
errors.add("article.edit.user.wrong",new ActionMessage("article.edit.user.wrong"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
}
request.setAttribute("artId", artId);
request.setAttribute("forumId", forumId);
request.setAttribute("classId", classId);
request.setAttribute("action", action);
this.saveToken(request);
return mapping.findForward("Success");
}
}
|
UTF-8
|
Java
| 6,416 |
java
|
PostShow.java
|
Java
|
[
{
"context": " * <br><b>CopyRight: xiyouweb[西游网]</b>\r\n * @author benson\r\n * @version XIYOUWEB-2.0\r\n */\r\npublic class Post",
"end": 1101,
"score": 0.9994934797286987,
"start": 1095,
"tag": "USERNAME",
"value": "benson"
},
{
"context": "\tboolean iscAdmin = false;\r\n\t\t\t\t\tString userName = bbsuser.getUsername();\r\n\t\t\t\t\t//\t判断该版主是否为该论坛或区论坛的版主 ( >=6为",
"end": 4710,
"score": 0.9883837103843689,
"start": 4703,
"tag": "USERNAME",
"value": "bbsuser"
},
{
"context": "iscAdmin = false;\r\n\t\t\t\t\tString userName = bbsuser.getUsername();\r\n\t\t\t\t\t//\t判断该版主是否为该论坛或区论坛的版主 ( >=6为总版主和坛主)\r\n\t\t\t",
"end": 4722,
"score": 0.9292984008789062,
"start": 4711,
"tag": "USERNAME",
"value": "getUsername"
}
] | null |
[] |
package com.yhbbs.article.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import com.yhbbs.article.biz.ArticleBiz;
import com.yhbbs.article.itface.Article;
import com.yhbbs.forum.biz.ForumBiz;
import com.yhbbs.user.itface.bean.UserSession;
import com.yhbbs.utils.Constants;
import com.yhbbs.utils.ReqUtils;
import com.yhbbs.utils.StringUtils;
import com.yhbbs.yhclass.biz.ClassBiz;
/**
* <p>Title:发表和编辑帖子Action</p>
* <li> 根据Session判断用户是否有权发表和编辑帖子
* <li> 普通用户编辑自己的帖子要检查是否在允许时间内
* <li> 编辑帖子分:编辑主题帖子和回复帖子,帖子只有管理员和发帖本人可以编辑
* <li> 该处理包括:post、replay、vote、edit、editr<br>
* <li> 处理成功或失败后分别跳转到相关页面并提示相关信息和操作<br>
* <br><b>WebSite: www.xiyouweb.com</b>
* <br><b>CopyRight: xiyouweb[西游网]</b>
* @author benson
* @version XIYOUWEB-2.0
*/
public class PostShow extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,HttpServletResponse response) {
ActionMessages errors = new ActionMessages();
HttpSession session = request.getSession(true);
UserSession bbsuser = (UserSession) session.getAttribute(Constants.bbsuser);
// 取得参数并后传
String action = ReqUtils.getString(request,"action");
int artId = ReqUtils.getInt(request,"aId");
int forumId = ReqUtils.getInt(request,"fId");
int classId = ReqUtils.getInt(request,"cId");
// begin 判断操作是否合法
boolean option = true;
boolean option2 = true;
String optionStr = "post,replay,vote,edit,editr";
if(optionStr.indexOf(action)==-1)
option = false;
if(classId<1 || forumId<1)
option = false;
else if(artId==0){
if(classId!=ForumBiz.getForumClassId(forumId))
option = false;
}
if(!option){
errors.add("article.edit.wrong.action",new ActionMessage("article.edit.wrong.action"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// end
if(action.equals("replay")||action.equals("edit")||action.equals("editr"))
request.setAttribute("ree","ree");
if(action.equals("post")||action.equals("vote")||action.equals("edit"))
request.setAttribute("pve","pve");
if(action.equals("post")||action.equals("vote")||action.equals("replay"))
request.setAttribute("pvr","pvr");
// 只有登录用户和已经审核用户才可以发表帖子
if(bbsuser==null || bbsuser.getUsertype()<2){
errors.add("article.post.no.login",new ActionMessage("article.post.no.login"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}else if(bbsuser.getIslock().equals("1")){
errors.add("article.post.user.lock",new ActionMessage("article.post.user.lock"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
if(artId!=0){
int userType = 0;
userType = bbsuser.getUsertype();
// 取得要编辑的帖子信息
Article article = null;
int ruserId = 0;
String title = "";
String isvote = "";
String content = "";
article = (Article) ArticleBiz.getArtContent(artId);
if(article==null){
errors.add("article.edit.noexist",new ActionMessage("article.edit.noexist"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// begin 检查classId forumId是否为该帖子信息
int cId = article.getClassid();
int fId = article.getForum();
if(cId!=classId || fId!=forumId)
option2 = false;
if(action.equals("editr")&& article.getParentid()==0)
option2 = false;
if(action.equals("edit")&& article.getParentid()!=0)
option2 = false;
if(!option2){
errors.add("article.edit.wrong.action",new ActionMessage("article.edit.wrong.action"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// end
ruserId = article.getUserid();
title = article.getTitle();
isvote = article.getIsvote();
content = StringUtils.unEncode(article.getContent().getContent());
request.setAttribute("title",title);
request.setAttribute("isvote",isvote);
request.setAttribute("content",content);
// 判断当前用户是否用权编辑该帖子
if(userType>3){
boolean isfAdmin = false;
boolean iscAdmin = false;
String userName = bbsuser.getUsername();
// 判断该版主是否为该论坛或区论坛的版主 ( >=6为总版主和坛主)
if(userType<6){
isfAdmin = ForumBiz.isForumAdmin(forumId,userName);
iscAdmin = ClassBiz.isClassAdmin(classId,userName);
if(!isfAdmin && !iscAdmin){
errors.add("article.edit.not.admin",new ActionMessage("article.edit.not.admin"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
}
// forward
}else if(ruserId==bbsuser.getUserId()){ // 普通用户修改自己帖子
if(!ArticleBiz.isEditAgain(artId)){ // 是否在有效编辑时间内
errors.add("article.edit.time",new ActionMessage("article.edit.time"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
// forward
}else{
errors.add("article.edit.user.wrong",new ActionMessage("article.edit.user.wrong"));
saveErrors(request,errors);
return mapping.findForward("Failure");
}
}
request.setAttribute("artId", artId);
request.setAttribute("forumId", forumId);
request.setAttribute("classId", classId);
request.setAttribute("action", action);
this.saveToken(request);
return mapping.findForward("Success");
}
}
| 6,416 | 0.654894 | 0.651362 | 158 | 35.632912 | 21.324009 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.892405 | false | false |
7
|
c763aba5643149621d03f3693ef24536541c1711
| 35,966,056,177,645 |
51ca49bb5cfc5220d8af834756d3962450205067
|
/src/org/waveprotocol/wave/client/scheduler/knobs/KnobView.java
|
a6ecc80a96ec8c96a43b0df38eb54b5438f3088c
|
[
"Apache-2.0"
] |
permissive
|
vega113/WaveInCloud
|
https://github.com/vega113/WaveInCloud
|
c08f2e33503511e9754888ad63b2a674f348300b
|
7a240021b931b240c33dca0b8443152fb82e0487
|
refs/heads/master
| 2021-01-01T17:47:13.719000 | 2011-11-15T18:00:21 | 2011-11-15T18:00:21 | 1,935,818 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Copyright 2009 Google Inc.
*
* 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.waveprotocol.wave.client.scheduler.knobs;
import org.waveprotocol.wave.client.scheduler.Scheduler.Priority;
import org.waveprotocol.wave.model.util.ReadableStringSet;
import java.util.Collection;
/**
* View interface for a singl priority-level UI control.
*
*/
public interface KnobView {
/**
* Receiver of UI events.
*/
interface Listener {
void onClicked();
void onDetailsClicked();
void onClearClicked();
void onToggleTask(String name);
}
/**
* Creator of views.
*/
interface Factory {
/**
* Creates a UI component for a single priority level.
*
* @param priority level being controlled
* @return a new view for level {@code priority}.
*/
KnobView create(Priority priority);
}
/**
* Starts using this view.
*
* @param listener event receiver
*/
void init(Listener listener);
/**
* Stops using this view.
*/
void reset();
/**
* Shows this level as being enabled.
*/
void enable();
/**
* Shows this level as being disabled.
*/
void disable();
/**
* Shows the number of jobs in this priority level.
*
* @param count job count
*/
void showCount(int count);
/**
* Shows/updates the names of jobs running / having run.
*
* @param currentJobs
* @param oldJobs
* @param suppressedJobs current and old jobs that won't run
*/
void showJobs(Collection<String> currentJobs, Collection<String> oldJobs,
ReadableStringSet suppressedJobs);
/**
* Hides the job name details.
*/
void hideJobs();
}
|
UTF-8
|
Java
| 2,188 |
java
|
KnobView.java
|
Java
|
[] | null |
[] |
/**
* Copyright 2009 Google Inc.
*
* 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.waveprotocol.wave.client.scheduler.knobs;
import org.waveprotocol.wave.client.scheduler.Scheduler.Priority;
import org.waveprotocol.wave.model.util.ReadableStringSet;
import java.util.Collection;
/**
* View interface for a singl priority-level UI control.
*
*/
public interface KnobView {
/**
* Receiver of UI events.
*/
interface Listener {
void onClicked();
void onDetailsClicked();
void onClearClicked();
void onToggleTask(String name);
}
/**
* Creator of views.
*/
interface Factory {
/**
* Creates a UI component for a single priority level.
*
* @param priority level being controlled
* @return a new view for level {@code priority}.
*/
KnobView create(Priority priority);
}
/**
* Starts using this view.
*
* @param listener event receiver
*/
void init(Listener listener);
/**
* Stops using this view.
*/
void reset();
/**
* Shows this level as being enabled.
*/
void enable();
/**
* Shows this level as being disabled.
*/
void disable();
/**
* Shows the number of jobs in this priority level.
*
* @param count job count
*/
void showCount(int count);
/**
* Shows/updates the names of jobs running / having run.
*
* @param currentJobs
* @param oldJobs
* @param suppressedJobs current and old jobs that won't run
*/
void showJobs(Collection<String> currentJobs, Collection<String> oldJobs,
ReadableStringSet suppressedJobs);
/**
* Hides the job name details.
*/
void hideJobs();
}
| 2,188 | 0.667276 | 0.66362 | 97 | 21.556702 | 22.601418 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.237113 | false | false |
7
|
2aaa21620607dda500163f57e92213c294ddaaf9
| 5,291,399,776,124 |
0a19ee8121ec0e6dd0517bdf7b2d11bdc7556a27
|
/MarketPlaceIngenium/jdeveloperApps/MarketPlacePortlets/Portlets/src/co/com/co/com/types/CrearSubasta.java
|
c4dec264841d69edb77163b372d367a8c374dd48
|
[] |
no_license
|
leseroth/ingenium-managment
|
https://github.com/leseroth/ingenium-managment
|
2a751a24f83e7cf8fb2fe42826a9e46ba9034bd0
|
c34c8efa0d4cf8b095c792e1e7198f3f78c3ea15
|
refs/heads/master
| 2021-01-25T05:35:30.176000 | 2011-12-11T23:41:40 | 2011-12-11T23:41:40 | 38,320,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package co.com.co.com.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for crearSubasta complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="crearSubasta">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="po" type="{http://ws.transact.marketplace.losalpes.com.co/}purchaseOrderBO" minOccurs="0"/>
* <element name="fechaMax" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "crearSubasta", namespace = "http://ws.transact.marketplace.losalpes.com.co/", propOrder = {
"po",
"fechaMax"
})
public class CrearSubasta {
protected PurchaseOrderBO po;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar fechaMax;
/**
* Gets the value of the po property.
*
* @return
* possible object is
* {@link PurchaseOrderBO }
*
*/
public PurchaseOrderBO getPo() {
return po;
}
/**
* Sets the value of the po property.
*
* @param value
* allowed object is
* {@link PurchaseOrderBO }
*
*/
public void setPo(PurchaseOrderBO value) {
this.po = value;
}
/**
* Gets the value of the fechaMax property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFechaMax() {
return fechaMax;
}
/**
* Sets the value of the fechaMax property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFechaMax(XMLGregorianCalendar value) {
this.fechaMax = value;
}
}
|
UTF-8
|
Java
| 2,337 |
java
|
CrearSubasta.java
|
Java
|
[] | null |
[] |
package co.com.co.com.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for crearSubasta complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="crearSubasta">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="po" type="{http://ws.transact.marketplace.losalpes.com.co/}purchaseOrderBO" minOccurs="0"/>
* <element name="fechaMax" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "crearSubasta", namespace = "http://ws.transact.marketplace.losalpes.com.co/", propOrder = {
"po",
"fechaMax"
})
public class CrearSubasta {
protected PurchaseOrderBO po;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar fechaMax;
/**
* Gets the value of the po property.
*
* @return
* possible object is
* {@link PurchaseOrderBO }
*
*/
public PurchaseOrderBO getPo() {
return po;
}
/**
* Sets the value of the po property.
*
* @param value
* allowed object is
* {@link PurchaseOrderBO }
*
*/
public void setPo(PurchaseOrderBO value) {
this.po = value;
}
/**
* Gets the value of the fechaMax property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getFechaMax() {
return fechaMax;
}
/**
* Sets the value of the fechaMax property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFechaMax(XMLGregorianCalendar value) {
this.fechaMax = value;
}
}
| 2,337 | 0.589217 | 0.584082 | 89 | 24.235954 | 24.72547 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.280899 | false | false |
7
|
3cf1bc85e0d1363d89f4f7ec83a86e5d3f167702
| 3,899,830,337,377 |
7b10b4eb69600fc8e18ddf9d63b5c9ee1bcd99ee
|
/src/test/java/Modules/Sign_In.java
|
1fb361e0b9f86abcc46ba1f1f71097e13a4dba91
|
[] |
no_license
|
mhanda24/Cucumber
|
https://github.com/mhanda24/Cucumber
|
db9bfb20f541540bdb060c76a3ee32593f74ddf7
|
8512ada785c7451dfb46b95179dde59b96ce44ca
|
refs/heads/master
| 2021-08-30T17:34:58.182000 | 2017-12-18T20:49:52 | 2017-12-18T20:49:52 | 114,686,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Modules;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import PasswordGenerator.PwdEncryption;
public class Sign_In {
public static void Execute(WebDriver driver, Properties OR, String username, String password){
PwdEncryption pass = new PwdEncryption(driver);
driver.findElement(By.id(OR.getProperty("username"))).sendKeys(username);
driver.findElement(By.id(OR.getProperty("password"))).sendKeys(pass.pwdDecode(password));
driver.findElement(By.cssSelector(OR.getProperty("button"))).click();
}
}
|
UTF-8
|
Java
| 575 |
java
|
Sign_In.java
|
Java
|
[] | null |
[] |
package Modules;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import PasswordGenerator.PwdEncryption;
public class Sign_In {
public static void Execute(WebDriver driver, Properties OR, String username, String password){
PwdEncryption pass = new PwdEncryption(driver);
driver.findElement(By.id(OR.getProperty("username"))).sendKeys(username);
driver.findElement(By.id(OR.getProperty("password"))).sendKeys(pass.pwdDecode(password));
driver.findElement(By.cssSelector(OR.getProperty("button"))).click();
}
}
| 575 | 0.77913 | 0.77913 | 19 | 29.263159 | 31.971767 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.157895 | false | false |
7
|
5e758e8c5ebc77a873eb197ae00ce5ad49c3eecb
| 9,706,626,118,715 |
86564c756d18189b84213be5fafcd45cce9133cc
|
/src/main/java/net/dqsy/papermg/util/MD5Encoder.java
|
c9afeec2a5af01e38533c89275967678c6d6e283
|
[] |
no_license
|
haojungit/paper
|
https://github.com/haojungit/paper
|
68a8cc79b546c2986f582c619b1c1bafde507cb8
|
b7d367e818dab4d5906e37011477ab0e5dd6ff33
|
refs/heads/dev
| 2021-01-11T20:53:22.327000 | 2016-12-12T14:44:59 | 2016-12-12T14:44:59 | 79,204,658 | 4 | 2 | null | true | 2017-01-17T08:17:53 | 2017-01-17T08:17:53 | 2017-01-17T08:17:48 | 2016-12-12T14:45:10 | 1,596 | 0 | 0 | 0 | null | null | null |
package net.dqsy.papermg.util;
import java.security.MessageDigest;
public class MD5Encoder {
public static String encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = md.digest(resultString.getBytes());
resultString = byte2hexString(b);
} catch (Exception localException) {
}
return resultString;
}
private static final String byte2hexString(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xFF) < 16) {
buf.append("0");
}
buf.append(Long.toString(bytes[i] & 0xFF, 16));
}
return buf.toString();
}
public static void main(String[] args) {
System.out
.print("123456字符串经过加密后成了:" + encode("123456"));
}
}
|
UTF-8
|
Java
| 1,044 |
java
|
MD5Encoder.java
|
Java
|
[] | null |
[] |
package net.dqsy.papermg.util;
import java.security.MessageDigest;
public class MD5Encoder {
public static String encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = md.digest(resultString.getBytes());
resultString = byte2hexString(b);
} catch (Exception localException) {
}
return resultString;
}
private static final String byte2hexString(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if ((bytes[i] & 0xFF) < 16) {
buf.append("0");
}
buf.append(Long.toString(bytes[i] & 0xFF, 16));
}
return buf.toString();
}
public static void main(String[] args) {
System.out
.print("123456字符串经过加密后成了:" + encode("123456"));
}
}
| 1,044 | 0.569336 | 0.544922 | 34 | 29.147058 | 22.393713 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false |
7
|
de4cbfe1b3d11be2e420ea2db3c3867f3a3838b4
| 4,535,485,501,685 |
0e40997a79f71b26d41c94049420fcaca281a160
|
/HW4-RetailFoodStarter/src/sorting/EntryNameComparator.java
|
e5d049330230708371810a976fe9d716575a5cbb
|
[] |
no_license
|
camerongilinsky/CompSci2
|
https://github.com/camerongilinsky/CompSci2
|
152be2d9445c719274660615387c124ef90f7fa3
|
b135fafe05b613f940d0746ba092e279b8080d36
|
refs/heads/master
| 2020-04-17T06:31:16.105000 | 2019-04-21T16:26:52 | 2019-04-21T16:26:52 | 166,328,320 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// COURSE: CSCI1620
// TERM: Spring 2019
//
// NAME: Cameron Gilinsky and Carter Kennell
// RESOURCES: Piazza discussion board posts by the
// students and instructors for this class.
package sorting;
import java.util.Comparator;
import schedules.RetailFoodEntry;
/**
* A Comparator for the Name element of a RetailFoodEntry.
* @author Derek Babb
*/
public class EntryNameComparator implements Comparator<RetailFoodEntry>
{
/**
* Comparison method will take in two RetailFoodEntry objects and compare the
* Name of each of them. Names are ordered based on their standard
* lexicographic ordering.
*
* @param a The first RetailFoodEntry
* @param b The second RetailFoodEntry
* @return a negative integer, zero, or a positive integer as the first argument is less
* than, equal to, or greater than the second.
*/
public int compare(RetailFoodEntry a, RetailFoodEntry b)
{
if (a != null && b != null)
{
return a.getName().compareTo(b.getName());
}
else
{
return 0;
}
}
}
|
UTF-8
|
Java
| 1,020 |
java
|
EntryNameComparator.java
|
Java
|
[
{
"context": " COURSE: CSCI1620\n// TERM: Spring 2019\n//\n// NAME: Cameron Gilinsky and Carter Kennell\n// RESOURCES: Piazza discussio",
"end": 69,
"score": 0.9998512268066406,
"start": 53,
"tag": "NAME",
"value": "Cameron Gilinsky"
},
{
"context": "TERM: Spring 2019\n//\n// NAME: Cameron Gilinsky and Carter Kennell\n// RESOURCES: Piazza discussion board posts by th",
"end": 88,
"score": 0.9998588562011719,
"start": 74,
"tag": "NAME",
"value": "Carter Kennell"
},
{
"context": " the Name element of a RetailFoodEntry.\n * @author Derek Babb\n */\npublic class EntryNameComparator implements C",
"end": 355,
"score": 0.9998675584793091,
"start": 345,
"tag": "NAME",
"value": "Derek Babb"
}
] | null |
[] |
// COURSE: CSCI1620
// TERM: Spring 2019
//
// NAME: <NAME> and <NAME>
// RESOURCES: Piazza discussion board posts by the
// students and instructors for this class.
package sorting;
import java.util.Comparator;
import schedules.RetailFoodEntry;
/**
* A Comparator for the Name element of a RetailFoodEntry.
* @author <NAME>
*/
public class EntryNameComparator implements Comparator<RetailFoodEntry>
{
/**
* Comparison method will take in two RetailFoodEntry objects and compare the
* Name of each of them. Names are ordered based on their standard
* lexicographic ordering.
*
* @param a The first RetailFoodEntry
* @param b The second RetailFoodEntry
* @return a negative integer, zero, or a positive integer as the first argument is less
* than, equal to, or greater than the second.
*/
public int compare(RetailFoodEntry a, RetailFoodEntry b)
{
if (a != null && b != null)
{
return a.getName().compareTo(b.getName());
}
else
{
return 0;
}
}
}
| 998 | 0.714706 | 0.705882 | 41 | 23.902439 | 25.134569 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.097561 | false | false |
7
|
29107393242dcad3371f9f3d2c9c07b161fcec76
| 11,845,519,830,689 |
ee55acf9bd47d96a4dd5fc956d5ed01a1abfde34
|
/CouponActivityRetVo.java
|
93232c1f160ed2400a478cfeb40a49943dc38fba
|
[] |
no_license
|
lizeqi-sudo/ooad
|
https://github.com/lizeqi-sudo/ooad
|
c8879b98c0669e04cc62df2e993352157e219551
|
a5d49a5cc4bd170c9a91f050fd43c0eb527a5c8a
|
refs/heads/main
| 2023-02-03T11:39:53.112000 | 2020-12-24T03:57:45 | 2020-12-24T03:57:45 | 324,046,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.edu.xmu.goods.model.vo;
import cn.edu.xmu.goods.model.bo.CouponActivity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Data
@ApiModel(description = "优惠活动视图对象")
public class CouponActivityRetVo {
@ApiModelProperty(value = "优惠活动id")
private Long id;
@ApiModelProperty(value = "优惠活动名称")
private String name;
@ApiModelProperty(value = "优惠活动开始时间")
private String beginTime;
@ApiModelProperty(value = "优惠活动结束时间")
private String endTime;
@ApiModelProperty(value = "优惠活动发放优惠券时间")
private String couponTime;
@ApiModelProperty(value = "优惠活动所属商店id")
private Long shopId;
@ApiModelProperty(value = "优惠活动发放优惠券数量")
private Integer quantity;
@ApiModelProperty(value = "优惠活动发放时间类型")
private Byte validTerm;
@ApiModelProperty(value = "优惠活动图片url")
private String imageUrl;
@ApiModelProperty(value = "优惠活动策略")
private String strategy;
@ApiModelProperty(value = "优惠活动创建者")
private Long createdBy;
@ApiModelProperty(value = "优惠活动上次修改者")
private Long modifyBy;
@ApiModelProperty(value = "优惠活动创建时间")
private String gmtCreated;
@ApiModelProperty(value = "优惠活动上次修改时间")
private String gmtModified;
@ApiModelProperty(value = "优惠活动数量类型")
private Byte quantityType;
@ApiModelProperty(value = "优惠活动状态")
private Byte state;
public CouponActivityRetVo(CouponActivity couponActivity) {
this.id = couponActivity.getId();
this.name = couponActivity.getName();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.beginTime = df.format(couponActivity.getBeginTime());
this.endTime = df.format(couponActivity.getEndTime());
this.couponTime = df.format(couponActivity.getCouponTime());
this.shopId = couponActivity.getShopId();
this.quantity = couponActivity.getQuantity();
this.validTerm =couponActivity.getValidTerm();
this.imageUrl = couponActivity.getImageUrl();
this.strategy = couponActivity.getStrategy();
this.createdBy = couponActivity.getCreatedBy();
this.modifyBy = couponActivity.getModifyBy();
this.gmtCreated = df.format(couponActivity.getGmtCreated());
this.gmtModified =df.format(couponActivity.getGmtModified());
this.quantityType = couponActivity.getQuantityType();
this.state = couponActivity.getState().getCode();
}
}
|
UTF-8
|
Java
| 2,894 |
java
|
CouponActivityRetVo.java
|
Java
|
[] | null |
[] |
package cn.edu.xmu.goods.model.vo;
import cn.edu.xmu.goods.model.bo.CouponActivity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Data
@ApiModel(description = "优惠活动视图对象")
public class CouponActivityRetVo {
@ApiModelProperty(value = "优惠活动id")
private Long id;
@ApiModelProperty(value = "优惠活动名称")
private String name;
@ApiModelProperty(value = "优惠活动开始时间")
private String beginTime;
@ApiModelProperty(value = "优惠活动结束时间")
private String endTime;
@ApiModelProperty(value = "优惠活动发放优惠券时间")
private String couponTime;
@ApiModelProperty(value = "优惠活动所属商店id")
private Long shopId;
@ApiModelProperty(value = "优惠活动发放优惠券数量")
private Integer quantity;
@ApiModelProperty(value = "优惠活动发放时间类型")
private Byte validTerm;
@ApiModelProperty(value = "优惠活动图片url")
private String imageUrl;
@ApiModelProperty(value = "优惠活动策略")
private String strategy;
@ApiModelProperty(value = "优惠活动创建者")
private Long createdBy;
@ApiModelProperty(value = "优惠活动上次修改者")
private Long modifyBy;
@ApiModelProperty(value = "优惠活动创建时间")
private String gmtCreated;
@ApiModelProperty(value = "优惠活动上次修改时间")
private String gmtModified;
@ApiModelProperty(value = "优惠活动数量类型")
private Byte quantityType;
@ApiModelProperty(value = "优惠活动状态")
private Byte state;
public CouponActivityRetVo(CouponActivity couponActivity) {
this.id = couponActivity.getId();
this.name = couponActivity.getName();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
this.beginTime = df.format(couponActivity.getBeginTime());
this.endTime = df.format(couponActivity.getEndTime());
this.couponTime = df.format(couponActivity.getCouponTime());
this.shopId = couponActivity.getShopId();
this.quantity = couponActivity.getQuantity();
this.validTerm =couponActivity.getValidTerm();
this.imageUrl = couponActivity.getImageUrl();
this.strategy = couponActivity.getStrategy();
this.createdBy = couponActivity.getCreatedBy();
this.modifyBy = couponActivity.getModifyBy();
this.gmtCreated = df.format(couponActivity.getGmtCreated());
this.gmtModified =df.format(couponActivity.getGmtModified());
this.quantityType = couponActivity.getQuantityType();
this.state = couponActivity.getState().getCode();
}
}
| 2,894 | 0.69345 | 0.69345 | 70 | 35.514286 | 19.561436 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
7
|
8fe4b10fa4b9d98fd709a12b19fa21ccf429516e
| 8,899,172,241,863 |
1946b53423645b2cb8c381eb6c27b34f4d198e34
|
/spring-jdbc/src/main/java/org/springframework/jdbc/support/SqlArrayValue.java
|
a6834efaed897cc872d16625de9fc5e7b91d1ee9
|
[
"Apache-2.0"
] |
permissive
|
spring-projects/spring-framework
|
https://github.com/spring-projects/spring-framework
|
e0bf18593af55a5cddd57efbb86ebe5da8a8f38e
|
759e3d4aa6e4e8154f6428e496275bcd89431bba
|
refs/heads/main
| 2023-09-03T07:44:34.908000 | 2023-09-03T00:32:01 | 2023-09-03T00:32:01 | 1,148,753 | 56,403 | 43,516 |
Apache-2.0
| false | 2023-09-14T15:45:05 | 2010-12-08T04:04:45 | 2023-09-14T13:57:45 | 2023-09-14T15:45:03 | 197,376 | 53,106 | 36,868 | 1,183 |
Java
| false | false |
/*
* Copyright 2002-2023 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Common {@link SqlValue} implementation for JDBC {@link Array} creation
* based on the JDBC 4 {@link java.sql.Connection#createArrayOf} method.
*
* <p>Also serves as a template for custom {@link SqlValue} implementations
* with cleanup demand.
*
* @author Juergen Hoeller
* @author Philippe Marschall
* @since 6.1
*/
public class SqlArrayValue implements SqlValue {
private final String typeName;
private final Object[] elements;
@Nullable
private Array array;
/**
* Create a new {@code SqlArrayValue} for the given type name and elements.
* @param typeName the SQL name of the type the elements of the array map to
* @param elements the elements to populate the {@code Array} object with
* @see java.sql.Connection#createArrayOf
*/
public SqlArrayValue(String typeName, Object... elements) {
Assert.notNull(typeName, "Type name must not be null");
Assert.notNull(elements, "Elements array must not be null");
this.typeName = typeName;
this.elements = elements;
}
@Override
public void setValue(PreparedStatement ps, int paramIndex) throws SQLException {
this.array = ps.getConnection().createArrayOf(this.typeName, this.elements);
ps.setArray(paramIndex, this.array);
}
@Override
public void cleanup() {
if (this.array != null) {
try {
this.array.free();
}
catch (SQLException ex) {
throw new DataAccessResourceFailureException("Could not free Array object", ex);
}
}
}
}
|
UTF-8
|
Java
| 2,361 |
java
|
SqlArrayValue.java
|
Java
|
[
{
"context": "lementations\n * with cleanup demand.\n *\n * @author Juergen Hoeller\n * @author Philippe Marschall\n * @since 6.1\n */\np",
"end": 1188,
"score": 0.9998031854629517,
"start": 1173,
"tag": "NAME",
"value": "Juergen Hoeller"
},
{
"context": "p demand.\n *\n * @author Juergen Hoeller\n * @author Philippe Marschall\n * @since 6.1\n */\npublic class SqlArrayValue impl",
"end": 1218,
"score": 0.9998170733451843,
"start": 1200,
"tag": "NAME",
"value": "Philippe Marschall"
}
] | null |
[] |
/*
* Copyright 2002-2023 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Common {@link SqlValue} implementation for JDBC {@link Array} creation
* based on the JDBC 4 {@link java.sql.Connection#createArrayOf} method.
*
* <p>Also serves as a template for custom {@link SqlValue} implementations
* with cleanup demand.
*
* @author <NAME>
* @author <NAME>
* @since 6.1
*/
public class SqlArrayValue implements SqlValue {
private final String typeName;
private final Object[] elements;
@Nullable
private Array array;
/**
* Create a new {@code SqlArrayValue} for the given type name and elements.
* @param typeName the SQL name of the type the elements of the array map to
* @param elements the elements to populate the {@code Array} object with
* @see java.sql.Connection#createArrayOf
*/
public SqlArrayValue(String typeName, Object... elements) {
Assert.notNull(typeName, "Type name must not be null");
Assert.notNull(elements, "Elements array must not be null");
this.typeName = typeName;
this.elements = elements;
}
@Override
public void setValue(PreparedStatement ps, int paramIndex) throws SQLException {
this.array = ps.getConnection().createArrayOf(this.typeName, this.elements);
ps.setArray(paramIndex, this.array);
}
@Override
public void cleanup() {
if (this.array != null) {
try {
this.array.free();
}
catch (SQLException ex) {
throw new DataAccessResourceFailureException("Could not free Array object", ex);
}
}
}
}
| 2,340 | 0.738247 | 0.731893 | 80 | 28.512501 | 27.930716 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.05 | false | false |
7
|
ef2d27aa66f73721042f049c37489155782c42e5
| 1,992,864,890,018 |
7884724d5e29f2d2b137cf46ce9839409534ab4c
|
/lab05/src/mc322/lab05/Tabuleiro.java
|
b11997f52caa3657c0609ee6ae8fbc4db8a81270
|
[] |
no_license
|
dan7sc/danaoop
|
https://github.com/dan7sc/danaoop
|
6e80ddccc1e6a6359bf510bfa8adb6814ffd6dbc
|
b6dd27b537acf7ce9f5e3c13e55d5f9abce33e4c
|
refs/heads/main
| 2023-06-05T01:53:09.743000 | 2021-06-17T19:23:12 | 2021-06-17T19:23:12 | 363,170,476 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mc322.lab05;
public class Tabuleiro {
static final int NUM_PECAS = 24;
static final int LIN = 9;
static final int COL = 9;
static final char[] colunas = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\n' };
static final char[] linhas = { '8', '7', '6', '5', '4', '3', '2', '1', '\n' };
static final String inicio = "-p-p-p-p\np-p-p-p-\n-p-p-p-p\n--------\n--------\nb-b-b-b-\n-b-b-b-b\nb-b-b-b-\n";
char[][] casas = new char[LIN][COL];
Peca[] pecas = new Peao[NUM_PECAS];
public Tabuleiro() {
for(int i = 0; i < LIN; i++) {
for(int j = 0; j < COL; j++) {
if(i*COL+j < 72 && inicio.charAt(i*COL+j) != '\n') {
casas[i][j] = inicio.charAt(i*COL+j);
}
}
}
}
public String imprime() {
String jogada = new String();
for(int i = 0; i < LIN - 1; i++) {
// Imprime numeros das linhas do tabuleiro
System.out.print(linhas[i]);
// Imprime tabuleiro
for(int j = 0; j < COL - 1; j++) {
jogada = jogada.concat("" + casas[i][j]);
System.out.print(" " + casas[i][j]);
}
jogada = jogada.concat("" + '\n');
System.out.println();
}
System.out.print(" ");
// Imprime numero das colunas do tabuleiro
for(int i = 0; i < COL; i++) {
System.out.print(" " + colunas[i]);
}
System.out.println();
return jogada;
}
public boolean ehPermitidoPeca(int lin, int col) {
if(casas[lin][col] == '-') {
return false;
}
return true;
}
public void adicionaPecas() {
String posicao;
char cor;
int indice = 0;
for(int i = 0; i < LIN - 1; i++) {
for(int j = 0; j < COL - 1; j++) {
if(ehPermitidoPeca(i, j)) {
posicao = "" + colunas[j] + linhas[i];
cor = casas[i][j];
pecas[indice++] = new Peao(posicao, cor);
}
}
}
}
public void imprimeJogada(String movimento) {
System.out.println("Source: " + movimento.charAt(0) + movimento.charAt(1));
System.out.println("Target: " + movimento.charAt(3) + movimento.charAt(4));
}
public Peca buscaPeca(Posicao posicao) {
for(int i = 0; i < NUM_PECAS; i++) {
if(pecas[i].posicao.obtem().compareTo(posicao.obtem()) == 0) {
return pecas[i];
}
}
return null;
}
public Posicao obtemPosicaoDoAlvo(Posicao atacante, Posicao alvo) {
char letra = atacante.letra();
char numero = atacante.numero();
// Alvo está posicionado à direita do atacante
if(alvo.letra() - atacante.letra() > 0) {
letra++;
// Alvo está posicionado à esquerda do atacante
} else if(alvo.letra() - atacante.letra() < 0) {
letra--;
}
// Alvo está posicionado acima do atacante
if(alvo.numero() - atacante.numero() > 0) {
numero++;
// Alvo está posicionado abaixo do atacante
} else if(alvo.numero() - atacante.numero() < 0) {
numero--;
}
return new Posicao("" + letra + numero);
}
public boolean movePeca(String movimento) {
Peca pecaAtacante;
Posicao posicaoInicial = new Posicao("" + movimento.charAt(0) + movimento.charAt(1));
Posicao posicaoFinal = new Posicao("" + movimento.charAt(3) + movimento.charAt(4));
int numCasas; // numero de casas que a peça avançará
boolean ehCapturada;
pecaAtacante = buscaPeca(posicaoInicial);
numCasas = Math.abs(posicaoFinal.indiceNumero() - posicaoInicial.indiceNumero());
if(pecaAtacante == null) {
return false;
}
if(numCasas > 1) {
ehCapturada = capturaPeca(pecaAtacante, posicaoFinal);
if(!ehCapturada) {
return false;
}
}
pecaAtacante.saltaPara(posicaoFinal);
atualizaCasas(posicaoInicial, posicaoFinal, pecaAtacante.cor);
return true;
}
public boolean capturaPeca(Peca atacante, Posicao posicaoFinal) {
Posicao posicaoDoAlvo = obtemPosicaoDoAlvo(atacante.posicao, posicaoFinal);
Peca alvo = buscaPeca(posicaoDoAlvo);
if(alvo == null) {
return false;
}
casas[posicaoDoAlvo.indiceNumero()][posicaoDoAlvo.indiceLetra()] = '-';
alvo.remove();
return true;
}
public void atualizaCasas(Posicao posicaoInicial, Posicao posicaoFinal, char cor) {
casas[posicaoInicial.indiceNumero()][posicaoInicial.indiceLetra()] = '-';
casas[posicaoFinal.indiceNumero()][posicaoFinal.indiceLetra()] = cor;
}
}
|
UTF-8
|
Java
| 4,366 |
java
|
Tabuleiro.java
|
Java
|
[] | null |
[] |
package mc322.lab05;
public class Tabuleiro {
static final int NUM_PECAS = 24;
static final int LIN = 9;
static final int COL = 9;
static final char[] colunas = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '\n' };
static final char[] linhas = { '8', '7', '6', '5', '4', '3', '2', '1', '\n' };
static final String inicio = "-p-p-p-p\np-p-p-p-\n-p-p-p-p\n--------\n--------\nb-b-b-b-\n-b-b-b-b\nb-b-b-b-\n";
char[][] casas = new char[LIN][COL];
Peca[] pecas = new Peao[NUM_PECAS];
public Tabuleiro() {
for(int i = 0; i < LIN; i++) {
for(int j = 0; j < COL; j++) {
if(i*COL+j < 72 && inicio.charAt(i*COL+j) != '\n') {
casas[i][j] = inicio.charAt(i*COL+j);
}
}
}
}
public String imprime() {
String jogada = new String();
for(int i = 0; i < LIN - 1; i++) {
// Imprime numeros das linhas do tabuleiro
System.out.print(linhas[i]);
// Imprime tabuleiro
for(int j = 0; j < COL - 1; j++) {
jogada = jogada.concat("" + casas[i][j]);
System.out.print(" " + casas[i][j]);
}
jogada = jogada.concat("" + '\n');
System.out.println();
}
System.out.print(" ");
// Imprime numero das colunas do tabuleiro
for(int i = 0; i < COL; i++) {
System.out.print(" " + colunas[i]);
}
System.out.println();
return jogada;
}
public boolean ehPermitidoPeca(int lin, int col) {
if(casas[lin][col] == '-') {
return false;
}
return true;
}
public void adicionaPecas() {
String posicao;
char cor;
int indice = 0;
for(int i = 0; i < LIN - 1; i++) {
for(int j = 0; j < COL - 1; j++) {
if(ehPermitidoPeca(i, j)) {
posicao = "" + colunas[j] + linhas[i];
cor = casas[i][j];
pecas[indice++] = new Peao(posicao, cor);
}
}
}
}
public void imprimeJogada(String movimento) {
System.out.println("Source: " + movimento.charAt(0) + movimento.charAt(1));
System.out.println("Target: " + movimento.charAt(3) + movimento.charAt(4));
}
public Peca buscaPeca(Posicao posicao) {
for(int i = 0; i < NUM_PECAS; i++) {
if(pecas[i].posicao.obtem().compareTo(posicao.obtem()) == 0) {
return pecas[i];
}
}
return null;
}
public Posicao obtemPosicaoDoAlvo(Posicao atacante, Posicao alvo) {
char letra = atacante.letra();
char numero = atacante.numero();
// Alvo está posicionado à direita do atacante
if(alvo.letra() - atacante.letra() > 0) {
letra++;
// Alvo está posicionado à esquerda do atacante
} else if(alvo.letra() - atacante.letra() < 0) {
letra--;
}
// Alvo está posicionado acima do atacante
if(alvo.numero() - atacante.numero() > 0) {
numero++;
// Alvo está posicionado abaixo do atacante
} else if(alvo.numero() - atacante.numero() < 0) {
numero--;
}
return new Posicao("" + letra + numero);
}
public boolean movePeca(String movimento) {
Peca pecaAtacante;
Posicao posicaoInicial = new Posicao("" + movimento.charAt(0) + movimento.charAt(1));
Posicao posicaoFinal = new Posicao("" + movimento.charAt(3) + movimento.charAt(4));
int numCasas; // numero de casas que a peça avançará
boolean ehCapturada;
pecaAtacante = buscaPeca(posicaoInicial);
numCasas = Math.abs(posicaoFinal.indiceNumero() - posicaoInicial.indiceNumero());
if(pecaAtacante == null) {
return false;
}
if(numCasas > 1) {
ehCapturada = capturaPeca(pecaAtacante, posicaoFinal);
if(!ehCapturada) {
return false;
}
}
pecaAtacante.saltaPara(posicaoFinal);
atualizaCasas(posicaoInicial, posicaoFinal, pecaAtacante.cor);
return true;
}
public boolean capturaPeca(Peca atacante, Posicao posicaoFinal) {
Posicao posicaoDoAlvo = obtemPosicaoDoAlvo(atacante.posicao, posicaoFinal);
Peca alvo = buscaPeca(posicaoDoAlvo);
if(alvo == null) {
return false;
}
casas[posicaoDoAlvo.indiceNumero()][posicaoDoAlvo.indiceLetra()] = '-';
alvo.remove();
return true;
}
public void atualizaCasas(Posicao posicaoInicial, Posicao posicaoFinal, char cor) {
casas[posicaoInicial.indiceNumero()][posicaoInicial.indiceLetra()] = '-';
casas[posicaoFinal.indiceNumero()][posicaoFinal.indiceLetra()] = cor;
}
}
| 4,366 | 0.585724 | 0.575166 | 144 | 29.256945 | 25.242916 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.715278 | false | false |
7
|
ef3d9457bf287785188a7a6a7706b2511211ec6c
| 19,816,979,146,745 |
ab95e7975ed9b9185fc1d025711cee772fded700
|
/framework-fxtv/src/main/java/com/fxtv/framework/component/LoginComponent.java
|
5f0b24a3e54db026e29785f3fa2d735fd92049d3
|
[] |
no_license
|
var1993/framework
|
https://github.com/var1993/framework
|
7fe1437f0c722b958b67a57e93a772ee653db884
|
d6b0aa0925aa2ce6545ad9f9b75dde3e70f603ee
|
refs/heads/master
| 2021-01-20T20:14:42.978000 | 2016-07-28T04:23:51 | 2016-07-28T04:23:51 | 62,783,544 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fxtv.framework.component;
import com.fxtv.framework.frame.BaseComponent;
/**
* 登录组件
*
* @author Android2
*
*/
public class LoginComponent extends BaseComponent {
/**
* 第三方登录
*
* @param context
* --当前activity
* @param loginType
* --登录方式
* @param actionListener
* --监听用于回调
*/
/*public void thridLogin(Context context, Platform loginType,
PlatformActionListener actionListener) {
if (FrameworkUtils.isNetworkConnected(context)) {
if (loginType.isValid()) {
loginType.removeAccount(false);
}
loginType.setPlatformActionListener(actionListener);
loginType.SSOSetting(false);
loginType.showUser(null);
} else {
FrameworkUtils.showToast(context, "网络未连接");
}
}*/
}
|
UTF-8
|
Java
| 818 |
java
|
LoginComponent.java
|
Java
|
[
{
"context": "k.frame.BaseComponent;\n\n/**\n * 登录组件\n * \n * @author Android2\n * \n */\npublic class LoginComponent extends BaseC",
"end": 122,
"score": 0.9993867874145508,
"start": 114,
"tag": "USERNAME",
"value": "Android2"
}
] | null |
[] |
package com.fxtv.framework.component;
import com.fxtv.framework.frame.BaseComponent;
/**
* 登录组件
*
* @author Android2
*
*/
public class LoginComponent extends BaseComponent {
/**
* 第三方登录
*
* @param context
* --当前activity
* @param loginType
* --登录方式
* @param actionListener
* --监听用于回调
*/
/*public void thridLogin(Context context, Platform loginType,
PlatformActionListener actionListener) {
if (FrameworkUtils.isNetworkConnected(context)) {
if (loginType.isValid()) {
loginType.removeAccount(false);
}
loginType.setPlatformActionListener(actionListener);
loginType.SSOSetting(false);
loginType.showUser(null);
} else {
FrameworkUtils.showToast(context, "网络未连接");
}
}*/
}
| 818 | 0.665796 | 0.664491 | 37 | 19.702703 | 18.551411 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.432432 | false | false |
7
|
d04f5c6e7fc60251c6afee147b38cceba286e021
| 19,816,979,146,213 |
0b6dd4025d66b29b940b694b4d455eca4cda277e
|
/step-sequence/src/main/java/org/zalando/automata/execution/step/Step.java
|
59dcd5f4b72bbcb3e36ad64648d630613ac415f8
|
[] |
no_license
|
zalando-incubator/automata-misc
|
https://github.com/zalando-incubator/automata-misc
|
94efca58b69ba284ebfff7c632faa81fad42061d
|
a60b91b0029fbbb70da0c103646fcd90e5ccef30
|
refs/heads/master
| 2016-09-17T12:16:07.240000 | 2016-09-07T08:54:52 | 2016-09-07T08:54:52 | 59,994,048 | 2 | 2 | null | false | 2016-09-07T08:39:50 | 2016-05-30T08:35:15 | 2016-05-30T11:33:16 | 2016-09-07T08:39:50 | 85 | 0 | 1 | 0 |
Java
| null | null |
package org.zalando.automata.execution.step;
import org.zalando.automata.execution.Context;
/**
* Created by maryefyev on 13.10.15.
*/
public interface Step {
String getName();
void execute(final Context context) throws Exception;
ActionOnFailure getActionOnFailure();
void setActionOnFailure(ActionOnFailure action);
}
|
UTF-8
|
Java
| 340 |
java
|
Step.java
|
Java
|
[
{
"context": "ndo.automata.execution.Context;\n\n/**\n * Created by maryefyev on 13.10.15.\n */\npublic interface Step {\n Stri",
"end": 121,
"score": 0.9978711009025574,
"start": 112,
"tag": "USERNAME",
"value": "maryefyev"
}
] | null |
[] |
package org.zalando.automata.execution.step;
import org.zalando.automata.execution.Context;
/**
* Created by maryefyev on 13.10.15.
*/
public interface Step {
String getName();
void execute(final Context context) throws Exception;
ActionOnFailure getActionOnFailure();
void setActionOnFailure(ActionOnFailure action);
}
| 340 | 0.755882 | 0.738235 | 13 | 25.153847 | 21.023233 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false |
7
|
d781f6d17bc17a104d5b7ffb0ae402d2991a369c
| 6,356,551,664,923 |
5090ca9d01b52d019e2b227081eba289fc43ef05
|
/src/main/java/io/zipcoder/casino/ConcreteMenus/Menu.java
|
d8710c1c8dd64aba7d2cb578032664e3a7d5d92b
|
[] |
no_license
|
nehctuk/CR-Casino
|
https://github.com/nehctuk/CR-Casino
|
16926e4cd043f8e8d738e667abccef977fae50d0
|
aca25b4b4540e601e90f8a2e28b3321a66456329
|
refs/heads/master
| 2021-08-19T21:37:24.263000 | 2017-11-27T13:10:10 | 2017-11-27T13:10:10 | 111,140,619 | 0 | 2 | null | true | 2017-11-22T00:31:55 | 2017-11-17T19:04:03 | 2017-11-17T19:04:05 | 2017-11-22T00:01:40 | 179 | 0 | 1 | 1 |
Java
| false | null |
package io.zipcoder.casino.ConcreteMenus;
import io.zipcoder.casino.Console;
public abstract class Menu {
private Enum[] menuEnum;
public Menu(Enum[] menuEnums) {
this.menuEnum = menuEnums;
}
public abstract void userMenuSelection(String input);
public void display() {
String userInput;
do {
try {
do {
userInput = this.getInput().toUpperCase();
userMenuSelection(convertEnumsToNums(userInput));
} while (!"quit".equalsIgnoreCase(userInput));
break;
} catch (IllegalArgumentException|ArrayIndexOutOfBoundsException e) {
Console.print("\nINVALID INPUT!!! Please enter a valid menu option.");
continue;
}
}while (true);
}
public String convertEnumsToNums(String menuNum) {
int stringToNum = Integer.parseInt(menuNum)-1;
return ""+this.menuEnum[stringToNum];
}
public String getInput() {
this.menuTitle();
Console.print(this.toString());
return Console.getStringInput("");
}
public abstract void menuTitle();
public abstract String toString();
}
|
UTF-8
|
Java
| 1,232 |
java
|
Menu.java
|
Java
|
[] | null |
[] |
package io.zipcoder.casino.ConcreteMenus;
import io.zipcoder.casino.Console;
public abstract class Menu {
private Enum[] menuEnum;
public Menu(Enum[] menuEnums) {
this.menuEnum = menuEnums;
}
public abstract void userMenuSelection(String input);
public void display() {
String userInput;
do {
try {
do {
userInput = this.getInput().toUpperCase();
userMenuSelection(convertEnumsToNums(userInput));
} while (!"quit".equalsIgnoreCase(userInput));
break;
} catch (IllegalArgumentException|ArrayIndexOutOfBoundsException e) {
Console.print("\nINVALID INPUT!!! Please enter a valid menu option.");
continue;
}
}while (true);
}
public String convertEnumsToNums(String menuNum) {
int stringToNum = Integer.parseInt(menuNum)-1;
return ""+this.menuEnum[stringToNum];
}
public String getInput() {
this.menuTitle();
Console.print(this.toString());
return Console.getStringInput("");
}
public abstract void menuTitle();
public abstract String toString();
}
| 1,232 | 0.590909 | 0.590097 | 47 | 25.212767 | 23.562445 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446809 | false | false |
7
|
1c8d4e55daf0c5061643973e75c057fa6b82a85c
| 20,418,274,578,278 |
0390907440982871457d00aa4f8ae3cae8457d1b
|
/src/leapgestureanalyzer/Point.java
|
d26ba71226e284c255bf7630b3c75a38f636f9db
|
[] |
no_license
|
andresbejarano/LeapGestureAnalyzer
|
https://github.com/andresbejarano/LeapGestureAnalyzer
|
f98b3fb10525e05aa7e09a254338caff186db6fd
|
7910da177b8fb03112e25e4488575af03c7b0934
|
refs/heads/master
| 2020-05-16T13:34:45.841000 | 2015-05-04T17:35:54 | 2015-05-04T17:35:54 | 34,494,643 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package leapgestureanalyzer;
/**
*
* @author AndresMauricio
*/
public class Point {
public float x;
public float y;
public float z;
/**
*
*/
public Point() {
x = y = z = 0;
}
/**
*
* @param v
*/
public Point(float v)
{
x = y = z = v;
}
/**
*
* @param x
* @param y
* @param z
*/
public Point(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
*
* @param x
* @param y
* @param z
*/
public Point(String x, String y, String z) {
this.x = Float.parseFloat(x);
this.y = Float.parseFloat(y);
this.z = Float.parseFloat(z);
}
/**
*
* @param point
*/
public Point(Point point)
{
x = point.x;
y = point.y;
z = point.z;
}
/**
*
* @param point
*/
public void add(Point point)
{
x += point.x;
y += point.y;
z += point.z;
}
}
|
UTF-8
|
Java
| 1,173 |
java
|
Point.java
|
Java
|
[
{
"context": "ackage leapgestureanalyzer;\r\n\r\n/**\r\n *\r\n * @author AndresMauricio\r\n */\r\npublic class Point {\r\n \r\n public floa",
"end": 66,
"score": 0.999813437461853,
"start": 52,
"tag": "NAME",
"value": "AndresMauricio"
}
] | null |
[] |
package leapgestureanalyzer;
/**
*
* @author AndresMauricio
*/
public class Point {
public float x;
public float y;
public float z;
/**
*
*/
public Point() {
x = y = z = 0;
}
/**
*
* @param v
*/
public Point(float v)
{
x = y = z = v;
}
/**
*
* @param x
* @param y
* @param z
*/
public Point(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
*
* @param x
* @param y
* @param z
*/
public Point(String x, String y, String z) {
this.x = Float.parseFloat(x);
this.y = Float.parseFloat(y);
this.z = Float.parseFloat(z);
}
/**
*
* @param point
*/
public Point(Point point)
{
x = point.x;
y = point.y;
z = point.z;
}
/**
*
* @param point
*/
public void add(Point point)
{
x += point.x;
y += point.y;
z += point.z;
}
}
| 1,173 | 0.361466 | 0.360614 | 75 | 13.64 | 10.78473 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.293333 | false | false |
7
|
fa77b8a7d354175554dfbc5f1d45273cc9cbc7ce
| 28,020,366,702,406 |
6d919c8065e587d276157fb756638e5a44887a38
|
/old/src/dao/impl/SickerDaoImpl.java
|
f48fc6d6b460fef4cbe3897cd4b69fd9199929fa
|
[] |
no_license
|
PineappleLB/sickness-system
|
https://github.com/PineappleLB/sickness-system
|
facd40ce14b39c26387ab560fd9c140a6e166cda
|
6bbf21845fd786449f8a53a5b003dbecc7633cba
|
refs/heads/master
| 2023-01-29T17:13:16.420000 | 2019-10-15T07:26:21 | 2019-10-15T07:26:21 | 138,247,680 | 0 | 1 | null | false | 2023-01-03T17:16:40 | 2018-06-22T02:59:11 | 2019-10-15T07:26:23 | 2023-01-03T17:16:39 | 32,144 | 0 | 2 | 8 |
TSQL
| false | false |
package dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dao.SickerDao;
import util.DatabaseUtil;
import util.Scope;
import util.Sick;
public class SickerDaoImpl implements SickerDao {
private Connection conn = DatabaseUtil.getConnection();
@Override
public List<Map<String, Object>> selectAllSickerInfo() {
return selectSickerInfo("all","all");
}
@Override
public int addSickerInfo(String name, String age, String home_address, String sick, String phone,
String work_address, String scope) {
String sql = "insert into t_sicker_info (name,age,home_address,sick,phone,work_address,scope) " +
"values(?,?,?,?,?,?,?)";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, Integer.parseInt(age));
ps.setString(3, home_address);
ps.setString(4, sick);
ps.setString(5, phone);
ps.setString(6, work_address);
ps.setString(7, scope);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public int updSickerInfo(String id, String age, String home_address, String sick, String phone,
String work_address, String scope) {
String sql = "update t_sicker_info set age=?,home_address=?,sick=?,phone=?,work_address=?,scope=? " +
"where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(age));
ps.setString(2, home_address);
ps.setString(3, sick);
ps.setString(4, phone);
ps.setString(5, work_address);
ps.setString(6, scope);
ps.setString(7, id);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public int delSickerInfo(String[] ids) {
String sql = "delete t_sicker_info where id in(";
for (int i = 0; i < ids.length; i++) {
if(ids[i] == null || ids[i].equals("")) {
continue;
}
sql += "?,";
}
sql = new StringBuilder(sql).reverse().deleteCharAt(0).reverse().append(")").toString();
try {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < ids.length; i++) {
if(ids[i] == null || ids[i].equals("")) {
continue;
}
ps.setString(i + 1, ids[i]);
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public List<Map<String, Object>> selectSickerInfo(String sickType, String scopeType) {
String sql = "select * from t_sicker_info where 1=1";
int i = 1;
if(!sickType.equals("all")) {
sql += " and sick=?";
}
if(!scopeType.equals("all")) {
sql += " and scope=?";
}
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(!sickType.equals("all")) {
ps.setString(i, sickType);
i++;
}
if(!scopeType.equals("all")) {
ps.setString(i, scopeType);
}
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("id", rs.getInt("id"));
map.put("name", rs.getString("name"));
map.put("age", rs.getInt("age"));
map.put("home_address", rs.getString("home_address"));
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("phone", rs.getString("phone"));
map.put("work_address", rs.getString("work_address"));
map.put("scope", Scope.getScope(rs.getString("scope")));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public List<Map<String, Object>> selectSickerCount(String sickType, String scopeType) {
String sql = "select count(1) as count,sick,scope from t_sicker_info where 1=1 ";
int i = 1;
if(!sickType.equals("all")) {
sql += " and sick=?";
}
if(!scopeType.equals("all")) {
sql += " and scope=? ";
}
sql += " group by sick,scope";
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(!sickType.equals("all")) {
ps.setString(i, sickType);
i++;
}
if(!scopeType.equals("all")) {
ps.setString(i, scopeType);
}
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("scope", Scope.getScope(rs.getString("scope")));
map.put("count", rs.getInt("count"));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public List<Map<String, Object>> selectSickerInfoBy(String sel_text, String sel_type) {
String sql = "select * from t_sicker_info where 1=1";
if(sel_type!= null && !sel_type.equals("")) {
if(sel_type.equals("id")) {
sql += " and " + sel_type + " like ?";
} else if(sel_type.equals("name")) {
sql += " and " + sel_type + " like ?";
}
}
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "%"+sel_text+"%");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("id", rs.getInt("id"));
map.put("name", rs.getString("name"));
map.put("age", rs.getInt("age"));
map.put("home_address", rs.getString("home_address"));
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("phone", rs.getString("phone"));
map.put("work_address", rs.getString("work_address"));
map.put("scope", Scope.getScope(rs.getString("scope")));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
|
UTF-8
|
Java
| 5,845 |
java
|
SickerDaoImpl.java
|
Java
|
[] | null |
[] |
package dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dao.SickerDao;
import util.DatabaseUtil;
import util.Scope;
import util.Sick;
public class SickerDaoImpl implements SickerDao {
private Connection conn = DatabaseUtil.getConnection();
@Override
public List<Map<String, Object>> selectAllSickerInfo() {
return selectSickerInfo("all","all");
}
@Override
public int addSickerInfo(String name, String age, String home_address, String sick, String phone,
String work_address, String scope) {
String sql = "insert into t_sicker_info (name,age,home_address,sick,phone,work_address,scope) " +
"values(?,?,?,?,?,?,?)";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, Integer.parseInt(age));
ps.setString(3, home_address);
ps.setString(4, sick);
ps.setString(5, phone);
ps.setString(6, work_address);
ps.setString(7, scope);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public int updSickerInfo(String id, String age, String home_address, String sick, String phone,
String work_address, String scope) {
String sql = "update t_sicker_info set age=?,home_address=?,sick=?,phone=?,work_address=?,scope=? " +
"where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(age));
ps.setString(2, home_address);
ps.setString(3, sick);
ps.setString(4, phone);
ps.setString(5, work_address);
ps.setString(6, scope);
ps.setString(7, id);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public int delSickerInfo(String[] ids) {
String sql = "delete t_sicker_info where id in(";
for (int i = 0; i < ids.length; i++) {
if(ids[i] == null || ids[i].equals("")) {
continue;
}
sql += "?,";
}
sql = new StringBuilder(sql).reverse().deleteCharAt(0).reverse().append(")").toString();
try {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < ids.length; i++) {
if(ids[i] == null || ids[i].equals("")) {
continue;
}
ps.setString(i + 1, ids[i]);
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
@Override
public List<Map<String, Object>> selectSickerInfo(String sickType, String scopeType) {
String sql = "select * from t_sicker_info where 1=1";
int i = 1;
if(!sickType.equals("all")) {
sql += " and sick=?";
}
if(!scopeType.equals("all")) {
sql += " and scope=?";
}
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(!sickType.equals("all")) {
ps.setString(i, sickType);
i++;
}
if(!scopeType.equals("all")) {
ps.setString(i, scopeType);
}
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("id", rs.getInt("id"));
map.put("name", rs.getString("name"));
map.put("age", rs.getInt("age"));
map.put("home_address", rs.getString("home_address"));
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("phone", rs.getString("phone"));
map.put("work_address", rs.getString("work_address"));
map.put("scope", Scope.getScope(rs.getString("scope")));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public List<Map<String, Object>> selectSickerCount(String sickType, String scopeType) {
String sql = "select count(1) as count,sick,scope from t_sicker_info where 1=1 ";
int i = 1;
if(!sickType.equals("all")) {
sql += " and sick=?";
}
if(!scopeType.equals("all")) {
sql += " and scope=? ";
}
sql += " group by sick,scope";
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
if(!sickType.equals("all")) {
ps.setString(i, sickType);
i++;
}
if(!scopeType.equals("all")) {
ps.setString(i, scopeType);
}
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("scope", Scope.getScope(rs.getString("scope")));
map.put("count", rs.getInt("count"));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Override
public List<Map<String, Object>> selectSickerInfoBy(String sel_text, String sel_type) {
String sql = "select * from t_sicker_info where 1=1";
if(sel_type!= null && !sel_type.equals("")) {
if(sel_type.equals("id")) {
sql += " and " + sel_type + " like ?";
} else if(sel_type.equals("name")) {
sql += " and " + sel_type + " like ?";
}
}
List<Map<String, Object>> infos = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "%"+sel_text+"%");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("id", rs.getInt("id"));
map.put("name", rs.getString("name"));
map.put("age", rs.getInt("age"));
map.put("home_address", rs.getString("home_address"));
map.put("sick", Sick.getSick(rs.getString("sick")));
map.put("phone", rs.getString("phone"));
map.put("work_address", rs.getString("work_address"));
map.put("scope", Scope.getScope(rs.getString("scope")));
infos.add(map);
}
return infos;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
| 5,845 | 0.629427 | 0.624123 | 206 | 27.373787 | 22.298746 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.364078 | false | false |
7
|
7adcb6128b4b13109e5efd0834c8619ac7fc4cc4
| 28,020,366,700,030 |
8760448a67884ea9858a405964baccd14a1def78
|
/src/main/hospital/CommandDesinfactNormalEmergencyVehicle.java
|
977c9d67d89e507b7c14e1e38796dcc097bfd751
|
[] |
no_license
|
andii04/hospitalcovid19
|
https://github.com/andii04/hospitalcovid19
|
4bbdcf61c8d0cf4b3506150bfa27c143ea64bf37
|
c06ad65eead0c493852617320f4067799b1f8a7e
|
refs/heads/master
| 2022-10-31T14:30:39.250000 | 2020-06-14T19:33:10 | 2020-06-14T19:33:10 | 264,616,357 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hospital;
public class CommandDesinfactNormalEmergencyVehicle implements ICommand {
DisinfectionRobot robot;
EmergencyVehicle emergencyVehicle;
//Command to desinfact normal vehicle
public CommandDesinfactNormalEmergencyVehicle(DisinfectionRobot robot, EmergencyVehicle emergencyVehicle) {
this.robot = robot;
this.emergencyVehicle = emergencyVehicle;
}
@Override
public void execute() {
robot.visit(emergencyVehicle);
}
}
|
UTF-8
|
Java
| 490 |
java
|
CommandDesinfactNormalEmergencyVehicle.java
|
Java
|
[] | null |
[] |
package hospital;
public class CommandDesinfactNormalEmergencyVehicle implements ICommand {
DisinfectionRobot robot;
EmergencyVehicle emergencyVehicle;
//Command to desinfact normal vehicle
public CommandDesinfactNormalEmergencyVehicle(DisinfectionRobot robot, EmergencyVehicle emergencyVehicle) {
this.robot = robot;
this.emergencyVehicle = emergencyVehicle;
}
@Override
public void execute() {
robot.visit(emergencyVehicle);
}
}
| 490 | 0.746939 | 0.746939 | 18 | 26.277779 | 28.811274 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
7
|
cac09c0245e66c2d8e47422cec360f5b8f78bdd7
| 2,989,297,268,169 |
12815c6c0eac579f5c060dc35cbd8d4f7fb36c57
|
/src/com/asher/yang/upload/bean/View.java
|
27366a0ed4002915e1db28ea5a93a4293f0eb2a4
|
[] |
no_license
|
AsherYang/AsherUpload
|
https://github.com/AsherYang/AsherUpload
|
332efddc5221ac5d2cc027db6a2675db8c2fc0f2
|
e71a9a316bd1e687c7d65db6118bfcd2f83efce0
|
refs/heads/master
| 2021-05-03T19:16:58.609000 | 2017-08-21T08:37:01 | 2017-08-21T08:37:01 | 69,156,313 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.asher.yang.upload.bean;
import java.util.LinkedList;
import java.util.List;
/**
* Created by AsherYang on 2016/9/24.
* email: ouyangfan1991@gmail.com
*/
public class View {
private String name;
private String path;
private final List<View> subViews = new LinkedList<View>();
public View() {
}
public View(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<View> getSubViews() {
return subViews;
}
public void addSubView(View subView) {
this.subViews.add(subView);
}
public static View createView(String viewName, String viewUrl) {
return new View(viewName, viewUrl);
}
}
|
UTF-8
|
Java
| 1,026 |
java
|
View.java
|
Java
|
[
{
"context": "ist;\r\nimport java.util.List;\r\n\r\n/**\r\n * Created by AsherYang on 2016/9/24.\r\n * email: ouyangfan1991@gmail.com\r",
"end": 123,
"score": 0.9998318552970886,
"start": 114,
"tag": "NAME",
"value": "AsherYang"
},
{
"context": "\r\n * Created by AsherYang on 2016/9/24.\r\n * email: ouyangfan1991@gmail.com\r\n */\r\npublic class View {\r\n\r\n private String n",
"end": 172,
"score": 0.9999204277992249,
"start": 149,
"tag": "EMAIL",
"value": "ouyangfan1991@gmail.com"
}
] | null |
[] |
package com.asher.yang.upload.bean;
import java.util.LinkedList;
import java.util.List;
/**
* Created by AsherYang on 2016/9/24.
* email: <EMAIL>
*/
public class View {
private String name;
private String path;
private final List<View> subViews = new LinkedList<View>();
public View() {
}
public View(String name, String path) {
this.name = name;
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<View> getSubViews() {
return subViews;
}
public void addSubView(View subView) {
this.subViews.add(subView);
}
public static View createView(String viewName, String viewUrl) {
return new View(viewName, viewUrl);
}
}
| 1,010 | 0.576023 | 0.565302 | 52 | 17.73077 | 17.440134 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false |
7
|
0038f8d1ea754041ec4ab9292596029259d344cc
| 17,763,984,737,781 |
305cd37955b8643b1a8db04c92cd9ba2a52a514f
|
/src/main/java/io/hyperfoil/tools/yaup/TimestampedData.java
|
f3a33c3d0ed6a38e2ecd119f7ffcd63c5e33922f
|
[
"Apache-2.0"
] |
permissive
|
RedHatPerf/yaup
|
https://github.com/RedHatPerf/yaup
|
ebaf48284c26c6b2e8bffc369d4a1f024c979c3e
|
f4d9ce08218fb0a9a3b56ed95ef7bc9cbebbd741
|
refs/heads/master
| 2021-05-02T10:05:55.215000 | 2021-03-15T18:17:18 | 2021-03-15T18:17:18 | 120,789,755 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.hyperfoil.tools.yaup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
/**
* Created by wreicher
*/
public class TimestampedData<T> {
private TreeSet<Long> timestamps;
private LinkedHashSet<String> names;
private HashMap<String,HashMap<Long,T>> data;
public TimestampedData(){
data = new HashMap<>();
names = new LinkedHashSet<>();
timestamps = new TreeSet<>();
}
public void add(String name,long timestamp,T value){
if(name.equals("[B")){
System.out.println(name+"->"+timestamp+"="+value);
}
names.add(name);
timestamps.add(timestamp);
if(!data.containsKey(name)){
data.put(name,new HashMap<>());
}
data.get(name).put(timestamp,value);
}
public T get(long timestamp,String name){
if(data.containsKey(name)){
HashMap<Long,T> map = data.get(name);
if(map.containsKey(timestamp)){
return map.get(timestamp);
}
}
return null;
}
public long firstTimestamp(){
return timestamps.first();
}
public long lastTimestamp(){
return timestamps.last();
}
public List<Long> timestamps(){
return Collections.unmodifiableList(new ArrayList<Long>(timestamps));
}
public List<String> names(){
return Collections.unmodifiableList(new ArrayList<String>(names));
}
public long nextTimestamp(long timestamp){
if(timestamp >= lastTimestamp()){
return Long.MAX_VALUE;
}
return timestamps.higher(timestamp);
}
public long prevTimestamp(long timestamp){
if(timestamp <= firstTimestamp()){
return Long.MIN_VALUE;
}
return timestamps.lower(timestamp);
}
}
|
UTF-8
|
Java
| 1,932 |
java
|
TimestampedData.java
|
Java
|
[
{
"context": "List;\nimport java.util.TreeSet;\n\n/**\n * Created by wreicher\n */\npublic class TimestampedData<T> {\n\n privat",
"end": 226,
"score": 0.9992415904998779,
"start": 218,
"tag": "USERNAME",
"value": "wreicher"
}
] | null |
[] |
package io.hyperfoil.tools.yaup;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
/**
* Created by wreicher
*/
public class TimestampedData<T> {
private TreeSet<Long> timestamps;
private LinkedHashSet<String> names;
private HashMap<String,HashMap<Long,T>> data;
public TimestampedData(){
data = new HashMap<>();
names = new LinkedHashSet<>();
timestamps = new TreeSet<>();
}
public void add(String name,long timestamp,T value){
if(name.equals("[B")){
System.out.println(name+"->"+timestamp+"="+value);
}
names.add(name);
timestamps.add(timestamp);
if(!data.containsKey(name)){
data.put(name,new HashMap<>());
}
data.get(name).put(timestamp,value);
}
public T get(long timestamp,String name){
if(data.containsKey(name)){
HashMap<Long,T> map = data.get(name);
if(map.containsKey(timestamp)){
return map.get(timestamp);
}
}
return null;
}
public long firstTimestamp(){
return timestamps.first();
}
public long lastTimestamp(){
return timestamps.last();
}
public List<Long> timestamps(){
return Collections.unmodifiableList(new ArrayList<Long>(timestamps));
}
public List<String> names(){
return Collections.unmodifiableList(new ArrayList<String>(names));
}
public long nextTimestamp(long timestamp){
if(timestamp >= lastTimestamp()){
return Long.MAX_VALUE;
}
return timestamps.higher(timestamp);
}
public long prevTimestamp(long timestamp){
if(timestamp <= firstTimestamp()){
return Long.MIN_VALUE;
}
return timestamps.lower(timestamp);
}
}
| 1,932 | 0.606625 | 0.606625 | 72 | 25.833334 | 18.91428 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513889 | false | false |
7
|
fe0a11c1e93b209b33bd213beb68f861476987d3
| 17,600,776,041,163 |
362309d827c638302130985081da59c4dd34941e
|
/src/controller/admin/article/IndexController.java
|
16c83e1a30f72148d75bb4a5b74d21663c89a20f
|
[] |
no_license
|
HsOjo/JspBlog
|
https://github.com/HsOjo/JspBlog
|
662993d2d9b7481f139d39b2f539dc860ac18a55
|
3f2357ad0e47672750fb336b9b5e5b1f71ade212
|
refs/heads/master
| 2022-10-29T20:27:47.128000 | 2020-06-22T06:18:08 | 2020-06-22T06:18:08 | 271,280,162 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controller.admin.article;
import controller.base.AdminBaseController;
import dao.ArticleDAO;
import dao.base.Paginate;
import entity.Article;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/admin/article/index")
public class IndexController extends AdminBaseController {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!this.authentication(req, resp)) return;
Map<String, String> param = this.param(req);
int page = Integer.parseInt(param.getOrDefault("page", "1"));
Paginate<Article> paginate = ArticleDAO.getInstance().paginate(page);
HashMap<String, Object> values = new HashMap<>();
values.put("paginate", paginate);
this.fetch(req, resp, values);
}
}
|
UTF-8
|
Java
| 1,030 |
java
|
IndexController.java
|
Java
|
[] | null |
[] |
package controller.admin.article;
import controller.base.AdminBaseController;
import dao.ArticleDAO;
import dao.base.Paginate;
import entity.Article;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/admin/article/index")
public class IndexController extends AdminBaseController {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!this.authentication(req, resp)) return;
Map<String, String> param = this.param(req);
int page = Integer.parseInt(param.getOrDefault("page", "1"));
Paginate<Article> paginate = ArticleDAO.getInstance().paginate(page);
HashMap<String, Object> values = new HashMap<>();
values.put("paginate", paginate);
this.fetch(req, resp, values);
}
}
| 1,030 | 0.747573 | 0.746602 | 29 | 34.517242 | 25.752966 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.965517 | false | false |
7
|
c0cdc9708dfefac636d0ac67add6c8218e69cd17
| 26,027,501,819,594 |
83371d340107e82dde45454d0792985698b5af7d
|
/app/src/main/java/com/wongxd/carinsurance/permission/PermissionActivity.java
|
516ee8ca2fb46f6a6b1750263e0e97e00c1e1dff
|
[] |
no_license
|
NamedJack/carInsurance
|
https://github.com/NamedJack/carInsurance
|
1e42936aaa65fc93b8fd12aa6ca6dd5a6181776c
|
535e070cd7e159fd3e9be34a55b6cae6b5b2d183
|
refs/heads/master
| 2021-08-23T07:43:17.990000 | 2017-12-04T05:57:03 | 2017-12-04T05:57:05 | 113,001,151 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wongxd.carinsurance.permission;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.wongxd.carinsurance.R;
import java.util.List;
/**
* 用法:
* <p>
* <p>
* 奇淫技巧:
* <p>
* checkPermission(CheckPermListener listener, int resString, String... mPerms)
* <p>
* - listener: 权限全部通过接口回调,只检测没有后续行为可 null
* - resString: 权限用途的说明提示(引导用户开启权限)
* - mPerms: 申请的高危权限组(可同时申请多个)
* 下面列出简单的使用方法
* <p>
* Activity中:
* <p>
* 首先需要检测权限的 Activity extends PermissionActivity
* <p>
* checkPermission(new CheckPermListener() {
*
* @Override public void superPermission() {
* TODO : 需要权限去完成的功能
* }
* },R.string.camera,
* Manifest.permission.CAMERA,
* Manifest.permission.WRITE_EXTERNAL_STORAGE);
* Fragment中:
* <p>
* 首先Fragment依存的 Activity extends PermissionActivit
* <p>
* ((PermissionActivity)getActivity()).checkPermission(
* new PermissionActivity.CheckPermListener() {
* @Override public void superPermission() {
* TODO : 需要权限去完成的功能
* }
* },R.string.camera, Manifest.permission.CAMERA);
*/
/*
* @创建者 Jrking
* @创建时间 2016/4/15 16:18
* @描述 ${Activity基类 }
* @更新描述 ${适配6.0权限问题}
*/
public class PermissionActivity extends AppCompatActivity implements
EasyPermissions.PermissionCallbacks {
protected static final int RC_PERM = 123;
protected static int reSting = R.string.ask_again;//默认提示语句
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initStatusBar("#303F9F");//透明状态栏
}
public void initStatusBar(String strColor) {
StatusBarCompat.setStatusBarColor(this, Color.parseColor(strColor));
StatusBarCompat.translucentStatusBar(this);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* 权限回调接口
*/
private CheckPermListener mListener;
public interface CheckPermListener {
//权限通过后的回调方法
void superPermission();
}
public void checkPermission(CheckPermListener listener, int resString, String... mPerms) {
mListener = listener;
if (EasyPermissions.hasPermissions(this, mPerms)) {
if (mListener != null)
mListener.superPermission();
} else {
EasyPermissions.requestPermissions(this, getString(resString),
RC_PERM, mPerms);
}
}
/**
*
* @param listener
* @param msg 提示信息
* @param mPerms
*/
public void checkPermission(CheckPermListener listener, String msg, String... mPerms) {
mListener = listener;
if (EasyPermissions.hasPermissions(this, mPerms)) {
if (mListener != null)
mListener.superPermission();
} else {
EasyPermissions.requestPermissions(this, msg,
RC_PERM, mPerms);
}
}
/**
* 用户权限处理,
* 如果全部获取, 则直接过.
* 如果权限缺失, 则提示Dialog.
*
* @param requestCode 请求码
* @param permissions 权限
* @param grantResults 结果
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EasyPermissions.SETTINGS_REQ_CODE) {
//设置返回
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
//同意了某些权限可能不是全部
}
@Override
public void onPermissionsAllGranted() {
if (mListener != null)
mListener.superPermission();//同意了全部权限的回调
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
getString(R.string.perm_tip),
R.string.setting, R.string.cancel, null, perms);
}
}
|
UTF-8
|
Java
| 5,056 |
java
|
PermissionActivity.java
|
Java
|
[
{
"context": " Manifest.permission.CAMERA);\n */\n\n\n/*\n * @创建者 Jrking\n * @创建时间 2016/4/15 16:18\n * @描述\t ${Activit",
"end": 1176,
"score": 0.9997045397758484,
"start": 1170,
"tag": "USERNAME",
"value": "Jrking"
}
] | null |
[] |
package com.wongxd.carinsurance.permission;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.wongxd.carinsurance.R;
import java.util.List;
/**
* 用法:
* <p>
* <p>
* 奇淫技巧:
* <p>
* checkPermission(CheckPermListener listener, int resString, String... mPerms)
* <p>
* - listener: 权限全部通过接口回调,只检测没有后续行为可 null
* - resString: 权限用途的说明提示(引导用户开启权限)
* - mPerms: 申请的高危权限组(可同时申请多个)
* 下面列出简单的使用方法
* <p>
* Activity中:
* <p>
* 首先需要检测权限的 Activity extends PermissionActivity
* <p>
* checkPermission(new CheckPermListener() {
*
* @Override public void superPermission() {
* TODO : 需要权限去完成的功能
* }
* },R.string.camera,
* Manifest.permission.CAMERA,
* Manifest.permission.WRITE_EXTERNAL_STORAGE);
* Fragment中:
* <p>
* 首先Fragment依存的 Activity extends PermissionActivit
* <p>
* ((PermissionActivity)getActivity()).checkPermission(
* new PermissionActivity.CheckPermListener() {
* @Override public void superPermission() {
* TODO : 需要权限去完成的功能
* }
* },R.string.camera, Manifest.permission.CAMERA);
*/
/*
* @创建者 Jrking
* @创建时间 2016/4/15 16:18
* @描述 ${Activity基类 }
* @更新描述 ${适配6.0权限问题}
*/
public class PermissionActivity extends AppCompatActivity implements
EasyPermissions.PermissionCallbacks {
protected static final int RC_PERM = 123;
protected static int reSting = R.string.ask_again;//默认提示语句
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initStatusBar("#303F9F");//透明状态栏
}
public void initStatusBar(String strColor) {
StatusBarCompat.setStatusBarColor(this, Color.parseColor(strColor));
StatusBarCompat.translucentStatusBar(this);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* 权限回调接口
*/
private CheckPermListener mListener;
public interface CheckPermListener {
//权限通过后的回调方法
void superPermission();
}
public void checkPermission(CheckPermListener listener, int resString, String... mPerms) {
mListener = listener;
if (EasyPermissions.hasPermissions(this, mPerms)) {
if (mListener != null)
mListener.superPermission();
} else {
EasyPermissions.requestPermissions(this, getString(resString),
RC_PERM, mPerms);
}
}
/**
*
* @param listener
* @param msg 提示信息
* @param mPerms
*/
public void checkPermission(CheckPermListener listener, String msg, String... mPerms) {
mListener = listener;
if (EasyPermissions.hasPermissions(this, mPerms)) {
if (mListener != null)
mListener.superPermission();
} else {
EasyPermissions.requestPermissions(this, msg,
RC_PERM, mPerms);
}
}
/**
* 用户权限处理,
* 如果全部获取, 则直接过.
* 如果权限缺失, 则提示Dialog.
*
* @param requestCode 请求码
* @param permissions 权限
* @param grantResults 结果
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EasyPermissions.SETTINGS_REQ_CODE) {
//设置返回
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
//同意了某些权限可能不是全部
}
@Override
public void onPermissionsAllGranted() {
if (mListener != null)
mListener.superPermission();//同意了全部权限的回调
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
getString(R.string.perm_tip),
R.string.setting, R.string.cancel, null, perms);
}
}
| 5,056 | 0.641678 | 0.637114 | 188 | 23.478724 | 24.101395 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.420213 | false | false |
7
|
d34e7e62a615e2361056c170cfeff5afcfd583f4
| 26,027,501,819,956 |
ef1061f43663da0e64f778f6cb39effef9ce33b7
|
/ZXBank/src/com/zd/core/jdbc/DBMap.java
|
9bcd7f9dc300aa7bc30c8b49647c245b0ebfe051
|
[] |
no_license
|
demon0228/Test
|
https://github.com/demon0228/Test
|
c90476b925c3cf48a5dbc45406096471783958e8
|
fe226c0a39bcf760ddac524bd89d20e023ad8a72
|
refs/heads/master
| 2017-12-04T18:26:38.072000 | 2017-04-13T10:47:15 | 2017-04-13T10:47:15 | 86,434,900 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zd.core.jdbc;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 用于存储数据库查询结果的map实例
* 用于queryForList查询的实现,保证字段大小写不一致时可正确获取对应的值
*/
public class DBMap implements Map<String, Object> {
private Map<String, Object> coreMap = new HashMap<String, Object>();
private String conversion(String key){
if(key==null){
return key;
}
return key.toUpperCase();
}
public void clear() {
coreMap.clear();
}
public boolean containsKey(Object key) {
return coreMap.containsKey(conversion((String)key));
}
public boolean containsValue(Object value) {
return coreMap.containsValue(value);
}
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return coreMap.entrySet();
}
public Object get(Object key) {
return coreMap.get(conversion((String)key));
}
public boolean isEmpty() {
return coreMap.isEmpty();
}
public Set<String> keySet() {
return coreMap.keySet();
}
public Object put(String key, Object value) {
return coreMap.put(conversion(key),value);
}
public void putAll(Map<? extends String, ? extends Object> t) {
// for (Entry<? extends String, ? extends Object> tempEntry : t.entrySet()) {
// coreMap.put(tempEntry.getKey(), tempEntry.getValue());
// }
Set<?> set = t.keySet();
for(Iterator<?> iter = set.iterator(); iter.hasNext();){
String key = (String)iter.next();
coreMap.put(conversion(key),t.get(key));
}
}
public Object remove(Object key) {
return coreMap.remove(conversion((String)key));
}
public int size() {
return coreMap.size();
}
public Collection<Object> values() {
return coreMap.values();
}
public String toString(){
return coreMap.toString();
}
}
|
UTF-8
|
Java
| 1,843 |
java
|
DBMap.java
|
Java
|
[] | null |
[] |
package com.zd.core.jdbc;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 用于存储数据库查询结果的map实例
* 用于queryForList查询的实现,保证字段大小写不一致时可正确获取对应的值
*/
public class DBMap implements Map<String, Object> {
private Map<String, Object> coreMap = new HashMap<String, Object>();
private String conversion(String key){
if(key==null){
return key;
}
return key.toUpperCase();
}
public void clear() {
coreMap.clear();
}
public boolean containsKey(Object key) {
return coreMap.containsKey(conversion((String)key));
}
public boolean containsValue(Object value) {
return coreMap.containsValue(value);
}
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return coreMap.entrySet();
}
public Object get(Object key) {
return coreMap.get(conversion((String)key));
}
public boolean isEmpty() {
return coreMap.isEmpty();
}
public Set<String> keySet() {
return coreMap.keySet();
}
public Object put(String key, Object value) {
return coreMap.put(conversion(key),value);
}
public void putAll(Map<? extends String, ? extends Object> t) {
// for (Entry<? extends String, ? extends Object> tempEntry : t.entrySet()) {
// coreMap.put(tempEntry.getKey(), tempEntry.getValue());
// }
Set<?> set = t.keySet();
for(Iterator<?> iter = set.iterator(); iter.hasNext();){
String key = (String)iter.next();
coreMap.put(conversion(key),t.get(key));
}
}
public Object remove(Object key) {
return coreMap.remove(conversion((String)key));
}
public int size() {
return coreMap.size();
}
public Collection<Object> values() {
return coreMap.values();
}
public String toString(){
return coreMap.toString();
}
}
| 1,843 | 0.687891 | 0.687891 | 85 | 19.694118 | 20.474962 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.482353 | false | false |
7
|
85c838ea895d29ec2e0c5c2ca4812578d7cb9369
| 6,923,487,348,039 |
d0d9f8e0f7799c170c0ffcab94494c2327a0b6a6
|
/src/main/java/com/talena/agents/couchbase/core/OpenPartition.java
|
ad7cea15f099259c61540e8df8470bc34ea07ada
|
[] |
no_license
|
srinivasv/couchbase-backup
|
https://github.com/srinivasv/couchbase-backup
|
78b36ab204e80f2151b2a95ed2b3f16d351db5e2
|
4d2504575c2839f1e62a6086be520db4f17b0688
|
refs/heads/master
| 2021-01-21T13:15:04.434000 | 2016-06-03T17:57:25 | 2016-06-03T17:57:25 | 49,247,786 | 1 | 1 | null | false | 2016-06-22T08:14:47 | 2016-01-08T03:46:43 | 2016-05-23T06:44:37 | 2016-06-03T17:57:31 | 137 | 0 | 1 | 0 |
Groff
| null | null |
package com.talena.agents.couchbase.core;
import com.couchbase.client.core.message.dcp.FailoverLogEntry;
import com.talena.agents.couchbase.core.AbstractPartition.Type;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import rx.Observable;
import rx.functions.Func1;
/**
* <p>A partition that was successfully opened but hasn't been closed yet.</p>
*
* <p>All of the partition's data may not have been streamed if the connection
* was lost due to some reason.</p>
*/
public class OpenPartition extends AbstractPartition {
// DCP state required for retries of the current stream and any subsequent
// incremental streams. Must be persisted to stable storage after each
// successful streaming operation.
private List<FailoverLogEntry> failoverLog;
private long lastSeenSeqno;
private long lastSnapshotStartSeqno;
private long lastSnapshotEndSeqno;
public OpenPartition(final short id, final PartitionSpec spec) {
super(id, spec);
}
public OpenPartition(final OpenPartition open) {
super(open.id(), open.spec());
this.failoverLog = open.failoverLog();
this.lastSeenSeqno = open.lastSeenSeqno();
this.lastSnapshotStartSeqno = open.lastSnapshotStartSeqno();
this.lastSnapshotEndSeqno = open.lastSnapshotEndSeqno();
}
public OpenPartition(final OpenPartition open, final PartitionSpec spec) {
super(open.id(), spec);
this.failoverLog = open.failoverLog();
this.lastSeenSeqno = open.lastSeenSeqno();
this.lastSnapshotStartSeqno = open.lastSnapshotStartSeqno();
this.lastSnapshotEndSeqno = open.lastSnapshotEndSeqno();
}
@Override
public Type type() {
return Type.Open;
}
public List<FailoverLogEntry> failoverLog() {
return failoverLog;
}
public void failoverLog(List<FailoverLogEntry> failoverLog) {
this.failoverLog = failoverLog;
}
public long lastSeenSeqno() {
return lastSeenSeqno;
}
public void lastSeenSeqno(long lastSeenSeqno) {
this.lastSeenSeqno = lastSeenSeqno;
}
public long lastSnapshotStartSeqno() {
return lastSnapshotStartSeqno;
}
public void lastSnapshotStartSeqno(long lastSnapshotStartSeqno) {
this.lastSnapshotStartSeqno = lastSnapshotStartSeqno;
}
public long lastSnapshotEndSeqno() {
return lastSnapshotEndSeqno;
}
public void lastSnapshotEndSeqno(long lastSnapshotEndSeqno) {
this.lastSnapshotEndSeqno = lastSnapshotEndSeqno;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("OpenPartition{id=").append(id());
sb.append(", failoverLog=").append(StringUtils.join(
Observable.from(failoverLog())
.map(new Func1<FailoverLogEntry, String>() {
@Override
public String call(FailoverLogEntry entry) {
return String.format("FailoverLogEntry{uuid=%d, seqno=%d}",
entry.vbucketUUID(), entry.sequenceNumber());
}
})
.toList()
.toBlocking()
.first()
));
sb.append(", lastSeenSeqno=").append(lastSeenSeqno());
sb.append(", lastSnapshotStartSeqno=").append(lastSnapshotStartSeqno());
sb.append(", lastSnapshotEndSeqno=").append(lastSnapshotEndSeqno());
sb.append("}");
return sb.toString();
}
}
|
UTF-8
|
Java
| 3,279 |
java
|
OpenPartition.java
|
Java
|
[] | null |
[] |
package com.talena.agents.couchbase.core;
import com.couchbase.client.core.message.dcp.FailoverLogEntry;
import com.talena.agents.couchbase.core.AbstractPartition.Type;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import rx.Observable;
import rx.functions.Func1;
/**
* <p>A partition that was successfully opened but hasn't been closed yet.</p>
*
* <p>All of the partition's data may not have been streamed if the connection
* was lost due to some reason.</p>
*/
public class OpenPartition extends AbstractPartition {
// DCP state required for retries of the current stream and any subsequent
// incremental streams. Must be persisted to stable storage after each
// successful streaming operation.
private List<FailoverLogEntry> failoverLog;
private long lastSeenSeqno;
private long lastSnapshotStartSeqno;
private long lastSnapshotEndSeqno;
public OpenPartition(final short id, final PartitionSpec spec) {
super(id, spec);
}
public OpenPartition(final OpenPartition open) {
super(open.id(), open.spec());
this.failoverLog = open.failoverLog();
this.lastSeenSeqno = open.lastSeenSeqno();
this.lastSnapshotStartSeqno = open.lastSnapshotStartSeqno();
this.lastSnapshotEndSeqno = open.lastSnapshotEndSeqno();
}
public OpenPartition(final OpenPartition open, final PartitionSpec spec) {
super(open.id(), spec);
this.failoverLog = open.failoverLog();
this.lastSeenSeqno = open.lastSeenSeqno();
this.lastSnapshotStartSeqno = open.lastSnapshotStartSeqno();
this.lastSnapshotEndSeqno = open.lastSnapshotEndSeqno();
}
@Override
public Type type() {
return Type.Open;
}
public List<FailoverLogEntry> failoverLog() {
return failoverLog;
}
public void failoverLog(List<FailoverLogEntry> failoverLog) {
this.failoverLog = failoverLog;
}
public long lastSeenSeqno() {
return lastSeenSeqno;
}
public void lastSeenSeqno(long lastSeenSeqno) {
this.lastSeenSeqno = lastSeenSeqno;
}
public long lastSnapshotStartSeqno() {
return lastSnapshotStartSeqno;
}
public void lastSnapshotStartSeqno(long lastSnapshotStartSeqno) {
this.lastSnapshotStartSeqno = lastSnapshotStartSeqno;
}
public long lastSnapshotEndSeqno() {
return lastSnapshotEndSeqno;
}
public void lastSnapshotEndSeqno(long lastSnapshotEndSeqno) {
this.lastSnapshotEndSeqno = lastSnapshotEndSeqno;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("OpenPartition{id=").append(id());
sb.append(", failoverLog=").append(StringUtils.join(
Observable.from(failoverLog())
.map(new Func1<FailoverLogEntry, String>() {
@Override
public String call(FailoverLogEntry entry) {
return String.format("FailoverLogEntry{uuid=%d, seqno=%d}",
entry.vbucketUUID(), entry.sequenceNumber());
}
})
.toList()
.toBlocking()
.first()
));
sb.append(", lastSeenSeqno=").append(lastSeenSeqno());
sb.append(", lastSnapshotStartSeqno=").append(lastSnapshotStartSeqno());
sb.append(", lastSnapshotEndSeqno=").append(lastSnapshotEndSeqno());
sb.append("}");
return sb.toString();
}
}
| 3,279 | 0.715157 | 0.714242 | 111 | 28.540541 | 25.143116 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477477 | false | false |
7
|
c6ad82d668d2ec003d4d4e730191a77cb72eb5b0
| 14,336,600,900,860 |
ec9bf57a07b7b06134ec7a21407a11f69cc644f7
|
/src/com/ubercab/rider/realtime/model/Shape_UnpaidBill.java
|
588d49ac6d47e01a93c43ecb34f57664f9f56fe3
|
[] |
no_license
|
jzarca01/com.ubercab
|
https://github.com/jzarca01/com.ubercab
|
f95c12cab7a28f05e8f1d1a9d8a12a5ac7fbf4b1
|
e6b454fb0ad547287ae4e71e59d6b9482369647a
|
refs/heads/master
| 2020-06-21T04:37:43.723000 | 2016-07-19T16:30:34 | 2016-07-19T16:30:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ubercab.rider.realtime.model;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public final class Shape_UnpaidBill
extends UnpaidBill
{
public static final Parcelable.Creator<UnpaidBill> CREATOR = new Shape_UnpaidBill.1();
private static final ClassLoader PARCELABLE_CL = Shape_UnpaidBill.class.getClassLoader();
private String amount;
private String amountString;
private String clientBillUuid;
private String createdAt;
private UnpaidBillTrip trip;
private String uuid;
Shape_UnpaidBill() {}
private Shape_UnpaidBill(Parcel paramParcel)
{
amount = ((String)paramParcel.readValue(PARCELABLE_CL));
amountString = ((String)paramParcel.readValue(PARCELABLE_CL));
createdAt = ((String)paramParcel.readValue(PARCELABLE_CL));
uuid = ((String)paramParcel.readValue(PARCELABLE_CL));
clientBillUuid = ((String)paramParcel.readValue(PARCELABLE_CL));
trip = ((UnpaidBillTrip)paramParcel.readValue(PARCELABLE_CL));
}
public final int describeContents()
{
return 0;
}
public final boolean equals(Object paramObject)
{
if (this == paramObject) {}
do
{
return true;
if ((paramObject == null) || (getClass() != paramObject.getClass())) {
return false;
}
paramObject = (UnpaidBill)paramObject;
if (((UnpaidBill)paramObject).getAmount() != null)
{
if (((UnpaidBill)paramObject).getAmount().equals(getAmount())) {}
}
else {
while (getAmount() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getAmountString() != null)
{
if (((UnpaidBill)paramObject).getAmountString().equals(getAmountString())) {}
}
else {
while (getAmountString() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getCreatedAt() != null)
{
if (((UnpaidBill)paramObject).getCreatedAt().equals(getCreatedAt())) {}
}
else {
while (getCreatedAt() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getUuid() != null)
{
if (((UnpaidBill)paramObject).getUuid().equals(getUuid())) {}
}
else {
while (getUuid() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getClientBillUuid() != null)
{
if (((UnpaidBill)paramObject).getClientBillUuid().equals(getClientBillUuid())) {}
}
else {
while (getClientBillUuid() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getTrip() == null) {
break;
}
} while (((UnpaidBill)paramObject).getTrip().equals(getTrip()));
for (;;)
{
return false;
if (getTrip() == null) {
break;
}
}
}
public final String getAmount()
{
return amount;
}
public final String getAmountString()
{
return amountString;
}
public final String getClientBillUuid()
{
return clientBillUuid;
}
public final String getCreatedAt()
{
return createdAt;
}
public final UnpaidBillTrip getTrip()
{
return trip;
}
@Deprecated
public final String getUuid()
{
return uuid;
}
public final int hashCode()
{
int i1 = 0;
int i;
int j;
label21:
int k;
label30:
int m;
label40:
int n;
if (amount == null)
{
i = 0;
if (amountString != null) {
break label101;
}
j = 0;
if (createdAt != null) {
break label112;
}
k = 0;
if (uuid != null) {
break label123;
}
m = 0;
if (clientBillUuid != null) {
break label135;
}
n = 0;
label50:
if (trip != null) {
break label147;
}
}
for (;;)
{
return (n ^ (m ^ (k ^ (j ^ (i ^ 0xF4243) * 1000003) * 1000003) * 1000003) * 1000003) * 1000003 ^ i1;
i = amount.hashCode();
break;
label101:
j = amountString.hashCode();
break label21;
label112:
k = createdAt.hashCode();
break label30;
label123:
m = uuid.hashCode();
break label40;
label135:
n = clientBillUuid.hashCode();
break label50;
label147:
i1 = trip.hashCode();
}
}
final UnpaidBill setAmount(String paramString)
{
amount = paramString;
return this;
}
final UnpaidBill setAmountString(String paramString)
{
amountString = paramString;
return this;
}
final UnpaidBill setClientBillUuid(String paramString)
{
clientBillUuid = paramString;
return this;
}
final UnpaidBill setCreatedAt(String paramString)
{
createdAt = paramString;
return this;
}
final UnpaidBill setTrip(UnpaidBillTrip paramUnpaidBillTrip)
{
trip = paramUnpaidBillTrip;
return this;
}
@Deprecated
final UnpaidBill setUuid(String paramString)
{
uuid = paramString;
return this;
}
public final String toString()
{
return "UnpaidBill{amount=" + amount + ", amountString=" + amountString + ", createdAt=" + createdAt + ", uuid=" + uuid + ", clientBillUuid=" + clientBillUuid + ", trip=" + trip + "}";
}
public final void writeToParcel(Parcel paramParcel, int paramInt)
{
paramParcel.writeValue(amount);
paramParcel.writeValue(amountString);
paramParcel.writeValue(createdAt);
paramParcel.writeValue(uuid);
paramParcel.writeValue(clientBillUuid);
paramParcel.writeValue(trip);
}
}
/* Location:
* Qualified Name: com.ubercab.rider.realtime.model.Shape_UnpaidBill
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
UTF-8
|
Java
| 5,724 |
java
|
Shape_UnpaidBill.java
|
Java
|
[] | null |
[] |
package com.ubercab.rider.realtime.model;
import android.os.Parcel;
import android.os.Parcelable.Creator;
public final class Shape_UnpaidBill
extends UnpaidBill
{
public static final Parcelable.Creator<UnpaidBill> CREATOR = new Shape_UnpaidBill.1();
private static final ClassLoader PARCELABLE_CL = Shape_UnpaidBill.class.getClassLoader();
private String amount;
private String amountString;
private String clientBillUuid;
private String createdAt;
private UnpaidBillTrip trip;
private String uuid;
Shape_UnpaidBill() {}
private Shape_UnpaidBill(Parcel paramParcel)
{
amount = ((String)paramParcel.readValue(PARCELABLE_CL));
amountString = ((String)paramParcel.readValue(PARCELABLE_CL));
createdAt = ((String)paramParcel.readValue(PARCELABLE_CL));
uuid = ((String)paramParcel.readValue(PARCELABLE_CL));
clientBillUuid = ((String)paramParcel.readValue(PARCELABLE_CL));
trip = ((UnpaidBillTrip)paramParcel.readValue(PARCELABLE_CL));
}
public final int describeContents()
{
return 0;
}
public final boolean equals(Object paramObject)
{
if (this == paramObject) {}
do
{
return true;
if ((paramObject == null) || (getClass() != paramObject.getClass())) {
return false;
}
paramObject = (UnpaidBill)paramObject;
if (((UnpaidBill)paramObject).getAmount() != null)
{
if (((UnpaidBill)paramObject).getAmount().equals(getAmount())) {}
}
else {
while (getAmount() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getAmountString() != null)
{
if (((UnpaidBill)paramObject).getAmountString().equals(getAmountString())) {}
}
else {
while (getAmountString() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getCreatedAt() != null)
{
if (((UnpaidBill)paramObject).getCreatedAt().equals(getCreatedAt())) {}
}
else {
while (getCreatedAt() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getUuid() != null)
{
if (((UnpaidBill)paramObject).getUuid().equals(getUuid())) {}
}
else {
while (getUuid() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getClientBillUuid() != null)
{
if (((UnpaidBill)paramObject).getClientBillUuid().equals(getClientBillUuid())) {}
}
else {
while (getClientBillUuid() != null) {
return false;
}
}
if (((UnpaidBill)paramObject).getTrip() == null) {
break;
}
} while (((UnpaidBill)paramObject).getTrip().equals(getTrip()));
for (;;)
{
return false;
if (getTrip() == null) {
break;
}
}
}
public final String getAmount()
{
return amount;
}
public final String getAmountString()
{
return amountString;
}
public final String getClientBillUuid()
{
return clientBillUuid;
}
public final String getCreatedAt()
{
return createdAt;
}
public final UnpaidBillTrip getTrip()
{
return trip;
}
@Deprecated
public final String getUuid()
{
return uuid;
}
public final int hashCode()
{
int i1 = 0;
int i;
int j;
label21:
int k;
label30:
int m;
label40:
int n;
if (amount == null)
{
i = 0;
if (amountString != null) {
break label101;
}
j = 0;
if (createdAt != null) {
break label112;
}
k = 0;
if (uuid != null) {
break label123;
}
m = 0;
if (clientBillUuid != null) {
break label135;
}
n = 0;
label50:
if (trip != null) {
break label147;
}
}
for (;;)
{
return (n ^ (m ^ (k ^ (j ^ (i ^ 0xF4243) * 1000003) * 1000003) * 1000003) * 1000003) * 1000003 ^ i1;
i = amount.hashCode();
break;
label101:
j = amountString.hashCode();
break label21;
label112:
k = createdAt.hashCode();
break label30;
label123:
m = uuid.hashCode();
break label40;
label135:
n = clientBillUuid.hashCode();
break label50;
label147:
i1 = trip.hashCode();
}
}
final UnpaidBill setAmount(String paramString)
{
amount = paramString;
return this;
}
final UnpaidBill setAmountString(String paramString)
{
amountString = paramString;
return this;
}
final UnpaidBill setClientBillUuid(String paramString)
{
clientBillUuid = paramString;
return this;
}
final UnpaidBill setCreatedAt(String paramString)
{
createdAt = paramString;
return this;
}
final UnpaidBill setTrip(UnpaidBillTrip paramUnpaidBillTrip)
{
trip = paramUnpaidBillTrip;
return this;
}
@Deprecated
final UnpaidBill setUuid(String paramString)
{
uuid = paramString;
return this;
}
public final String toString()
{
return "UnpaidBill{amount=" + amount + ", amountString=" + amountString + ", createdAt=" + createdAt + ", uuid=" + uuid + ", clientBillUuid=" + clientBillUuid + ", trip=" + trip + "}";
}
public final void writeToParcel(Parcel paramParcel, int paramInt)
{
paramParcel.writeValue(amount);
paramParcel.writeValue(amountString);
paramParcel.writeValue(createdAt);
paramParcel.writeValue(uuid);
paramParcel.writeValue(clientBillUuid);
paramParcel.writeValue(trip);
}
}
/* Location:
* Qualified Name: com.ubercab.rider.realtime.model.Shape_UnpaidBill
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 5,724 | 0.595213 | 0.577044 | 248 | 22.084677 | 23.624517 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.383065 | false | false |
7
|
3f97b9f81b1dcd740c648bc9b90cfb9c5d60e80d
| 14,190,571,965,076 |
6f6ab8d7640a31d2b1c653dc0610279395f0cb60
|
/MP1/src/MP1/MyList.java
|
3877704e32fadfa0fc7771cca29af5664d270604
|
[] |
no_license
|
bjdag1234/cs145git
|
https://github.com/bjdag1234/cs145git
|
274212b4f4303e2c79bce4ff878a6d876e7d369a
|
3c1831e34175f66677556ca8faab1dc35b179eec
|
refs/heads/master
| 2020-06-02T08:04:48.976000 | 2012-01-31T14:00:05 | 2012-01-31T14:00:05 | 3,163,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package MP1;
/**
* this class was modified from an online source
* Source: http://www.dreamincode.net/forums/topic/44036-how-to-add-tooltip-on-jlist-item/
*/
import javax.swing.*;
import java.awt.event.*;
// Custom class to extend our JList and expose tooltip functionality.
class MyList extends JList {
User_List ul;
JTextArea input;
public MyList(User_List uls, JTextArea inpt) {
super();
ul = uls;
input = inpt;
// Attach a mouse motion adapter to let us know the mouse is over an item and to show the tip.
addMouseMotionListener( new MouseMotionAdapter() {
@Override
public void mouseMoved( MouseEvent e) {
MyList theList = (MyList) e.getSource();
//ListModel model = theList.getModel();
int index = theList.locationToIndex(e.getPoint());
if (index > -1) {
theList.setToolTipText(null);
String text = ul.getUserAt(index).getStatus();
theList.setToolTipText(text);
}
}
});
addMouseListener(new MouseListener(){
int count=0;
int index=-1;
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Click "+count +" index = "+index);
MyList theList = (MyList) e.getSource();
int indx = theList.locationToIndex(e.getPoint());
if (indx == index)
count++;
else{
count = 0;
index = indx;
}
if (count >= 2){
String name = ul.getUserAt(index).getName();
input.setText("/whisper "+name+" ");
}
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
});
}
// Expose the getToolTipText event of our JList
@Override
public String getToolTipText(MouseEvent e){
return super.getToolTipText();
}
}
|
UTF-8
|
Java
| 2,374 |
java
|
MyList.java
|
Java
|
[] | null |
[] |
package MP1;
/**
* this class was modified from an online source
* Source: http://www.dreamincode.net/forums/topic/44036-how-to-add-tooltip-on-jlist-item/
*/
import javax.swing.*;
import java.awt.event.*;
// Custom class to extend our JList and expose tooltip functionality.
class MyList extends JList {
User_List ul;
JTextArea input;
public MyList(User_List uls, JTextArea inpt) {
super();
ul = uls;
input = inpt;
// Attach a mouse motion adapter to let us know the mouse is over an item and to show the tip.
addMouseMotionListener( new MouseMotionAdapter() {
@Override
public void mouseMoved( MouseEvent e) {
MyList theList = (MyList) e.getSource();
//ListModel model = theList.getModel();
int index = theList.locationToIndex(e.getPoint());
if (index > -1) {
theList.setToolTipText(null);
String text = ul.getUserAt(index).getStatus();
theList.setToolTipText(text);
}
}
});
addMouseListener(new MouseListener(){
int count=0;
int index=-1;
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Click "+count +" index = "+index);
MyList theList = (MyList) e.getSource();
int indx = theList.locationToIndex(e.getPoint());
if (indx == index)
count++;
else{
count = 0;
index = indx;
}
if (count >= 2){
String name = ul.getUserAt(index).getName();
input.setText("/whisper "+name+" ");
}
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
});
}
// Expose the getToolTipText event of our JList
@Override
public String getToolTipText(MouseEvent e){
return super.getToolTipText();
}
}
| 2,374 | 0.512637 | 0.508003 | 74 | 31.094595 | 22.864565 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false |
7
|
b711d744d0ea49e7f5732dc6678e1c09ae9ceb01
| 7,258,494,774,154 |
6dbae30c806f661bcdcbc5f5f6a366ad702b1eea
|
/Corpus/eclipse.jdt.core/4282.java
|
91925cb59501cb3c328fb1404ae81aa1a1c90188
|
[
"MIT"
] |
permissive
|
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
|
https://github.com/SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
|
d3fd21745dfddb2979e8ac262588cfdfe471899f
|
0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0
|
refs/heads/master
| 2020-03-31T15:52:01.005000 | 2018-10-01T23:38:50 | 2018-10-01T23:38:50 | 152,354,327 | 1 | 0 |
MIT
| true | 2018-10-10T02:57:02 | 2018-10-10T02:57:02 | 2018-10-01T23:38:52 | 2018-10-01T23:38:50 | 135,431 | 0 | 0 | 0 | null | false | null |
package targets.bug407841;
import targets.bug407841.ModuleLegacy;
import org.eclipse.jdt.apt.pluggable.tests.annotations.Module;
@Module(key = ModuleCore.KEY)
public class ModuleCore {
public static final String LEGACY_KEY = ModuleLegacy.KEY;
public static final String KEY = "CORE";
}
|
UTF-8
|
Java
| 298 |
java
|
4282.java
|
Java
|
[] | null |
[] |
package targets.bug407841;
import targets.bug407841.ModuleLegacy;
import org.eclipse.jdt.apt.pluggable.tests.annotations.Module;
@Module(key = ModuleCore.KEY)
public class ModuleCore {
public static final String LEGACY_KEY = ModuleLegacy.KEY;
public static final String KEY = "CORE";
}
| 298 | 0.771812 | 0.731544 | 12 | 23.833334 | 22.861298 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
7
|
5102ad85450cf2295cc7a7f561823159a6b2c314
| 21,827,023,856,895 |
624abcd9562f276f6d492282cc8e20251bb9d935
|
/hejiameng/src/main/java/com/sangame/hjm/manager/OnLineMessageByExcel.java
|
36f7c3647ee66ee1feb294ac9fb5e7ed602b4b38
|
[] |
no_license
|
shangguanxiaoguan/AutoTest
|
https://github.com/shangguanxiaoguan/AutoTest
|
45864c986ef4564b3d1b210f3c63e8cf8e9d6e4b
|
afd41d39b318b0191ae795ef36e262a6c196e679
|
refs/heads/master
| 2022-07-12T07:42:14.136000 | 2019-08-15T06:08:01 | 2019-08-15T06:08:01 | 188,189,539 | 0 | 0 | null | false | 2022-06-29T17:34:22 | 2019-05-23T08:05:32 | 2019-08-15T06:08:24 | 2022-06-29T17:34:22 | 5,970 | 0 | 0 | 19 |
Java
| false | false |
package com.sangame.hjm.manager;
import com.google.gson.Gson;
import com.sangame.hjm.base.BaseApi;
import com.sangame.hjm.config.TestConfig;
import com.sangame.hjm.model.InterfaceName;
import com.sangame.hjm.model.OnLineMessageResult;
import com.sangame.hjm.utils.ConfigFile;
import com.sangame.hjm.utils.HttpMethodPostUtil;
import com.sangame.hjm.utils.ReadExcelUtil;
import org.apache.http.impl.client.DefaultHttpClient;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class OnLineMessageByExcel extends BaseApi {
@BeforeTest
public void beforeTest(){
TestConfig.onLineMessageUrl = ConfigFile.getUrl(InterfaceName.ONLINEMESSAGE);
TestConfig.defaultHttpClient = new DefaultHttpClient();
}
@DataProvider(name = "post")
public Iterator<Object[]> post() throws IOException {
//Excel表格中的sheet页来填写数字参数,第一页下标为0
System.out.println("========哈哈哈哈");
// Object[][] objects = ReadExcelUtil.readExData(testCaseExcel,1);
// System.out.println(objects.toString());
// return ReadExcelUtil.readExData(testCaseExcel,1);
List<Map<String,String>> data = ReadExcelUtil.getData(testCaseExcel);
System.out.println("从Excel中获取的数据:" + data.toString());
// data.add()
return null;
}
@Test(dataProvider = "post")
//此处传递的参数必须和Excel表中的顺序一致,不然会报错
public void onLineMessage(String cngoldId, String commentId,String content) throws Exception {
System.out.println("黄金矿工的科技感的空间发");
//使用构造函数将传入的用户名密码初始化成登录请求参数
// LoginOrRegisterCase loginParameters = new LoginOrRegisterCase(account,loginPwd,partnerCode);
// Map<String, String> map=FastjsonUtils.toMap(FastjsonUtils.toJson(loginParameters));
// //Log.info("my out**********"+map);
// //发送登录请求
// CloseableHttpResponse closeableHttpResponse = RestClient.postForm(hostManager+loginUrl, map, null);
// //从返回结果中获取状态码
// int statusCode = RestClient.getStatusCode(closeableHttpResponse);
// //Assert.assertEquals(statusCode,Constants.RESPNSE_STATUS_CODE_200,"status code is not 200");
// //断言响应json内容中name和job是不是期待结果
// String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
// System.out.println("my out**********"+responseString);
// //JSONObject res = FastjsonUtils.toJsonObject(responseString);
// //sessionKey = FastjsonUtils.toMap(res.getString("data")).get("session_key");
// System.out.println("data**********: " + res.getString("message"));
// System.out.println("data**********: " + sessionKey);
// String partnerType=FastjsonUtils.toMap(res.getString("data")).get("partnerType");
// Assert.assertEquals(partnerType,"路内" ,"partnerType is not 路内");
//SqlSession sqlSession = DatebaseUtil.getSqlSession();
//LoginOrRegisterCase loginOrRegisterCase = sqlSession.selectOne("loginOrRegisterCase",1);
//System.out.println("loginOrRegisterCase:" + loginOrRegisterCase.toString());
//发送请求,获取接口返回的结果
Map<String,Object> map = new HashMap<>();
map.put("cngoldId",cngoldId);
map.put("commentId",commentId);
map.put("content",content);
System.out.println("在线留言测试数据:" + map.toString());
String result = HttpMethodPostUtil.httpMethodPost(TestConfig.onLineMessageUrl,map);
OnLineMessageResult onLineMessageResult = new Gson().fromJson(result,OnLineMessageResult.class);
System.out.println("在线留言接口返回的结果:" + onLineMessageResult.toString());
//验证结果
// SqlSession expectedSession = DatebaseUtil.getSqlSession();
// JmUser expectedResult = expectedSession.selectOne("getUserInfo",loginOrRegisterCase.getMobile());
// System.out.println("数据库获取结果:" + expectedResult.toString());
Assert.assertEquals(onLineMessageResult.getCode(),0);
}
// @BeforeClass
// public void endTest(){
// System.out.print("测试结束");
// }
}
|
UTF-8
|
Java
| 4,547 |
java
|
OnLineMessageByExcel.java
|
Java
|
[] | null |
[] |
package com.sangame.hjm.manager;
import com.google.gson.Gson;
import com.sangame.hjm.base.BaseApi;
import com.sangame.hjm.config.TestConfig;
import com.sangame.hjm.model.InterfaceName;
import com.sangame.hjm.model.OnLineMessageResult;
import com.sangame.hjm.utils.ConfigFile;
import com.sangame.hjm.utils.HttpMethodPostUtil;
import com.sangame.hjm.utils.ReadExcelUtil;
import org.apache.http.impl.client.DefaultHttpClient;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class OnLineMessageByExcel extends BaseApi {
@BeforeTest
public void beforeTest(){
TestConfig.onLineMessageUrl = ConfigFile.getUrl(InterfaceName.ONLINEMESSAGE);
TestConfig.defaultHttpClient = new DefaultHttpClient();
}
@DataProvider(name = "post")
public Iterator<Object[]> post() throws IOException {
//Excel表格中的sheet页来填写数字参数,第一页下标为0
System.out.println("========哈哈哈哈");
// Object[][] objects = ReadExcelUtil.readExData(testCaseExcel,1);
// System.out.println(objects.toString());
// return ReadExcelUtil.readExData(testCaseExcel,1);
List<Map<String,String>> data = ReadExcelUtil.getData(testCaseExcel);
System.out.println("从Excel中获取的数据:" + data.toString());
// data.add()
return null;
}
@Test(dataProvider = "post")
//此处传递的参数必须和Excel表中的顺序一致,不然会报错
public void onLineMessage(String cngoldId, String commentId,String content) throws Exception {
System.out.println("黄金矿工的科技感的空间发");
//使用构造函数将传入的用户名密码初始化成登录请求参数
// LoginOrRegisterCase loginParameters = new LoginOrRegisterCase(account,loginPwd,partnerCode);
// Map<String, String> map=FastjsonUtils.toMap(FastjsonUtils.toJson(loginParameters));
// //Log.info("my out**********"+map);
// //发送登录请求
// CloseableHttpResponse closeableHttpResponse = RestClient.postForm(hostManager+loginUrl, map, null);
// //从返回结果中获取状态码
// int statusCode = RestClient.getStatusCode(closeableHttpResponse);
// //Assert.assertEquals(statusCode,Constants.RESPNSE_STATUS_CODE_200,"status code is not 200");
// //断言响应json内容中name和job是不是期待结果
// String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
// System.out.println("my out**********"+responseString);
// //JSONObject res = FastjsonUtils.toJsonObject(responseString);
// //sessionKey = FastjsonUtils.toMap(res.getString("data")).get("session_key");
// System.out.println("data**********: " + res.getString("message"));
// System.out.println("data**********: " + sessionKey);
// String partnerType=FastjsonUtils.toMap(res.getString("data")).get("partnerType");
// Assert.assertEquals(partnerType,"路内" ,"partnerType is not 路内");
//SqlSession sqlSession = DatebaseUtil.getSqlSession();
//LoginOrRegisterCase loginOrRegisterCase = sqlSession.selectOne("loginOrRegisterCase",1);
//System.out.println("loginOrRegisterCase:" + loginOrRegisterCase.toString());
//发送请求,获取接口返回的结果
Map<String,Object> map = new HashMap<>();
map.put("cngoldId",cngoldId);
map.put("commentId",commentId);
map.put("content",content);
System.out.println("在线留言测试数据:" + map.toString());
String result = HttpMethodPostUtil.httpMethodPost(TestConfig.onLineMessageUrl,map);
OnLineMessageResult onLineMessageResult = new Gson().fromJson(result,OnLineMessageResult.class);
System.out.println("在线留言接口返回的结果:" + onLineMessageResult.toString());
//验证结果
// SqlSession expectedSession = DatebaseUtil.getSqlSession();
// JmUser expectedResult = expectedSession.selectOne("getUserInfo",loginOrRegisterCase.getMobile());
// System.out.println("数据库获取结果:" + expectedResult.toString());
Assert.assertEquals(onLineMessageResult.getCode(),0);
}
// @BeforeClass
// public void endTest(){
// System.out.print("测试结束");
// }
}
| 4,547 | 0.699451 | 0.696825 | 93 | 44.043011 | 30.76687 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.88172 | false | false |
5
|
edd17e05e948adff5bb71693b824df1b94fc7e8e
| 21,827,023,859,885 |
c47d5163b84a27cd9fad912c6be4ea24c2304408
|
/epsAndes/src/main/java/uniandes/isis2304/epsAndes/persistencia/SQLCampana.java
|
cf54ec35042e07376dd7861a02d2a476e9c26c19
|
[] |
no_license
|
ja-avos/EPSAndes
|
https://github.com/ja-avos/EPSAndes
|
128b93d3c2a9d7c9b88188a4d68e18a288fe2d32
|
2fa81938e2e30b31fb3c1d59965e20026e9d7e78
|
refs/heads/master
| 2022-03-08T21:57:18.681000 | 2019-12-05T02:52:55 | 2019-12-05T02:52:55 | 211,563,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uniandes.isis2304.epsAndes.persistencia;
import java.sql.Timestamp;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
public class SQLCampana {
private final static String SQL = PersistenciaEPSAndes.SQL;
private PersistenciaEPSAndes pe;
public SQLCampana (PersistenciaEPSAndes pe)
{
this.pe = pe;
}
public long addCampana (PersistenceManager pm, long id_Campana, Timestamp fecha_inicio,
Timestamp fecha_Fin)
{
Query q = pm.newQuery(SQL, "INSERT INTO " + pe.getTableCampana() +
"(id_Campana, fecha_inicio, fecha_fin, cancelada) values (?,?,?,?)");
q.setParameters(id_Campana, fecha_inicio, fecha_Fin, 0);
return (long) q.executeUnique();
}
public long cancelCampana (PersistenceManager pm, long id_campana) {
Query q = pm.newQuery(SQL, "UPDATE " + pe.getTableCampana() +
" SET cancelada = 1 WHERE id_campana = ?");
q.setParameters(id_campana);
return (long) q.executeUnique();
}
}
|
UTF-8
|
Java
| 981 |
java
|
SQLCampana.java
|
Java
|
[] | null |
[] |
package uniandes.isis2304.epsAndes.persistencia;
import java.sql.Timestamp;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
public class SQLCampana {
private final static String SQL = PersistenciaEPSAndes.SQL;
private PersistenciaEPSAndes pe;
public SQLCampana (PersistenciaEPSAndes pe)
{
this.pe = pe;
}
public long addCampana (PersistenceManager pm, long id_Campana, Timestamp fecha_inicio,
Timestamp fecha_Fin)
{
Query q = pm.newQuery(SQL, "INSERT INTO " + pe.getTableCampana() +
"(id_Campana, fecha_inicio, fecha_fin, cancelada) values (?,?,?,?)");
q.setParameters(id_Campana, fecha_inicio, fecha_Fin, 0);
return (long) q.executeUnique();
}
public long cancelCampana (PersistenceManager pm, long id_campana) {
Query q = pm.newQuery(SQL, "UPDATE " + pe.getTableCampana() +
" SET cancelada = 1 WHERE id_campana = ?");
q.setParameters(id_campana);
return (long) q.executeUnique();
}
}
| 981 | 0.69317 | 0.687054 | 34 | 27.852942 | 27.373379 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.676471 | false | false |
5
|
999cb59373d2c025dca2ee952ebbc3b145d00d64
| 26,182,120,636,516 |
1ef497fef3ca2bd5981ff2a6d3b5df32a845ce85
|
/jadx-decompile/com/google/android/gms/internal/iy.java
|
0b10ba27e2a38dcba04e42633130028b1c0e889f
|
[] |
no_license
|
gmtandi/droneapp
|
https://github.com/gmtandi/droneapp
|
624eeb8a77bbb6cbe3160d79d0c9b46e827e8f4f
|
bfacef0ef2cc43aded3e03c012debcee868706c5
|
refs/heads/master
| 2019-07-22T10:11:35.423000 | 2017-06-01T00:38:41 | 2017-06-01T00:38:41 | 92,822,587 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.google.android.gms.internal;
public class iy {
private final long a;
private final ij b;
private final lh c;
private final ia d;
private final boolean e;
public iy(long j, ij ijVar, ia iaVar) {
this.a = j;
this.b = ijVar;
this.c = null;
this.d = iaVar;
this.e = true;
}
public iy(long j, ij ijVar, lh lhVar, boolean z) {
this.a = j;
this.b = ijVar;
this.c = lhVar;
this.d = null;
this.e = z;
}
public long a() {
return this.a;
}
public ij b() {
return this.b;
}
public lh c() {
if (this.c != null) {
return this.c;
}
throw new IllegalArgumentException("Can't access overwrite when write is a merge!");
}
public ia d() {
if (this.d != null) {
return this.d;
}
throw new IllegalArgumentException("Can't access merge when write is an overwrite!");
}
public boolean e() {
return this.c != null;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
iy iyVar = (iy) obj;
if (this.a != iyVar.a) {
return false;
}
if (!this.b.equals(iyVar.b)) {
return false;
}
if (this.e != iyVar.e) {
return false;
}
if (!this.c == null ? this.c.equals(iyVar.c) : iyVar.c == null) {
return false;
}
if (this.d != null) {
if (this.d.equals(iyVar.d)) {
return true;
}
} else if (iyVar.d == null) {
return true;
}
return false;
}
public boolean f() {
return this.e;
}
public int hashCode() {
int i = 0;
int hashCode = ((this.c != null ? this.c.hashCode() : 0) + (((((Long.valueOf(this.a).hashCode() * 31) + Boolean.valueOf(this.e).hashCode()) * 31) + this.b.hashCode()) * 31)) * 31;
if (this.d != null) {
i = this.d.hashCode();
}
return hashCode + i;
}
public String toString() {
long j = this.a;
String valueOf = String.valueOf(this.b);
boolean z = this.e;
String valueOf2 = String.valueOf(this.c);
String valueOf3 = String.valueOf(this.d);
return new StringBuilder(((String.valueOf(valueOf).length() + 78) + String.valueOf(valueOf2).length()) + String.valueOf(valueOf3).length()).append("UserWriteRecord{id=").append(j).append(" path=").append(valueOf).append(" visible=").append(z).append(" overwrite=").append(valueOf2).append(" merge=").append(valueOf3).append("}").toString();
}
}
|
UTF-8
|
Java
| 2,823 |
java
|
iy.java
|
Java
|
[] | null |
[] |
package com.google.android.gms.internal;
public class iy {
private final long a;
private final ij b;
private final lh c;
private final ia d;
private final boolean e;
public iy(long j, ij ijVar, ia iaVar) {
this.a = j;
this.b = ijVar;
this.c = null;
this.d = iaVar;
this.e = true;
}
public iy(long j, ij ijVar, lh lhVar, boolean z) {
this.a = j;
this.b = ijVar;
this.c = lhVar;
this.d = null;
this.e = z;
}
public long a() {
return this.a;
}
public ij b() {
return this.b;
}
public lh c() {
if (this.c != null) {
return this.c;
}
throw new IllegalArgumentException("Can't access overwrite when write is a merge!");
}
public ia d() {
if (this.d != null) {
return this.d;
}
throw new IllegalArgumentException("Can't access merge when write is an overwrite!");
}
public boolean e() {
return this.c != null;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
iy iyVar = (iy) obj;
if (this.a != iyVar.a) {
return false;
}
if (!this.b.equals(iyVar.b)) {
return false;
}
if (this.e != iyVar.e) {
return false;
}
if (!this.c == null ? this.c.equals(iyVar.c) : iyVar.c == null) {
return false;
}
if (this.d != null) {
if (this.d.equals(iyVar.d)) {
return true;
}
} else if (iyVar.d == null) {
return true;
}
return false;
}
public boolean f() {
return this.e;
}
public int hashCode() {
int i = 0;
int hashCode = ((this.c != null ? this.c.hashCode() : 0) + (((((Long.valueOf(this.a).hashCode() * 31) + Boolean.valueOf(this.e).hashCode()) * 31) + this.b.hashCode()) * 31)) * 31;
if (this.d != null) {
i = this.d.hashCode();
}
return hashCode + i;
}
public String toString() {
long j = this.a;
String valueOf = String.valueOf(this.b);
boolean z = this.e;
String valueOf2 = String.valueOf(this.c);
String valueOf3 = String.valueOf(this.d);
return new StringBuilder(((String.valueOf(valueOf).length() + 78) + String.valueOf(valueOf2).length()) + String.valueOf(valueOf3).length()).append("UserWriteRecord{id=").append(j).append(" path=").append(valueOf).append(" visible=").append(z).append(" overwrite=").append(valueOf2).append(" merge=").append(valueOf3).append("}").toString();
}
}
| 2,823 | 0.504428 | 0.498052 | 103 | 26.407766 | 39.741749 | 348 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.495146 | false | false |
5
|
795926c588421c3b1ab34c06a209ba311c9ba1ac
| 7,627,861,980,792 |
d368c7c3797cc3ff28bee06c7a4b10a01567cedf
|
/src/main/java/edu/mum/asd/libraryframework/service/BookService.java
|
89a4d0bb94c3e4c077dbf6ceae56a51be379105b
|
[] |
no_license
|
MafrelKarki/Library-Framework
|
https://github.com/MafrelKarki/Library-Framework
|
0f2628108a1d3cf57be7d9e46dc7af2ad63e3712
|
f17317f2d46553b6d4c324d99f295321cd38feb3
|
refs/heads/master
| 2020-03-17T10:16:57.060000 | 2018-05-17T22:19:15 | 2018-05-17T22:19:15 | 133,506,754 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.mum.asd.libraryframework.service;
import edu.mum.asd.libraryframework.dao.DAOFactoryImpl;
import edu.mum.asd.libraryframework.dao.IDAOFactory;
import edu.mum.asd.libraryframework.dao.IItemDAO;
import edu.mum.asd.libraryframework.model.IItem;
public class BookService {
IDAOFactory idaoFactory=new DAOFactoryImpl();
IItemDAO cdDao= idaoFactory.getItemDAO("CD");
public void create(IItem item) {
cdDao.create(item);
}
public void delete(IItem item) {
cdDao.delete(item);
}
public void update(IItem item) {
cdDao.delete(item);
}
public IItem find(IItem item) {
return cdDao.find(item);
}
}
|
UTF-8
|
Java
| 635 |
java
|
BookService.java
|
Java
|
[] | null |
[] |
package edu.mum.asd.libraryframework.service;
import edu.mum.asd.libraryframework.dao.DAOFactoryImpl;
import edu.mum.asd.libraryframework.dao.IDAOFactory;
import edu.mum.asd.libraryframework.dao.IItemDAO;
import edu.mum.asd.libraryframework.model.IItem;
public class BookService {
IDAOFactory idaoFactory=new DAOFactoryImpl();
IItemDAO cdDao= idaoFactory.getItemDAO("CD");
public void create(IItem item) {
cdDao.create(item);
}
public void delete(IItem item) {
cdDao.delete(item);
}
public void update(IItem item) {
cdDao.delete(item);
}
public IItem find(IItem item) {
return cdDao.find(item);
}
}
| 635 | 0.748031 | 0.748031 | 31 | 19.483871 | 19.72369 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.129032 | false | false |
5
|
a394ee31616dd689555fb2ea29ee765019a7547e
| 12,764,642,806,910 |
dddf410dc4b13ebc014bc3c81a2918080c7f14cf
|
/call_system_service/src/main/java/bz/sunlight/service/CustomerService.java
|
7da79b63733d34b534b8370162400cc3808e65cc
|
[] |
no_license
|
LIZISHU1997/call-center
|
https://github.com/LIZISHU1997/call-center
|
e9a1ab4947313387d2057cbb670bd9c25ab28322
|
6155f101f86091ab5ec752da703a7d496105b1fd
|
refs/heads/master
| 2021-06-18T16:40:25.455000 | 2017-06-22T02:35:55 | 2017-06-22T02:39:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bz.sunlight.service;
import java.util.List;
import java.util.Map;
import bz.sunlight.dto.CallRecordDTO;
import bz.sunlight.dto.CustomerTagDTO;
import bz.sunlight.entity.CallRecord;
import bz.sunlight.entity.CustomerServer;
import bz.sunlight.entity.CustomerTag;
import bz.sunlight.vo.CallRecordVo;
public interface CustomerService {
List<CustomerTag> getCustomerTagWithCallRecord(String importBatch,int pageNo,int itemCount);
List<CustomerTag> getCustomerTag(String importBatch,int pageNo,int itemCount);
CustomerTag getCustomerTag(String id);
void updateCustomerTag(CustomerTag customerTag);
void insertCallRecord(CallRecordVo callRecordVo,CustomerServer customerServer);
void updateCallRecord(CallRecordVo callRecordVo);
CallRecord getCallRecord(String id);
CallRecord getCallRecord(String customerTagId,Short status);
List<CallRecord> getCallRecordByCustomerTagId(String customerTagId);
List<String> selectionBatch();
int getCount(String batch);
int getDialTime(String customerTagId);
int selectRecordCount(Map map);
List<CallRecord> selectRecordByBatch(Map map);
public List<CustomerTag> selectCustomerTagByCondition(CallRecordDTO customerTagDTO);
public int selectCustomerTagCountByCondition(CallRecordDTO customerTagDTO);
List<CustomerTag> selectCustomerTagByConditionExcel(CallRecordDTO customerTagDTO);
List<CallRecord> getCallRecordByCustomerTagIdExcel(Map map);
List<CustomerTag> selectCustomerTagByConditionTest(CallRecordDTO callRecordDTO);
void updateByIdSelective(CallRecord record);
}
|
UTF-8
|
Java
| 1,572 |
java
|
CustomerService.java
|
Java
|
[] | null |
[] |
package bz.sunlight.service;
import java.util.List;
import java.util.Map;
import bz.sunlight.dto.CallRecordDTO;
import bz.sunlight.dto.CustomerTagDTO;
import bz.sunlight.entity.CallRecord;
import bz.sunlight.entity.CustomerServer;
import bz.sunlight.entity.CustomerTag;
import bz.sunlight.vo.CallRecordVo;
public interface CustomerService {
List<CustomerTag> getCustomerTagWithCallRecord(String importBatch,int pageNo,int itemCount);
List<CustomerTag> getCustomerTag(String importBatch,int pageNo,int itemCount);
CustomerTag getCustomerTag(String id);
void updateCustomerTag(CustomerTag customerTag);
void insertCallRecord(CallRecordVo callRecordVo,CustomerServer customerServer);
void updateCallRecord(CallRecordVo callRecordVo);
CallRecord getCallRecord(String id);
CallRecord getCallRecord(String customerTagId,Short status);
List<CallRecord> getCallRecordByCustomerTagId(String customerTagId);
List<String> selectionBatch();
int getCount(String batch);
int getDialTime(String customerTagId);
int selectRecordCount(Map map);
List<CallRecord> selectRecordByBatch(Map map);
public List<CustomerTag> selectCustomerTagByCondition(CallRecordDTO customerTagDTO);
public int selectCustomerTagCountByCondition(CallRecordDTO customerTagDTO);
List<CustomerTag> selectCustomerTagByConditionExcel(CallRecordDTO customerTagDTO);
List<CallRecord> getCallRecordByCustomerTagIdExcel(Map map);
List<CustomerTag> selectCustomerTagByConditionTest(CallRecordDTO callRecordDTO);
void updateByIdSelective(CallRecord record);
}
| 1,572 | 0.826336 | 0.826336 | 56 | 27.071428 | 28.857939 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.321429 | false | false |
5
|
59a199e62e513e1bd4739ada92e61f85fb287b83
| 23,416,161,704,250 |
7aaaaa6615adf38e191e833e477e51bccb18b399
|
/ClientKTV/src/com/udp/test/UDPClient.java
|
f42f72da74ec28ccbc8040144e9c083b66072dbe
|
[] |
no_license
|
achellies/Ktv_Luna
|
https://github.com/achellies/Ktv_Luna
|
42d1a3680d9ae3ce447f9c2b71d3a85df684c862
|
75bde04697164c206fdbe3542a7c56bafbd5ab62
|
refs/heads/master
| 2021-01-23T18:09:17.218000 | 2013-03-20T16:01:41 | 2013-03-20T16:01:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.udp.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
public UDPClient() {
// TODO Auto-generated constructor stub
}
/**
* ·¢ËÍÖ¸Áî²âÊÔº¯Êý
*
* @param portEtxtStr
* @param ipEtxtStr
* @param codeEtxtStr
*
* @throws IOException
*/
public String send_msg(String codeEtxtStr, String ipEtxtStr, int portEtxtStr)
throws IOException {
// TODO Auto-generated method stub
DatagramSocket client = new DatagramSocket();
String sendStr = codeEtxtStr;
byte[] sendBuf;
sendBuf = sendStr.getBytes();
InetAddress addr = InetAddress.getByName(ipEtxtStr);
int port = portEtxtStr;
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,
addr, port);
client.send(sendPacket);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
client.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0, recvPacket
.getLength());
client.close();
return recvStr;
}
}
|
WINDOWS-1252
|
Java
| 1,121 |
java
|
UDPClient.java
|
Java
|
[] | null |
[] |
package com.udp.test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClient {
public UDPClient() {
// TODO Auto-generated constructor stub
}
/**
* ·¢ËÍÖ¸Áî²âÊÔº¯Êý
*
* @param portEtxtStr
* @param ipEtxtStr
* @param codeEtxtStr
*
* @throws IOException
*/
public String send_msg(String codeEtxtStr, String ipEtxtStr, int portEtxtStr)
throws IOException {
// TODO Auto-generated method stub
DatagramSocket client = new DatagramSocket();
String sendStr = codeEtxtStr;
byte[] sendBuf;
sendBuf = sendStr.getBytes();
InetAddress addr = InetAddress.getByName(ipEtxtStr);
int port = portEtxtStr;
DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,
addr, port);
client.send(sendPacket);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
client.receive(recvPacket);
String recvStr = new String(recvPacket.getData(), 0, recvPacket
.getLength());
client.close();
return recvStr;
}
}
| 1,121 | 0.725792 | 0.721267 | 43 | 24.697674 | 20.10384 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.930233 | false | false |
5
|
4d43bbc7c8c0852e54d20b0d998cc7e4e7a36578
| 22,033,182,239,406 |
7010b9ed0cb7a5ea9363c7e0655bfd88c811afe7
|
/src/test/java/org/createyourevent/app/web/rest/ProductResourceIT.java
|
d4fd62136de67958445a91f17e6c11688f7c43e7
|
[] |
no_license
|
createyourevent/createyourevent
|
https://github.com/createyourevent/createyourevent
|
a855c46054754acd0c1c432fe138b60692391b7f
|
f106fbddd2766d4fcb46921c13ad5a7861995bd3
|
refs/heads/main
| 2023-07-11T18:26:45.087000 | 2023-06-04T14:40:19 | 2023-06-04T14:40:19 | 332,435,618 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.createyourevent.app.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.createyourevent.app.web.rest.TestUtil.sameInstant;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.createyourevent.app.IntegrationTest;
import org.createyourevent.app.domain.Product;
import org.createyourevent.app.domain.enumeration.OrderStatus;
import org.createyourevent.app.domain.enumeration.PriceType;
import org.createyourevent.app.domain.enumeration.ProductType;
import org.createyourevent.app.domain.enumeration.RentType;
import org.createyourevent.app.domain.enumeration.Unit;
import org.createyourevent.app.repository.ProductRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
/**
* Integration tests for the {@link ProductResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ProductResourceIT {
private static final String DEFAULT_TITLE = "AAAAAAAAAA";
private static final String UPDATED_TITLE = "BBBBBBBBBB";
private static final String DEFAULT_KEYWORDS = "AAAAAAAAAA";
private static final String UPDATED_KEYWORDS = "BBBBBBBBBB";
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final ZonedDateTime DEFAULT_DATE_ADDED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE_ADDED = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final ZonedDateTime DEFAULT_DATE_MODIFIED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE_MODIFIED = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final PriceType DEFAULT_PRICE_TYPE = PriceType.SELL;
private static final PriceType UPDATED_PRICE_TYPE = PriceType.RENT;
private static final RentType DEFAULT_RENT_TYPE = RentType.HOURLY;
private static final RentType UPDATED_RENT_TYPE = RentType.HALFDAY;
private static final Float DEFAULT_PRICE = 1F;
private static final Float UPDATED_PRICE = 2F;
private static final byte[] DEFAULT_PHOTO = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_CONTENT_TYPE = "image/png";
private static final byte[] DEFAULT_PHOTO_2 = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO_2 = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_2_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_2_CONTENT_TYPE = "image/png";
private static final byte[] DEFAULT_PHOTO_3 = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO_3 = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_3_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_3_CONTENT_TYPE = "image/png";
private static final String DEFAULT_YOUTUBE = "AAAAAAAAAA";
private static final String UPDATED_YOUTUBE = "BBBBBBBBBB";
private static final Boolean DEFAULT_ACTIVE = false;
private static final Boolean UPDATED_ACTIVE = true;
private static final Float DEFAULT_STOCK = 1F;
private static final Float UPDATED_STOCK = 2F;
private static final ProductType DEFAULT_PRODUCT_TYPE = ProductType.REAL_ESTATE;
private static final ProductType UPDATED_PRODUCT_TYPE = ProductType.FOOD;
private static final String DEFAULT_ITEM_NUMBER = "AAAAAAAAAA";
private static final String UPDATED_ITEM_NUMBER = "BBBBBBBBBB";
private static final OrderStatus DEFAULT_STATUS = OrderStatus.NEW;
private static final OrderStatus UPDATED_STATUS = OrderStatus.PROCESSING;
private static final Unit DEFAULT_UNIT = Unit.ITEM;
private static final Unit UPDATED_UNIT = Unit.GRAM;
private static final Float DEFAULT_AMOUNT = 1F;
private static final Float UPDATED_AMOUNT = 2F;
private static final String DEFAULT_MOTTO = "AAAAAAAAAA";
private static final String UPDATED_MOTTO = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/products";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ProductRepository productRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restProductMockMvc;
private Product product;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Product createEntity(EntityManager em) {
Product product = new Product()
.title(DEFAULT_TITLE)
.keywords(DEFAULT_KEYWORDS)
.description(DEFAULT_DESCRIPTION)
.dateAdded(DEFAULT_DATE_ADDED)
.dateModified(DEFAULT_DATE_MODIFIED)
.priceType(DEFAULT_PRICE_TYPE)
.rentType(DEFAULT_RENT_TYPE)
.price(DEFAULT_PRICE)
.photo(DEFAULT_PHOTO)
.photoContentType(DEFAULT_PHOTO_CONTENT_TYPE)
.photo2(DEFAULT_PHOTO_2)
.photo2ContentType(DEFAULT_PHOTO_2_CONTENT_TYPE)
.photo3(DEFAULT_PHOTO_3)
.photo3ContentType(DEFAULT_PHOTO_3_CONTENT_TYPE)
.youtube(DEFAULT_YOUTUBE)
.active(DEFAULT_ACTIVE)
.stock(DEFAULT_STOCK)
.productType(DEFAULT_PRODUCT_TYPE)
.itemNumber(DEFAULT_ITEM_NUMBER)
.status(DEFAULT_STATUS)
.unit(DEFAULT_UNIT)
.amount(DEFAULT_AMOUNT)
.motto(DEFAULT_MOTTO);
return product;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Product createUpdatedEntity(EntityManager em) {
Product product = new Product()
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
return product;
}
@BeforeEach
public void initTest() {
product = createEntity(em);
}
@Test
@Transactional
void createProduct() throws Exception {
int databaseSizeBeforeCreate = productRepository.findAll().size();
// Create the Product
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isCreated());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeCreate + 1);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(DEFAULT_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(DEFAULT_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(DEFAULT_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(DEFAULT_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(DEFAULT_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(DEFAULT_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(DEFAULT_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(DEFAULT_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(DEFAULT_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(DEFAULT_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(DEFAULT_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(DEFAULT_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(DEFAULT_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(DEFAULT_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(DEFAULT_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(DEFAULT_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(DEFAULT_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(DEFAULT_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(DEFAULT_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(DEFAULT_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(DEFAULT_MOTTO);
}
@Test
@Transactional
void createProductWithExistingId() throws Exception {
// Create the Product with an existing ID
product.setId(1L);
int databaseSizeBeforeCreate = productRepository.findAll().size();
// An entity with an existing ID cannot be created, so this API call must fail
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkTitleIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setTitle(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkPriceIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setPrice(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkStockIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setStock(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkUnitIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setUnit(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkMottoIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setMotto(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllProducts() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
// Get all the productList
restProductMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(product.getId().intValue())))
.andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE)))
.andExpect(jsonPath("$.[*].keywords").value(hasItem(DEFAULT_KEYWORDS)))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].dateAdded").value(hasItem(sameInstant(DEFAULT_DATE_ADDED))))
.andExpect(jsonPath("$.[*].dateModified").value(hasItem(sameInstant(DEFAULT_DATE_MODIFIED))))
.andExpect(jsonPath("$.[*].priceType").value(hasItem(DEFAULT_PRICE_TYPE.toString())))
.andExpect(jsonPath("$.[*].rentType").value(hasItem(DEFAULT_RENT_TYPE.toString())))
.andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue())))
.andExpect(jsonPath("$.[*].photoContentType").value(hasItem(DEFAULT_PHOTO_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO))))
.andExpect(jsonPath("$.[*].photo2ContentType").value(hasItem(DEFAULT_PHOTO_2_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo2").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO_2))))
.andExpect(jsonPath("$.[*].photo3ContentType").value(hasItem(DEFAULT_PHOTO_3_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo3").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO_3))))
.andExpect(jsonPath("$.[*].youtube").value(hasItem(DEFAULT_YOUTUBE)))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())))
.andExpect(jsonPath("$.[*].stock").value(hasItem(DEFAULT_STOCK.doubleValue())))
.andExpect(jsonPath("$.[*].productType").value(hasItem(DEFAULT_PRODUCT_TYPE.toString())))
.andExpect(jsonPath("$.[*].itemNumber").value(hasItem(DEFAULT_ITEM_NUMBER)))
.andExpect(jsonPath("$.[*].status").value(hasItem(DEFAULT_STATUS.toString())))
.andExpect(jsonPath("$.[*].unit").value(hasItem(DEFAULT_UNIT.toString())))
.andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.doubleValue())))
.andExpect(jsonPath("$.[*].motto").value(hasItem(DEFAULT_MOTTO)));
}
@Test
@Transactional
void getProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
// Get the product
restProductMockMvc
.perform(get(ENTITY_API_URL_ID, product.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(product.getId().intValue()))
.andExpect(jsonPath("$.title").value(DEFAULT_TITLE))
.andExpect(jsonPath("$.keywords").value(DEFAULT_KEYWORDS))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.dateAdded").value(sameInstant(DEFAULT_DATE_ADDED)))
.andExpect(jsonPath("$.dateModified").value(sameInstant(DEFAULT_DATE_MODIFIED)))
.andExpect(jsonPath("$.priceType").value(DEFAULT_PRICE_TYPE.toString()))
.andExpect(jsonPath("$.rentType").value(DEFAULT_RENT_TYPE.toString()))
.andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue()))
.andExpect(jsonPath("$.photoContentType").value(DEFAULT_PHOTO_CONTENT_TYPE))
.andExpect(jsonPath("$.photo").value(Base64Utils.encodeToString(DEFAULT_PHOTO)))
.andExpect(jsonPath("$.photo2ContentType").value(DEFAULT_PHOTO_2_CONTENT_TYPE))
.andExpect(jsonPath("$.photo2").value(Base64Utils.encodeToString(DEFAULT_PHOTO_2)))
.andExpect(jsonPath("$.photo3ContentType").value(DEFAULT_PHOTO_3_CONTENT_TYPE))
.andExpect(jsonPath("$.photo3").value(Base64Utils.encodeToString(DEFAULT_PHOTO_3)))
.andExpect(jsonPath("$.youtube").value(DEFAULT_YOUTUBE))
.andExpect(jsonPath("$.active").value(DEFAULT_ACTIVE.booleanValue()))
.andExpect(jsonPath("$.stock").value(DEFAULT_STOCK.doubleValue()))
.andExpect(jsonPath("$.productType").value(DEFAULT_PRODUCT_TYPE.toString()))
.andExpect(jsonPath("$.itemNumber").value(DEFAULT_ITEM_NUMBER))
.andExpect(jsonPath("$.status").value(DEFAULT_STATUS.toString()))
.andExpect(jsonPath("$.unit").value(DEFAULT_UNIT.toString()))
.andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT.doubleValue()))
.andExpect(jsonPath("$.motto").value(DEFAULT_MOTTO));
}
@Test
@Transactional
void getNonExistingProduct() throws Exception {
// Get the product
restProductMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putNewProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product
Product updatedProduct = productRepository.findById(product.getId()).get();
// Disconnect from session so that the updates on updatedProduct are not directly saved in db
em.detach(updatedProduct);
updatedProduct
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, updatedProduct.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(UPDATED_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(UPDATED_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(UPDATED_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(UPDATED_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(UPDATED_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(UPDATED_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(UPDATED_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(UPDATED_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(UPDATED_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(UPDATED_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(UPDATED_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(UPDATED_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void putNonExistingProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, product.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, count.incrementAndGet())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateProductWithPatch() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product using partial update
Product partialUpdatedProduct = new Product();
partialUpdatedProduct.setId(product.getId());
partialUpdatedProduct
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.stock(UPDATED_STOCK)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProduct.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(DEFAULT_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(DEFAULT_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(DEFAULT_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(DEFAULT_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(DEFAULT_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(DEFAULT_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(DEFAULT_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(DEFAULT_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(DEFAULT_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(DEFAULT_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(DEFAULT_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(DEFAULT_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(DEFAULT_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void fullUpdateProductWithPatch() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product using partial update
Product partialUpdatedProduct = new Product();
partialUpdatedProduct.setId(product.getId());
partialUpdatedProduct
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProduct.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(UPDATED_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(UPDATED_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(UPDATED_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(UPDATED_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(UPDATED_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(UPDATED_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(UPDATED_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(UPDATED_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(UPDATED_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(UPDATED_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(UPDATED_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(UPDATED_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void patchNonExistingProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, product.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, count.incrementAndGet())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL)
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeDelete = productRepository.findAll().size();
// Delete the product
restProductMockMvc
.perform(delete(ENTITY_API_URL_ID, product.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeDelete - 1);
}
}
|
UTF-8
|
Java
| 36,908 |
java
|
ProductResourceIT.java
|
Java
|
[] | null |
[] |
package org.createyourevent.app.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.createyourevent.app.web.rest.TestUtil.sameInstant;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.createyourevent.app.IntegrationTest;
import org.createyourevent.app.domain.Product;
import org.createyourevent.app.domain.enumeration.OrderStatus;
import org.createyourevent.app.domain.enumeration.PriceType;
import org.createyourevent.app.domain.enumeration.ProductType;
import org.createyourevent.app.domain.enumeration.RentType;
import org.createyourevent.app.domain.enumeration.Unit;
import org.createyourevent.app.repository.ProductRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
/**
* Integration tests for the {@link ProductResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ProductResourceIT {
private static final String DEFAULT_TITLE = "AAAAAAAAAA";
private static final String UPDATED_TITLE = "BBBBBBBBBB";
private static final String DEFAULT_KEYWORDS = "AAAAAAAAAA";
private static final String UPDATED_KEYWORDS = "BBBBBBBBBB";
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final ZonedDateTime DEFAULT_DATE_ADDED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE_ADDED = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final ZonedDateTime DEFAULT_DATE_MODIFIED = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE_MODIFIED = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final PriceType DEFAULT_PRICE_TYPE = PriceType.SELL;
private static final PriceType UPDATED_PRICE_TYPE = PriceType.RENT;
private static final RentType DEFAULT_RENT_TYPE = RentType.HOURLY;
private static final RentType UPDATED_RENT_TYPE = RentType.HALFDAY;
private static final Float DEFAULT_PRICE = 1F;
private static final Float UPDATED_PRICE = 2F;
private static final byte[] DEFAULT_PHOTO = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_CONTENT_TYPE = "image/png";
private static final byte[] DEFAULT_PHOTO_2 = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO_2 = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_2_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_2_CONTENT_TYPE = "image/png";
private static final byte[] DEFAULT_PHOTO_3 = TestUtil.createByteArray(1, "0");
private static final byte[] UPDATED_PHOTO_3 = TestUtil.createByteArray(1, "1");
private static final String DEFAULT_PHOTO_3_CONTENT_TYPE = "image/jpg";
private static final String UPDATED_PHOTO_3_CONTENT_TYPE = "image/png";
private static final String DEFAULT_YOUTUBE = "AAAAAAAAAA";
private static final String UPDATED_YOUTUBE = "BBBBBBBBBB";
private static final Boolean DEFAULT_ACTIVE = false;
private static final Boolean UPDATED_ACTIVE = true;
private static final Float DEFAULT_STOCK = 1F;
private static final Float UPDATED_STOCK = 2F;
private static final ProductType DEFAULT_PRODUCT_TYPE = ProductType.REAL_ESTATE;
private static final ProductType UPDATED_PRODUCT_TYPE = ProductType.FOOD;
private static final String DEFAULT_ITEM_NUMBER = "AAAAAAAAAA";
private static final String UPDATED_ITEM_NUMBER = "BBBBBBBBBB";
private static final OrderStatus DEFAULT_STATUS = OrderStatus.NEW;
private static final OrderStatus UPDATED_STATUS = OrderStatus.PROCESSING;
private static final Unit DEFAULT_UNIT = Unit.ITEM;
private static final Unit UPDATED_UNIT = Unit.GRAM;
private static final Float DEFAULT_AMOUNT = 1F;
private static final Float UPDATED_AMOUNT = 2F;
private static final String DEFAULT_MOTTO = "AAAAAAAAAA";
private static final String UPDATED_MOTTO = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/products";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ProductRepository productRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restProductMockMvc;
private Product product;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Product createEntity(EntityManager em) {
Product product = new Product()
.title(DEFAULT_TITLE)
.keywords(DEFAULT_KEYWORDS)
.description(DEFAULT_DESCRIPTION)
.dateAdded(DEFAULT_DATE_ADDED)
.dateModified(DEFAULT_DATE_MODIFIED)
.priceType(DEFAULT_PRICE_TYPE)
.rentType(DEFAULT_RENT_TYPE)
.price(DEFAULT_PRICE)
.photo(DEFAULT_PHOTO)
.photoContentType(DEFAULT_PHOTO_CONTENT_TYPE)
.photo2(DEFAULT_PHOTO_2)
.photo2ContentType(DEFAULT_PHOTO_2_CONTENT_TYPE)
.photo3(DEFAULT_PHOTO_3)
.photo3ContentType(DEFAULT_PHOTO_3_CONTENT_TYPE)
.youtube(DEFAULT_YOUTUBE)
.active(DEFAULT_ACTIVE)
.stock(DEFAULT_STOCK)
.productType(DEFAULT_PRODUCT_TYPE)
.itemNumber(DEFAULT_ITEM_NUMBER)
.status(DEFAULT_STATUS)
.unit(DEFAULT_UNIT)
.amount(DEFAULT_AMOUNT)
.motto(DEFAULT_MOTTO);
return product;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Product createUpdatedEntity(EntityManager em) {
Product product = new Product()
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
return product;
}
@BeforeEach
public void initTest() {
product = createEntity(em);
}
@Test
@Transactional
void createProduct() throws Exception {
int databaseSizeBeforeCreate = productRepository.findAll().size();
// Create the Product
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isCreated());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeCreate + 1);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(DEFAULT_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(DEFAULT_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(DEFAULT_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(DEFAULT_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(DEFAULT_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(DEFAULT_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(DEFAULT_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(DEFAULT_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(DEFAULT_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(DEFAULT_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(DEFAULT_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(DEFAULT_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(DEFAULT_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(DEFAULT_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(DEFAULT_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(DEFAULT_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(DEFAULT_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(DEFAULT_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(DEFAULT_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(DEFAULT_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(DEFAULT_MOTTO);
}
@Test
@Transactional
void createProductWithExistingId() throws Exception {
// Create the Product with an existing ID
product.setId(1L);
int databaseSizeBeforeCreate = productRepository.findAll().size();
// An entity with an existing ID cannot be created, so this API call must fail
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkTitleIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setTitle(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkPriceIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setPrice(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkStockIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setStock(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkUnitIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setUnit(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkMottoIsRequired() throws Exception {
int databaseSizeBeforeTest = productRepository.findAll().size();
// set the field null
product.setMotto(null);
// Create the Product, which fails.
restProductMockMvc
.perform(
post(ENTITY_API_URL)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllProducts() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
// Get all the productList
restProductMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(product.getId().intValue())))
.andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE)))
.andExpect(jsonPath("$.[*].keywords").value(hasItem(DEFAULT_KEYWORDS)))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].dateAdded").value(hasItem(sameInstant(DEFAULT_DATE_ADDED))))
.andExpect(jsonPath("$.[*].dateModified").value(hasItem(sameInstant(DEFAULT_DATE_MODIFIED))))
.andExpect(jsonPath("$.[*].priceType").value(hasItem(DEFAULT_PRICE_TYPE.toString())))
.andExpect(jsonPath("$.[*].rentType").value(hasItem(DEFAULT_RENT_TYPE.toString())))
.andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue())))
.andExpect(jsonPath("$.[*].photoContentType").value(hasItem(DEFAULT_PHOTO_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO))))
.andExpect(jsonPath("$.[*].photo2ContentType").value(hasItem(DEFAULT_PHOTO_2_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo2").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO_2))))
.andExpect(jsonPath("$.[*].photo3ContentType").value(hasItem(DEFAULT_PHOTO_3_CONTENT_TYPE)))
.andExpect(jsonPath("$.[*].photo3").value(hasItem(Base64Utils.encodeToString(DEFAULT_PHOTO_3))))
.andExpect(jsonPath("$.[*].youtube").value(hasItem(DEFAULT_YOUTUBE)))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())))
.andExpect(jsonPath("$.[*].stock").value(hasItem(DEFAULT_STOCK.doubleValue())))
.andExpect(jsonPath("$.[*].productType").value(hasItem(DEFAULT_PRODUCT_TYPE.toString())))
.andExpect(jsonPath("$.[*].itemNumber").value(hasItem(DEFAULT_ITEM_NUMBER)))
.andExpect(jsonPath("$.[*].status").value(hasItem(DEFAULT_STATUS.toString())))
.andExpect(jsonPath("$.[*].unit").value(hasItem(DEFAULT_UNIT.toString())))
.andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.doubleValue())))
.andExpect(jsonPath("$.[*].motto").value(hasItem(DEFAULT_MOTTO)));
}
@Test
@Transactional
void getProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
// Get the product
restProductMockMvc
.perform(get(ENTITY_API_URL_ID, product.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(product.getId().intValue()))
.andExpect(jsonPath("$.title").value(DEFAULT_TITLE))
.andExpect(jsonPath("$.keywords").value(DEFAULT_KEYWORDS))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.dateAdded").value(sameInstant(DEFAULT_DATE_ADDED)))
.andExpect(jsonPath("$.dateModified").value(sameInstant(DEFAULT_DATE_MODIFIED)))
.andExpect(jsonPath("$.priceType").value(DEFAULT_PRICE_TYPE.toString()))
.andExpect(jsonPath("$.rentType").value(DEFAULT_RENT_TYPE.toString()))
.andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue()))
.andExpect(jsonPath("$.photoContentType").value(DEFAULT_PHOTO_CONTENT_TYPE))
.andExpect(jsonPath("$.photo").value(Base64Utils.encodeToString(DEFAULT_PHOTO)))
.andExpect(jsonPath("$.photo2ContentType").value(DEFAULT_PHOTO_2_CONTENT_TYPE))
.andExpect(jsonPath("$.photo2").value(Base64Utils.encodeToString(DEFAULT_PHOTO_2)))
.andExpect(jsonPath("$.photo3ContentType").value(DEFAULT_PHOTO_3_CONTENT_TYPE))
.andExpect(jsonPath("$.photo3").value(Base64Utils.encodeToString(DEFAULT_PHOTO_3)))
.andExpect(jsonPath("$.youtube").value(DEFAULT_YOUTUBE))
.andExpect(jsonPath("$.active").value(DEFAULT_ACTIVE.booleanValue()))
.andExpect(jsonPath("$.stock").value(DEFAULT_STOCK.doubleValue()))
.andExpect(jsonPath("$.productType").value(DEFAULT_PRODUCT_TYPE.toString()))
.andExpect(jsonPath("$.itemNumber").value(DEFAULT_ITEM_NUMBER))
.andExpect(jsonPath("$.status").value(DEFAULT_STATUS.toString()))
.andExpect(jsonPath("$.unit").value(DEFAULT_UNIT.toString()))
.andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT.doubleValue()))
.andExpect(jsonPath("$.motto").value(DEFAULT_MOTTO));
}
@Test
@Transactional
void getNonExistingProduct() throws Exception {
// Get the product
restProductMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putNewProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product
Product updatedProduct = productRepository.findById(product.getId()).get();
// Disconnect from session so that the updates on updatedProduct are not directly saved in db
em.detach(updatedProduct);
updatedProduct
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, updatedProduct.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(updatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(UPDATED_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(UPDATED_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(UPDATED_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(UPDATED_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(UPDATED_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(UPDATED_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(UPDATED_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(UPDATED_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(UPDATED_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(UPDATED_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(UPDATED_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(UPDATED_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void putNonExistingProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, product.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL_ID, count.incrementAndGet())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateProductWithPatch() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product using partial update
Product partialUpdatedProduct = new Product();
partialUpdatedProduct.setId(product.getId());
partialUpdatedProduct
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.stock(UPDATED_STOCK)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProduct.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(DEFAULT_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(DEFAULT_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(DEFAULT_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(DEFAULT_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(DEFAULT_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(DEFAULT_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(DEFAULT_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(DEFAULT_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(DEFAULT_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(DEFAULT_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(DEFAULT_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(DEFAULT_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(DEFAULT_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(DEFAULT_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void fullUpdateProductWithPatch() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeUpdate = productRepository.findAll().size();
// Update the product using partial update
Product partialUpdatedProduct = new Product();
partialUpdatedProduct.setId(product.getId());
partialUpdatedProduct
.title(UPDATED_TITLE)
.keywords(UPDATED_KEYWORDS)
.description(UPDATED_DESCRIPTION)
.dateAdded(UPDATED_DATE_ADDED)
.dateModified(UPDATED_DATE_MODIFIED)
.priceType(UPDATED_PRICE_TYPE)
.rentType(UPDATED_RENT_TYPE)
.price(UPDATED_PRICE)
.photo(UPDATED_PHOTO)
.photoContentType(UPDATED_PHOTO_CONTENT_TYPE)
.photo2(UPDATED_PHOTO_2)
.photo2ContentType(UPDATED_PHOTO_2_CONTENT_TYPE)
.photo3(UPDATED_PHOTO_3)
.photo3ContentType(UPDATED_PHOTO_3_CONTENT_TYPE)
.youtube(UPDATED_YOUTUBE)
.active(UPDATED_ACTIVE)
.stock(UPDATED_STOCK)
.productType(UPDATED_PRODUCT_TYPE)
.itemNumber(UPDATED_ITEM_NUMBER)
.status(UPDATED_STATUS)
.unit(UPDATED_UNIT)
.amount(UPDATED_AMOUNT)
.motto(UPDATED_MOTTO);
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedProduct.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedProduct))
)
.andExpect(status().isOk());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
Product testProduct = productList.get(productList.size() - 1);
assertThat(testProduct.getTitle()).isEqualTo(UPDATED_TITLE);
assertThat(testProduct.getKeywords()).isEqualTo(UPDATED_KEYWORDS);
assertThat(testProduct.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testProduct.getDateAdded()).isEqualTo(UPDATED_DATE_ADDED);
assertThat(testProduct.getDateModified()).isEqualTo(UPDATED_DATE_MODIFIED);
assertThat(testProduct.getPriceType()).isEqualTo(UPDATED_PRICE_TYPE);
assertThat(testProduct.getRentType()).isEqualTo(UPDATED_RENT_TYPE);
assertThat(testProduct.getPrice()).isEqualTo(UPDATED_PRICE);
assertThat(testProduct.getPhoto()).isEqualTo(UPDATED_PHOTO);
assertThat(testProduct.getPhotoContentType()).isEqualTo(UPDATED_PHOTO_CONTENT_TYPE);
assertThat(testProduct.getPhoto2()).isEqualTo(UPDATED_PHOTO_2);
assertThat(testProduct.getPhoto2ContentType()).isEqualTo(UPDATED_PHOTO_2_CONTENT_TYPE);
assertThat(testProduct.getPhoto3()).isEqualTo(UPDATED_PHOTO_3);
assertThat(testProduct.getPhoto3ContentType()).isEqualTo(UPDATED_PHOTO_3_CONTENT_TYPE);
assertThat(testProduct.getYoutube()).isEqualTo(UPDATED_YOUTUBE);
assertThat(testProduct.getActive()).isEqualTo(UPDATED_ACTIVE);
assertThat(testProduct.getStock()).isEqualTo(UPDATED_STOCK);
assertThat(testProduct.getProductType()).isEqualTo(UPDATED_PRODUCT_TYPE);
assertThat(testProduct.getItemNumber()).isEqualTo(UPDATED_ITEM_NUMBER);
assertThat(testProduct.getStatus()).isEqualTo(UPDATED_STATUS);
assertThat(testProduct.getUnit()).isEqualTo(UPDATED_UNIT);
assertThat(testProduct.getAmount()).isEqualTo(UPDATED_AMOUNT);
assertThat(testProduct.getMotto()).isEqualTo(UPDATED_MOTTO);
}
@Test
@Transactional
void patchNonExistingProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, product.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL_ID, count.incrementAndGet())
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isBadRequest());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamProduct() throws Exception {
int databaseSizeBeforeUpdate = productRepository.findAll().size();
product.setId(count.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restProductMockMvc
.perform(
patch(ENTITY_API_URL)
.with(csrf())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(product))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Product in the database
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteProduct() throws Exception {
// Initialize the database
productRepository.saveAndFlush(product);
int databaseSizeBeforeDelete = productRepository.findAll().size();
// Delete the product
restProductMockMvc
.perform(delete(ENTITY_API_URL_ID, product.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Product> productList = productRepository.findAll();
assertThat(productList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| 36,908 | 0.666007 | 0.662323 | 807 | 44.734821 | 29.537643 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.39653 | false | false |
5
|
ade126cf4416e50b6eefc34f180c9cf987534de2
| 13,254,269,087,954 |
c67412a747669b3bf8d56cfc1b38b5004b8f0bc6
|
/goods/src/main/java/com/yesmywine/goods/service/Impl/PropServiceImpl.java
|
ddbdbb1e9b847d06b6416b3701a5d085232a32b2
|
[] |
no_license
|
qiango/yesmywine
|
https://github.com/qiango/yesmywine
|
56e8b25565afdc7a69e66de416f1376bdfa26aac
|
b1b46c4f2f33b858e0dca68273a4fc03f2e46665
|
refs/heads/master
| 2021-10-20T03:56:12.871000 | 2019-02-25T15:32:05 | 2019-02-25T15:32:05 | 114,221,199 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yesmywine.goods.service.Impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.yesmywine.base.record.biz.BaseServiceImpl;
import com.yesmywine.goods.bean.*;
import com.yesmywine.goods.dao.*;
import com.yesmywine.goods.entity.CategoryProperty;
import com.yesmywine.goods.entityProperties.*;
import com.yesmywine.goods.entityProperties.Properties;
import com.yesmywine.goods.service.CommonService;
import com.yesmywine.goods.service.ProService;
import com.yesmywine.httpclient.bean.HttpBean;
import com.yesmywine.httpclient.bean.RequestMethod;
import com.yesmywine.util.basic.*;
import com.yesmywine.util.basic.Dictionary;
import com.yesmywine.util.error.yesmywineException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.transaction.Transactional;
import java.util.*;
/**
* Created by hz on 1/6/17.
*/
@Service
@Transactional
public class PropServiceImpl extends BaseServiceImpl<com.yesmywine.goods.entityProperties.Properties, Integer> implements ProService {
@Autowired
private PropertiesDao propertiesDao;
@Autowired
private ProperValueDao properValueDao;
// @Autowired
// private PropGoodsDao propGoodsDao;
@Autowired
private GoodsDao goodsRepository;
@Autowired
private CategoryPropertyDao categoryPropertyDao;
@Autowired
private SkuDao skuDao;
@Autowired
private SpuDao spuDao;
@Autowired
private CommonService<com.yesmywine.goods.entityProperties.Properties> commonService;
@Autowired
private CommonService<PropertiesValue> commonServiceValue;
@Autowired
private CategoryDao categoryDao;
public String addPrpo(Map<String, String> parm) throws yesmywineException { //新增属性
// Integer categoryId = Integer.parseInt(parm.get("categoryId"));
String isSku = parm.get("isSku"); //0是
String canSearch = parm.get("canSearch");//0是
String cnName = parm.get("cnName");
String code = parm.get("code");
if(null!=propertiesDao.findByCode(code)){
ValueUtil.isError("该编码已存在");
}
if(null!=propertiesDao.findByCnName(cnName)){
ValueUtil.isError("该属性已存在");
}
com.yesmywine.goods.entityProperties.Properties properties = new com.yesmywine.goods.entityProperties.Properties();
properties.setCnName(cnName);
properties.setCode(parm.get("code"));
// properties.setEnName(enName);
// properties.setCategory(categoryDao.findOne(categoryId));
properties.setIsUse(IsUse.no);
if (isSku.equals("yes")) {
properties.setIsSku(IsSku.yes);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else
properties.setCanSearch(CanSearch.yes);
properties.setEntryMode(EntryMode.nullall);
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
// Integer propertiesId = propertiesDao.findId();
// if(ValueUtil.notEmpity(parm.get("valueJson"))){
// String valueJson= parm.get("valueJson");
// JsonParser jsonParser = new JsonParser();
// JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
// for (int i = 0; i < arr.size(); i++) {
// PropertiesValue propertiesValue = new PropertiesValue();
//// propertiesValue.setCnName(cnName);
// propertiesValue.setPropertiesId(propertiesId);
// String value = arr.get(i).getAsJsonObject().get("value").getAsString();
// String code = arr.get(i).getAsJsonObject().get("code").getAsString();
// propertiesValue.setCode(code);
// propertiesValue.setCnValue(value);
// properValueDao.save(propertiesValue);
// }
// }
// return "success";
} else
properties.setIsSku(IsSku.no);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else {
properties.setCanSearch(CanSearch.yes);
}
String entryMode = parm.get("entryMode");
if(entryMode.equals("manual")){
properties.setEntryMode(EntryMode.manual);
try {
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
}catch (Exception e){
return "该属性已存在";
}
}else {
properties.setEntryMode(EntryMode.lists);
propertiesDao.save(properties);
parm.put("id", properties.getId().toString());
if (!this.commonService.synchronous(parm, Dictionary.MALL_HOST + "/goods/properties/synchronous", 0)) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
}
}
@Override
public Map<String, String> addPrpoByImport(Map<String, String> parm) throws yesmywineException {
Map<String, String> reMap = new HashMap<>();
String isSku = parm.get("isSku"); //0是
String canSearch = parm.get("canSearch");//0是
String cnName = parm.get("cnName");
if(null!=propertiesDao.findByCnName(cnName)){
reMap.put("erro", "该属性已存在");
return reMap;
}
// String enName = parm.get("enName");
// Category category=new Category();
// category.setId(categoryId);
// if(null!=propertiesDao.findByCategoryAndCnName(category,cnName)){
// return "该属性在此分类下已有,不可新建";
// }
com.yesmywine.goods.entityProperties.Properties properties = new com.yesmywine.goods.entityProperties.Properties();
properties.setCnName(cnName);
// properties.setEnName(enName);
// properties.setCategory(categoryDao.findOne(categoryId));
properties.setIsUse(IsUse.no);
if (isSku.equals("yes")) {
properties.setIsSku(IsSku.yes);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else
properties.setCanSearch(CanSearch.yes);
properties.setEntryMode(EntryMode.nullall);
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(ValueUtil.isEmpity(parm.get("valueJson"))){
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}
Integer propertiesId = propertiesDao.findId();
if(ValueUtil.notEmpity(parm.get("valueJson"))){
String valueJson= parm.get("valueJson");
JsonParser jsonParser = new JsonParser();
JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
for (int i = 0; i < arr.size(); i++) {
PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setCnName(cnName);
propertiesValue.setPropertiesId(propertiesId);
String value = arr.get(i).getAsJsonObject().get("value").getAsString();
String code = arr.get(i).getAsJsonObject().get("code").getAsString();
propertiesValue.setCode(code);
propertiesValue.setCnValue(value);
properValueDao.save(propertiesValue);
}
}
reMap.put("success", properties.getId().toString());
return reMap;
} else
properties.setIsSku(IsSku.no);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else {
properties.setCanSearch(CanSearch.yes);
}
String entryMode = parm.get("entryMode");
if(entryMode.equals("manual")){
properties.setEntryMode(EntryMode.manual);
try {
propertiesDao.save(properties);
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}catch (Exception e){
reMap.put("erro", "该属性已存在");
return reMap;
}
}else {
properties.setEntryMode(EntryMode.lists);
propertiesDao.save(properties);
Integer propertiesId = propertiesDao.findId();
if(ValueUtil.notEmpity(parm.get("valueJson"))) {
String valueJson = parm.get("valueJson");
String[] arr = valueJson.split(",");
for (int i = 0; i < arr.length; i++) {
PropertiesValue propertiesValue = new PropertiesValue();
propertiesValue.setPropertiesId(propertiesId);
// propertiesValue.setCnName(cnName);
propertiesValue.setCnValue(arr[i]);
properValueDao.save(propertiesValue);
}
}
}
propertiesDao.save(properties);
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}
public String updateProp(Integer id,String canSearch,String cnName,String isSku,String entryMode) throws yesmywineException {
com.yesmywine.goods.entityProperties.Properties entity = propertiesDao.findOne(id);
Properties byCnName = propertiesDao.findByCnName(cnName);
if(null!=byCnName&&byCnName.getId()!=(int)id){
ValueUtil.isError("该属性名已存在");
}
if (entity.getIsUse() == IsUse.no) {
entity.setCnName(cnName);
if (canSearch.equals("yes")) {
entity.setCanSearch(CanSearch.yes);
} else {
entity.setCanSearch(CanSearch.no);
}
if (isSku.equals("yes")) {
entity.setIsSku(IsSku.yes);
entity.setEntryMode(EntryMode.nullall);
} else if (entryMode.equals("manual")) { //手动
entity.setIsSku(IsSku.no);
entity.setEntryMode(EntryMode.manual);
} else {
entity.setIsSku(IsSku.no);
entity.setEntryMode(EntryMode.lists);
}
propertiesDao.save(entity);
Map<String, String> map = new HashMap<>();
map.put("id", entity.getId().toString());
if(!this.commonService.synchronous(entity, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 1, map)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
} else if (canSearch.equals("yes")) {
entity.setCanSearch(CanSearch.yes);
} else {
entity.setCanSearch(CanSearch.no);
}
entity.setCnName(cnName);
propertiesDao.save(entity);
Map<String, String> map = new HashMap<>();
map.put("id", entity.getId().toString());
// map.put("categoryId", categoryId.toString());
if(!this.commonService.synchronous(entity, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 1, map)) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
// if (valueJson == null) {
// return "success";
// } else if (entity.getIsSku() == IsSku.yes) {
// JsonParser jsonParser = new JsonParser();
// JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
// for (int i = 0; i < arr.size(); i++) {
// String value = arr.get(i).getAsJsonObject().get("value").getAsString();
// String code = arr.get(i).getAsJsonObject().get("code").getAsString();
// List<PropertiesValue> p=properValueDao.findByCnValueAndPropertiesId(value, id);
// if (0==p.size()) {
// PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setCnName(cnName);
// propertiesValue.setPropertiesId(id);
// propertiesValue.setCode(code);
// propertiesValue.setCnValue(value);
// Map<String, String> map1 = new HashMap<>();
// map1.put("id", propertiesValue.getId().toString());
//// map.put("categoryId", categoryId.toString());
// if(this.commonServiceValue.synchronous(propertiesValue, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1, map1)){
// properValueDao.save(propertiesValue);
// }
// return "同步失败";
// }else {
// return "该属性下属性值已存在";
// }
// }
// } else {
// String[] arr = valueJson.split(",");
// for (int i = 0; i < arr.length; i++) {
// List<PropertiesValue> propertiesValue1=properValueDao.findByCnValueAndPropertiesId(arr[i],id);
// if (0 == propertiesValue1.size()){
// PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setPropertiesId(id);
// propertiesValue.setCnName(cnName);
// propertiesValue.setCnValue(arr[i]);
// Map<String, String> map1 = new HashMap<>();
// map1.put("id", propertiesValue.getId().toString());
//// map.put("categoryId", categoryId.toString());
// if(this.commonServiceValue.synchronous(propertiesValue, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1, map1)){
// properValueDao.save(propertiesValue);
// }
// return "同步失败";
// }else{
// return "该属性下属性值已经存在";
// }
// }
// }
return "success";
// }
// return "同步失败";
}
public String updateAdd(Integer propId, String code, String value){
PropertiesValue propertiesValue = new PropertiesValue();
propertiesValue.setCnValue(value);
propertiesValue.setCode(code);
propertiesValue.setPropertiesId(propId);
properValueDao.save(propertiesValue);
return "success";
}
public String deleteProp(Integer propId) throws yesmywineException {
List<CategoryProperty> byPropertyId = categoryPropertyDao.findByPropertyId(propId);
if(byPropertyId.size()!=0){
ValueUtil.isError("该属性被用,不可删除");
}
com.yesmywine.goods.entityProperties.Properties properties = propertiesDao.findOne(propId);
propertiesDao.delete(properties);
if(!this.commonService.synchronous(properties, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 2)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
List<PropertiesValue> propList=properValueDao.findByPropertiesId(propId);
properValueDao.delete(propList);
return "success";
}
@Override
public com.yesmywine.goods.entityProperties.Properties findByCnName(String cnName) {
return this.propertiesDao.findByCnName(cnName);
}
// @Override
// public String propCanShow(Integer propId) throws yesmywineException {
// com.yesmywine.goods.entityProperties.Properties properties=propertiesDao.findOne(propId);
// properties.setCanShow(!properties.isCanShow());
// propertiesDao.save(properties);
// if(!this.commonService.synchronous(properties, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1)) {
// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
// return "同步失败";
// }
// return "success";
// }
// public Map<String, List<String>> getProperByCategory(Integer categoryId) { //通过分类获取可查询的属性和值(前台用)
// Category category=new Category();
// category.setId(categoryId);
// List<Properties> list = propertiesDao.findByCategoryAndCanSearch(category,CanSearch.yes);
// Map<String, List<String>> properyName = new HashMap<>();
// for (int i = 0; i < list.size(); i++) {
// List<PropertiesValue> listValue = properValueDao.findByPropertiesId(list.get(i).getId());
// String name = propertiesDao.findOne(list.get(i).getId()).getCnName();
// if (null == properyName.get(name)) {
// properyName.put(name, new ArrayList<>());
// }
// for (int j = 0; j < listValue.size(); j++) {
// String cnValue = listValue.get(j).getCnValue();
// properyName.get(name).add(cnValue);
// }
// }
// return properyName;
// }
// public Object getMethods(Integer categoryId) { //查出该分类下的属性值的组合
// List<Integer> properId = propertiesDao.findIdByCategoryId(categoryId);
// List<PropGoods> propGoods = new ArrayList<>();
// for (int j = 0; j < properId.size(); j++) {
// List<PropertiesValue> listValue = properValueDao.findByPropertiesId(properId.get(j));
// listValue.forEach(k -> {
// List<PropGoods> prop = propGoodsDao.findByPropValueId(String.valueOf(k.getId()));
// prop.forEach(l -> {
// propGoods.add(l);
// });
// });
// }
// List<Map<String, Object>> showOut = new ArrayList<>();
// Map<Integer, Map<String, Object>> goodsProperties = new HashMap<>();
// for (int i = 0; i < propGoods.size(); i++) {
// PropGoods tempPropGoods = propGoods.get(i);
// if (null == goodsProperties.get(tempPropGoods.getGoodsId())) {
// goodsProperties.put(tempPropGoods.getGoodsId(), new HashMap<>());
// goodsProperties.get(tempPropGoods.getGoodsId()).put("goodsId", tempPropGoods.getGoodsId());
// }
// goodsProperties.get(tempPropGoods.getGoodsId()).put(tempPropGoods.getCnName(), tempPropGoods.getPropValueId());
// }
// goodsProperties.forEach((k, v) -> {
// showOut.add(v);
// });
//
// return showOut;
// }
// public Map[] getGeneralProp(Integer categoryId) { //通过分类属性及部分属性的值
// Category category=new Category();
// category.setId(categoryId);
// List<Properties> propties = propertiesDao.findByCategoryAndDeleteEnum(category,DeleteEnum.NOT_DELETE);
// Map[] map = new HashMap[propties.size()];
// for(int i=0;i< propties.size(); i++){
// Map<String, Object> prop = new HashMap<>();
// prop.put("value", propties.get(i).getId().toString());
// String cnName = propties.get(i).getCnName();
// prop.put("label", cnName);
// List<PropertiesValue> values = properValueDao.findByPropertiesId(propties.get(i).getId());
// Map[] map2 = new HashMap[values.size()];
// for(int j=0;j< values.size(); j++){
// Map<String, String> value = new HashMap<>();
// value.put("value", values.get(j).getId().toString());
// String cnValue = values.get(j).getCnValue();
// value.put("label", cnValue);
// map2[j] = value;
// }
// prop.put("child", map2);
// map[i]= prop;
// }
// return map;
// }
public String getRepertory(String skuId) { //查看库存
HttpBean httpRequest = new HttpBean("http://88.88.88.211:8191/inventory/goodsInventory" + "/" + skuId, RequestMethod.get);
httpRequest.run();
String amount = httpRequest.getResponseContent();
return amount;
}
}
|
UTF-8
|
Java
| 22,157 |
java
|
PropServiceImpl.java
|
Java
|
[
{
"context": "nsactional;\nimport java.util.*;\n\n/**\n * Created by hz on 1/6/17.\n */\n@Service\n@Transactional\npublic cla",
"end": 988,
"score": 0.9995408058166504,
"start": 986,
"tag": "USERNAME",
"value": "hz"
},
{
"context": " HttpBean httpRequest = new HttpBean(\"http://88.88.88.211:8191/inventory/goodsInventory\" + \"/\" + skuId, Req",
"end": 21588,
"score": 0.9864530563354492,
"start": 21576,
"tag": "IP_ADDRESS",
"value": "88.88.88.211"
}
] | null |
[] |
package com.yesmywine.goods.service.Impl;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.yesmywine.base.record.biz.BaseServiceImpl;
import com.yesmywine.goods.bean.*;
import com.yesmywine.goods.dao.*;
import com.yesmywine.goods.entity.CategoryProperty;
import com.yesmywine.goods.entityProperties.*;
import com.yesmywine.goods.entityProperties.Properties;
import com.yesmywine.goods.service.CommonService;
import com.yesmywine.goods.service.ProService;
import com.yesmywine.httpclient.bean.HttpBean;
import com.yesmywine.httpclient.bean.RequestMethod;
import com.yesmywine.util.basic.*;
import com.yesmywine.util.basic.Dictionary;
import com.yesmywine.util.error.yesmywineException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.transaction.Transactional;
import java.util.*;
/**
* Created by hz on 1/6/17.
*/
@Service
@Transactional
public class PropServiceImpl extends BaseServiceImpl<com.yesmywine.goods.entityProperties.Properties, Integer> implements ProService {
@Autowired
private PropertiesDao propertiesDao;
@Autowired
private ProperValueDao properValueDao;
// @Autowired
// private PropGoodsDao propGoodsDao;
@Autowired
private GoodsDao goodsRepository;
@Autowired
private CategoryPropertyDao categoryPropertyDao;
@Autowired
private SkuDao skuDao;
@Autowired
private SpuDao spuDao;
@Autowired
private CommonService<com.yesmywine.goods.entityProperties.Properties> commonService;
@Autowired
private CommonService<PropertiesValue> commonServiceValue;
@Autowired
private CategoryDao categoryDao;
public String addPrpo(Map<String, String> parm) throws yesmywineException { //新增属性
// Integer categoryId = Integer.parseInt(parm.get("categoryId"));
String isSku = parm.get("isSku"); //0是
String canSearch = parm.get("canSearch");//0是
String cnName = parm.get("cnName");
String code = parm.get("code");
if(null!=propertiesDao.findByCode(code)){
ValueUtil.isError("该编码已存在");
}
if(null!=propertiesDao.findByCnName(cnName)){
ValueUtil.isError("该属性已存在");
}
com.yesmywine.goods.entityProperties.Properties properties = new com.yesmywine.goods.entityProperties.Properties();
properties.setCnName(cnName);
properties.setCode(parm.get("code"));
// properties.setEnName(enName);
// properties.setCategory(categoryDao.findOne(categoryId));
properties.setIsUse(IsUse.no);
if (isSku.equals("yes")) {
properties.setIsSku(IsSku.yes);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else
properties.setCanSearch(CanSearch.yes);
properties.setEntryMode(EntryMode.nullall);
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
// Integer propertiesId = propertiesDao.findId();
// if(ValueUtil.notEmpity(parm.get("valueJson"))){
// String valueJson= parm.get("valueJson");
// JsonParser jsonParser = new JsonParser();
// JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
// for (int i = 0; i < arr.size(); i++) {
// PropertiesValue propertiesValue = new PropertiesValue();
//// propertiesValue.setCnName(cnName);
// propertiesValue.setPropertiesId(propertiesId);
// String value = arr.get(i).getAsJsonObject().get("value").getAsString();
// String code = arr.get(i).getAsJsonObject().get("code").getAsString();
// propertiesValue.setCode(code);
// propertiesValue.setCnValue(value);
// properValueDao.save(propertiesValue);
// }
// }
// return "success";
} else
properties.setIsSku(IsSku.no);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else {
properties.setCanSearch(CanSearch.yes);
}
String entryMode = parm.get("entryMode");
if(entryMode.equals("manual")){
properties.setEntryMode(EntryMode.manual);
try {
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
}catch (Exception e){
return "该属性已存在";
}
}else {
properties.setEntryMode(EntryMode.lists);
propertiesDao.save(properties);
parm.put("id", properties.getId().toString());
if (!this.commonService.synchronous(parm, Dictionary.MALL_HOST + "/goods/properties/synchronous", 0)) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
}
}
@Override
public Map<String, String> addPrpoByImport(Map<String, String> parm) throws yesmywineException {
Map<String, String> reMap = new HashMap<>();
String isSku = parm.get("isSku"); //0是
String canSearch = parm.get("canSearch");//0是
String cnName = parm.get("cnName");
if(null!=propertiesDao.findByCnName(cnName)){
reMap.put("erro", "该属性已存在");
return reMap;
}
// String enName = parm.get("enName");
// Category category=new Category();
// category.setId(categoryId);
// if(null!=propertiesDao.findByCategoryAndCnName(category,cnName)){
// return "该属性在此分类下已有,不可新建";
// }
com.yesmywine.goods.entityProperties.Properties properties = new com.yesmywine.goods.entityProperties.Properties();
properties.setCnName(cnName);
// properties.setEnName(enName);
// properties.setCategory(categoryDao.findOne(categoryId));
properties.setIsUse(IsUse.no);
if (isSku.equals("yes")) {
properties.setIsSku(IsSku.yes);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else
properties.setCanSearch(CanSearch.yes);
properties.setEntryMode(EntryMode.nullall);
propertiesDao.save(properties);
parm.put("id",properties.getId().toString());
if(ValueUtil.isEmpity(parm.get("valueJson"))){
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}
Integer propertiesId = propertiesDao.findId();
if(ValueUtil.notEmpity(parm.get("valueJson"))){
String valueJson= parm.get("valueJson");
JsonParser jsonParser = new JsonParser();
JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
for (int i = 0; i < arr.size(); i++) {
PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setCnName(cnName);
propertiesValue.setPropertiesId(propertiesId);
String value = arr.get(i).getAsJsonObject().get("value").getAsString();
String code = arr.get(i).getAsJsonObject().get("code").getAsString();
propertiesValue.setCode(code);
propertiesValue.setCnValue(value);
properValueDao.save(propertiesValue);
}
}
reMap.put("success", properties.getId().toString());
return reMap;
} else
properties.setIsSku(IsSku.no);
if (canSearch.equals("no")) {
properties.setCanSearch(CanSearch.no);
} else {
properties.setCanSearch(CanSearch.yes);
}
String entryMode = parm.get("entryMode");
if(entryMode.equals("manual")){
properties.setEntryMode(EntryMode.manual);
try {
propertiesDao.save(properties);
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}catch (Exception e){
reMap.put("erro", "该属性已存在");
return reMap;
}
}else {
properties.setEntryMode(EntryMode.lists);
propertiesDao.save(properties);
Integer propertiesId = propertiesDao.findId();
if(ValueUtil.notEmpity(parm.get("valueJson"))) {
String valueJson = parm.get("valueJson");
String[] arr = valueJson.split(",");
for (int i = 0; i < arr.length; i++) {
PropertiesValue propertiesValue = new PropertiesValue();
propertiesValue.setPropertiesId(propertiesId);
// propertiesValue.setCnName(cnName);
propertiesValue.setCnValue(arr[i]);
properValueDao.save(propertiesValue);
}
}
}
propertiesDao.save(properties);
if(!this.commonService.synchronous(parm, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 0)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
reMap.put("erro", "同步失败");
return reMap;
}
reMap.put("success", properties.getId().toString());
return reMap;
}
public String updateProp(Integer id,String canSearch,String cnName,String isSku,String entryMode) throws yesmywineException {
com.yesmywine.goods.entityProperties.Properties entity = propertiesDao.findOne(id);
Properties byCnName = propertiesDao.findByCnName(cnName);
if(null!=byCnName&&byCnName.getId()!=(int)id){
ValueUtil.isError("该属性名已存在");
}
if (entity.getIsUse() == IsUse.no) {
entity.setCnName(cnName);
if (canSearch.equals("yes")) {
entity.setCanSearch(CanSearch.yes);
} else {
entity.setCanSearch(CanSearch.no);
}
if (isSku.equals("yes")) {
entity.setIsSku(IsSku.yes);
entity.setEntryMode(EntryMode.nullall);
} else if (entryMode.equals("manual")) { //手动
entity.setIsSku(IsSku.no);
entity.setEntryMode(EntryMode.manual);
} else {
entity.setIsSku(IsSku.no);
entity.setEntryMode(EntryMode.lists);
}
propertiesDao.save(entity);
Map<String, String> map = new HashMap<>();
map.put("id", entity.getId().toString());
if(!this.commonService.synchronous(entity, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 1, map)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
return "success";
} else if (canSearch.equals("yes")) {
entity.setCanSearch(CanSearch.yes);
} else {
entity.setCanSearch(CanSearch.no);
}
entity.setCnName(cnName);
propertiesDao.save(entity);
Map<String, String> map = new HashMap<>();
map.put("id", entity.getId().toString());
// map.put("categoryId", categoryId.toString());
if(!this.commonService.synchronous(entity, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 1, map)) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
// if (valueJson == null) {
// return "success";
// } else if (entity.getIsSku() == IsSku.yes) {
// JsonParser jsonParser = new JsonParser();
// JsonArray arr = jsonParser.parse(valueJson).getAsJsonArray();
// for (int i = 0; i < arr.size(); i++) {
// String value = arr.get(i).getAsJsonObject().get("value").getAsString();
// String code = arr.get(i).getAsJsonObject().get("code").getAsString();
// List<PropertiesValue> p=properValueDao.findByCnValueAndPropertiesId(value, id);
// if (0==p.size()) {
// PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setCnName(cnName);
// propertiesValue.setPropertiesId(id);
// propertiesValue.setCode(code);
// propertiesValue.setCnValue(value);
// Map<String, String> map1 = new HashMap<>();
// map1.put("id", propertiesValue.getId().toString());
//// map.put("categoryId", categoryId.toString());
// if(this.commonServiceValue.synchronous(propertiesValue, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1, map1)){
// properValueDao.save(propertiesValue);
// }
// return "同步失败";
// }else {
// return "该属性下属性值已存在";
// }
// }
// } else {
// String[] arr = valueJson.split(",");
// for (int i = 0; i < arr.length; i++) {
// List<PropertiesValue> propertiesValue1=properValueDao.findByCnValueAndPropertiesId(arr[i],id);
// if (0 == propertiesValue1.size()){
// PropertiesValue propertiesValue = new PropertiesValue();
// propertiesValue.setPropertiesId(id);
// propertiesValue.setCnName(cnName);
// propertiesValue.setCnValue(arr[i]);
// Map<String, String> map1 = new HashMap<>();
// map1.put("id", propertiesValue.getId().toString());
//// map.put("categoryId", categoryId.toString());
// if(this.commonServiceValue.synchronous(propertiesValue, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1, map1)){
// properValueDao.save(propertiesValue);
// }
// return "同步失败";
// }else{
// return "该属性下属性值已经存在";
// }
// }
// }
return "success";
// }
// return "同步失败";
}
public String updateAdd(Integer propId, String code, String value){
PropertiesValue propertiesValue = new PropertiesValue();
propertiesValue.setCnValue(value);
propertiesValue.setCode(code);
propertiesValue.setPropertiesId(propId);
properValueDao.save(propertiesValue);
return "success";
}
public String deleteProp(Integer propId) throws yesmywineException {
List<CategoryProperty> byPropertyId = categoryPropertyDao.findByPropertyId(propId);
if(byPropertyId.size()!=0){
ValueUtil.isError("该属性被用,不可删除");
}
com.yesmywine.goods.entityProperties.Properties properties = propertiesDao.findOne(propId);
propertiesDao.delete(properties);
if(!this.commonService.synchronous(properties, Dictionary.MALL_HOST+ "/goods/properties/synchronous", 2)){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ValueUtil.isError("同步失败");
}
List<PropertiesValue> propList=properValueDao.findByPropertiesId(propId);
properValueDao.delete(propList);
return "success";
}
@Override
public com.yesmywine.goods.entityProperties.Properties findByCnName(String cnName) {
return this.propertiesDao.findByCnName(cnName);
}
// @Override
// public String propCanShow(Integer propId) throws yesmywineException {
// com.yesmywine.goods.entityProperties.Properties properties=propertiesDao.findOne(propId);
// properties.setCanShow(!properties.isCanShow());
// propertiesDao.save(properties);
// if(!this.commonService.synchronous(properties, Dictionary.goodsUrl+ "/goods/properties/synchronous", 1)) {
// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
// return "同步失败";
// }
// return "success";
// }
// public Map<String, List<String>> getProperByCategory(Integer categoryId) { //通过分类获取可查询的属性和值(前台用)
// Category category=new Category();
// category.setId(categoryId);
// List<Properties> list = propertiesDao.findByCategoryAndCanSearch(category,CanSearch.yes);
// Map<String, List<String>> properyName = new HashMap<>();
// for (int i = 0; i < list.size(); i++) {
// List<PropertiesValue> listValue = properValueDao.findByPropertiesId(list.get(i).getId());
// String name = propertiesDao.findOne(list.get(i).getId()).getCnName();
// if (null == properyName.get(name)) {
// properyName.put(name, new ArrayList<>());
// }
// for (int j = 0; j < listValue.size(); j++) {
// String cnValue = listValue.get(j).getCnValue();
// properyName.get(name).add(cnValue);
// }
// }
// return properyName;
// }
// public Object getMethods(Integer categoryId) { //查出该分类下的属性值的组合
// List<Integer> properId = propertiesDao.findIdByCategoryId(categoryId);
// List<PropGoods> propGoods = new ArrayList<>();
// for (int j = 0; j < properId.size(); j++) {
// List<PropertiesValue> listValue = properValueDao.findByPropertiesId(properId.get(j));
// listValue.forEach(k -> {
// List<PropGoods> prop = propGoodsDao.findByPropValueId(String.valueOf(k.getId()));
// prop.forEach(l -> {
// propGoods.add(l);
// });
// });
// }
// List<Map<String, Object>> showOut = new ArrayList<>();
// Map<Integer, Map<String, Object>> goodsProperties = new HashMap<>();
// for (int i = 0; i < propGoods.size(); i++) {
// PropGoods tempPropGoods = propGoods.get(i);
// if (null == goodsProperties.get(tempPropGoods.getGoodsId())) {
// goodsProperties.put(tempPropGoods.getGoodsId(), new HashMap<>());
// goodsProperties.get(tempPropGoods.getGoodsId()).put("goodsId", tempPropGoods.getGoodsId());
// }
// goodsProperties.get(tempPropGoods.getGoodsId()).put(tempPropGoods.getCnName(), tempPropGoods.getPropValueId());
// }
// goodsProperties.forEach((k, v) -> {
// showOut.add(v);
// });
//
// return showOut;
// }
// public Map[] getGeneralProp(Integer categoryId) { //通过分类属性及部分属性的值
// Category category=new Category();
// category.setId(categoryId);
// List<Properties> propties = propertiesDao.findByCategoryAndDeleteEnum(category,DeleteEnum.NOT_DELETE);
// Map[] map = new HashMap[propties.size()];
// for(int i=0;i< propties.size(); i++){
// Map<String, Object> prop = new HashMap<>();
// prop.put("value", propties.get(i).getId().toString());
// String cnName = propties.get(i).getCnName();
// prop.put("label", cnName);
// List<PropertiesValue> values = properValueDao.findByPropertiesId(propties.get(i).getId());
// Map[] map2 = new HashMap[values.size()];
// for(int j=0;j< values.size(); j++){
// Map<String, String> value = new HashMap<>();
// value.put("value", values.get(j).getId().toString());
// String cnValue = values.get(j).getCnValue();
// value.put("label", cnValue);
// map2[j] = value;
// }
// prop.put("child", map2);
// map[i]= prop;
// }
// return map;
// }
public String getRepertory(String skuId) { //查看库存
HttpBean httpRequest = new HttpBean("http://172.16.31.10:8191/inventory/goodsInventory" + "/" + skuId, RequestMethod.get);
httpRequest.run();
String amount = httpRequest.getResponseContent();
return amount;
}
}
| 22,157 | 0.580084 | 0.57742 | 475 | 44.831577 | 29.826181 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.823158 | false | false |
5
|
d711423344cfa048435098e2c4f5b1eb5abbcb94
| 28,398,323,807,909 |
7e4767b0f31470d0ceea71fb0b11f2fdb4f6716e
|
/Roncoo_ShoppingCartProvider/src/main/java/com/roncoo/shoppingCartProvider/service/impl/ShoppingCartServiceImpl.java
|
f764e7946f8c37d31f94fca64ee0cc8126c47557
|
[] |
no_license
|
sily-wei/Roncoo
|
https://github.com/sily-wei/Roncoo
|
890109f5c626a8a751b346cfdf31eaa7372f1257
|
61b2e025cb0fff7f3139bca3da53a1f4af987cc4
|
refs/heads/master
| 2022-11-18T00:11:59.674000 | 2020-01-18T11:02:26 | 2020-01-18T11:02:26 | 234,326,009 | 5 | 1 | null | false | 2022-11-15T23:54:32 | 2020-01-16T13:28:12 | 2020-08-28T05:45:02 | 2022-11-15T23:54:29 | 107 | 2 | 1 | 3 |
Java
| false | false |
package com.roncoo.shoppingCartProvider.service.impl;
import com.roncoo.shoppingCartProvider.service.ShoppingCartService;
import org.springframework.stereotype.Service;
/**
* @author weining
* @date 2020/1/16 21:04
*/
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
}
|
UTF-8
|
Java
| 304 |
java
|
ShoppingCartServiceImpl.java
|
Java
|
[
{
"context": "pringframework.stereotype.Service;\n\n/**\n * @author weining\n * @date 2020/1/16 21:04\n */\n@Service\npublic clas",
"end": 193,
"score": 0.9996027946472168,
"start": 186,
"tag": "USERNAME",
"value": "weining"
}
] | null |
[] |
package com.roncoo.shoppingCartProvider.service.impl;
import com.roncoo.shoppingCartProvider.service.ShoppingCartService;
import org.springframework.stereotype.Service;
/**
* @author weining
* @date 2020/1/16 21:04
*/
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
}
| 304 | 0.8125 | 0.776316 | 12 | 24.333334 | 25.904739 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
5
|
918be5d841437b2347254e62b8d5f27aeab092ee
| 30,537,217,509,836 |
e8ff9670ab4f3743c9bf00d40421e95b15a3af04
|
/ApachePOI/Projeto/ApachePOI/src/main/java/com/apachepoi/dto/Aluno.java
|
b1786897723e61e71cca076362fcc63a2d1167d1
|
[] |
no_license
|
MarcoAP/TreinamentoJavaBecaEveris
|
https://github.com/MarcoAP/TreinamentoJavaBecaEveris
|
7bb9611ee7e56a73fcb6d1c2c58619d9fba41e4a
|
6efc9dbee94cfcc374da63666a0e2ca97a82721e
|
refs/heads/master
| 2020-04-12T16:43:17.896000 | 2018-12-26T11:24:31 | 2018-12-26T11:24:31 | 162,621,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.apachepoi.dto;
public class Aluno {
private String nomeAluno;
private String notaProva1;
private double notaProva2;
private double media;
private double participacao;
private double mediaFinal;
public Aluno() {
}
public Aluno(String nome, String ra, double nota1, double nota2, double media, double aprovado) {
super();
this.nomeAluno = nome;
this.notaProva1 = ra;
this.notaProva2 = nota1;
this.media = nota2;
this.participacao = media;
this.mediaFinal = aprovado;
}
public String getNomeAluno() {
return nomeAluno;
}
public void setNomeAluno(String nomeAluno) {
this.nomeAluno = nomeAluno;
}
public String getNotaProva1() {
return notaProva1;
}
public void setNotaProva1(String notaProva1) {
this.notaProva1 = notaProva1;
}
public double getNotaProva2() {
return notaProva2;
}
public void setNotaProva2(double notaProva2) {
this.notaProva2 = notaProva2;
}
public double getMedia() {
return media;
}
public void setMedia(double media) {
this.media = media;
}
public double getParticipacao() {
return participacao;
}
public void setParticipacao(double participacao) {
this.participacao = participacao;
}
public double getMediaFinal() {
return mediaFinal;
}
public void setMediaFinal(double mediaFinal) {
this.mediaFinal = mediaFinal;
}
}
|
UTF-8
|
Java
| 1,337 |
java
|
Aluno.java
|
Java
|
[] | null |
[] |
package com.apachepoi.dto;
public class Aluno {
private String nomeAluno;
private String notaProva1;
private double notaProva2;
private double media;
private double participacao;
private double mediaFinal;
public Aluno() {
}
public Aluno(String nome, String ra, double nota1, double nota2, double media, double aprovado) {
super();
this.nomeAluno = nome;
this.notaProva1 = ra;
this.notaProva2 = nota1;
this.media = nota2;
this.participacao = media;
this.mediaFinal = aprovado;
}
public String getNomeAluno() {
return nomeAluno;
}
public void setNomeAluno(String nomeAluno) {
this.nomeAluno = nomeAluno;
}
public String getNotaProva1() {
return notaProva1;
}
public void setNotaProva1(String notaProva1) {
this.notaProva1 = notaProva1;
}
public double getNotaProva2() {
return notaProva2;
}
public void setNotaProva2(double notaProva2) {
this.notaProva2 = notaProva2;
}
public double getMedia() {
return media;
}
public void setMedia(double media) {
this.media = media;
}
public double getParticipacao() {
return participacao;
}
public void setParticipacao(double participacao) {
this.participacao = participacao;
}
public double getMediaFinal() {
return mediaFinal;
}
public void setMediaFinal(double mediaFinal) {
this.mediaFinal = mediaFinal;
}
}
| 1,337 | 0.727749 | 0.71279 | 73 | 17.328768 | 17.919191 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.410959 | false | false |
5
|
54c84fe53926ef7b15f16c1ca7fc1f89b19420fc
| 9,337,258,944,931 |
781931a15b8f64be7e2dcc19da3ced248c3345b5
|
/sources/src/com/zyb/nowplus/presentation/controller/SmsController.java
|
dbb79832e70355d5fa96b00002050b4304c8ab05
|
[] |
no_license
|
360J2ME/360-People-Client-J2ME
|
https://github.com/360J2ME/360-People-Client-J2ME
|
bc9f5e9d75da347f1aa613ad48ca9e35d1c51eed
|
7d3fa8233ee77abbee75b0ec6388efec9a87e9fe
|
refs/heads/master
| 2016-09-03T06:34:06.999000 | 2010-08-09T15:08:12 | 2010-08-09T15:08:12 | 826,257 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
******************************************************************************/
//#condition polish.device.supports.nativesms == false
/**
*
*/
package com.zyb.nowplus.presentation.controller;
import com.zyb.nowplus.business.Model;
import com.zyb.nowplus.business.domain.Channel;
import com.zyb.nowplus.business.domain.ManagedProfile;
import com.zyb.nowplus.presentation.ExtendedScreenHistory;
import com.zyb.nowplus.presentation.view.forms.BaseTabForm;
import com.zyb.nowplus.presentation.view.forms.NotificationForm;
import com.zyb.nowplus.presentation.view.forms.SmsForm;
import com.zyb.nowplus.presentation.view.items.ProgressIndicatorItem;
import com.zyb.util.TextUtilities;
import com.zyb.util.event.Event;
import de.enough.polish.ui.Command;
import de.enough.polish.ui.CommandListener;
import de.enough.polish.ui.Displayable;
import de.enough.polish.util.Locale;
/**
* Controller class for sending sms when there is no native sms in platformRequest
* It handles commands from SmsForm and uses WMA to send sms-es.
*
* @author marek.defecinski@mobica.com
*
*/
public class SmsController extends ContextController implements CommandListener
{
public SmsController(Model model, Controller controller,
ExtendedScreenHistory history)
{
super(model, controller, history);
}
public byte getContext() {
return Event.Context.SMS_EDITOR;
}
public void handleEvent(byte context, int event, Object data) {
//#debug debug
System.out.println("handleEvent" + context + " " + event + " " + data);
// When you choose sms number
try {
if (context == getContext()) {
switch(event) {
case Event.SmsEditor.OPEN:
if (data instanceof Channel) {
//#style sms_form
SmsForm smsForm = new SmsForm(getModel(), getController(),
null, (Channel) data);
smsForm.setCommandListener(this);
getController().notifyEvent(Event.Context.NAVIGATION,
Event.Navigation.NEXT_CHECKPOINT, smsForm);
}
// When you want send sms in primary number.
else if (data instanceof ManagedProfile) {
//#style sms_form
SmsForm smsForm = new SmsForm(getModel(), getController(),
(ManagedProfile) data);
smsForm.setCommandListener(this);
getController().notifyEvent(Event.Context.NAVIGATION,
Event.Navigation.NEXT_CHECKPOINT, smsForm);
}
break;
case Event.SmsEditor.SEND_OK:
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.DISMISS, data);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.BACK_CHECKPOINT);
break;
case Event.SmsEditor.SEND_FAILED:
//#style notification_form_base
NotificationForm errorNotification = new NotificationForm(model, controller, Locale.get("nowplus.client.java.sms.error.notification.headline"),
Locale.get("nowplus.client.java.sms.error.notification.message"), BaseTabForm.cmdBack, 0, true);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.DISMISS, data);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.NEXT_GLOBAL, errorNotification);
break;
case Event.SmsEditor.SEND_STARTED:
controller.notifyEvent(Event.Context.NAVIGATION, Event.Navigation.NEXT_GLOBAL, data);
break;
}
}
} catch (IllegalArgumentException e) {
//#debug error
System.out.println("IllegalArgumentException " + e.getMessage());
}
}
public void commandAction(Command command, Displayable displayable)
{
//#debug debug
System.out.println("command:"+command.getLabel());
if (displayable instanceof SmsForm){
if(command == SmsForm.cmdOptions){
getController().notifyEvent(Event.Context.CONTEXTUAL_MENU, Event.ContextualMenu.OPEN, ((SmsForm)displayable).getProfile());
}else
if(command == SmsForm.cmdSubmit) {
final String number = ((SmsForm)displayable).getNumber();
final String message = ((SmsForm)displayable).getMessage();
if (message==null || message.length()==0){
return;
}
sendSms(TextUtilities.stripNonValidChars(TextUtilities.VALID_PHONE_NUMBER_CHARS, number), message);
} else if(command == SmsForm.cmdBack) {
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.BACK_CHECKPOINT);
}
}
}
public void sendSms(final String number, final String message) {
//#style notification_form_progress
NotificationForm sendingNotification = new NotificationForm(model, controller, Locale.get("nowplus.client.java.sms.notification.headline"),
null, null, 0, false, ProgressIndicatorItem.PROGRESS_INFINITE);
getModel().sendSms(number, message, sendingNotification);
}
}
|
UTF-8
|
Java
| 5,700 |
java
|
SmsController.java
|
Java
|
[
{
"context": "ople/VODAFONE.LICENSE.txt or\n * http://github.com/360/360-Engine-for-Android\n * See the License for the",
"end": 424,
"score": 0.9895567893981934,
"start": 421,
"tag": "USERNAME",
"value": "360"
},
{
"context": "sForm and uses WMA to send sms-es. \n * \n * @author marek.defecinski@mobica.com\n *\n */\npublic class SmsController extends Context",
"end": 2126,
"score": 0.999666154384613,
"start": 2099,
"tag": "EMAIL",
"value": "marek.defecinski@mobica.com"
}
] | null |
[] |
/*******************************************************************************
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
******************************************************************************/
//#condition polish.device.supports.nativesms == false
/**
*
*/
package com.zyb.nowplus.presentation.controller;
import com.zyb.nowplus.business.Model;
import com.zyb.nowplus.business.domain.Channel;
import com.zyb.nowplus.business.domain.ManagedProfile;
import com.zyb.nowplus.presentation.ExtendedScreenHistory;
import com.zyb.nowplus.presentation.view.forms.BaseTabForm;
import com.zyb.nowplus.presentation.view.forms.NotificationForm;
import com.zyb.nowplus.presentation.view.forms.SmsForm;
import com.zyb.nowplus.presentation.view.items.ProgressIndicatorItem;
import com.zyb.util.TextUtilities;
import com.zyb.util.event.Event;
import de.enough.polish.ui.Command;
import de.enough.polish.ui.CommandListener;
import de.enough.polish.ui.Displayable;
import de.enough.polish.util.Locale;
/**
* Controller class for sending sms when there is no native sms in platformRequest
* It handles commands from SmsForm and uses WMA to send sms-es.
*
* @author <EMAIL>
*
*/
public class SmsController extends ContextController implements CommandListener
{
public SmsController(Model model, Controller controller,
ExtendedScreenHistory history)
{
super(model, controller, history);
}
public byte getContext() {
return Event.Context.SMS_EDITOR;
}
public void handleEvent(byte context, int event, Object data) {
//#debug debug
System.out.println("handleEvent" + context + " " + event + " " + data);
// When you choose sms number
try {
if (context == getContext()) {
switch(event) {
case Event.SmsEditor.OPEN:
if (data instanceof Channel) {
//#style sms_form
SmsForm smsForm = new SmsForm(getModel(), getController(),
null, (Channel) data);
smsForm.setCommandListener(this);
getController().notifyEvent(Event.Context.NAVIGATION,
Event.Navigation.NEXT_CHECKPOINT, smsForm);
}
// When you want send sms in primary number.
else if (data instanceof ManagedProfile) {
//#style sms_form
SmsForm smsForm = new SmsForm(getModel(), getController(),
(ManagedProfile) data);
smsForm.setCommandListener(this);
getController().notifyEvent(Event.Context.NAVIGATION,
Event.Navigation.NEXT_CHECKPOINT, smsForm);
}
break;
case Event.SmsEditor.SEND_OK:
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.DISMISS, data);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.BACK_CHECKPOINT);
break;
case Event.SmsEditor.SEND_FAILED:
//#style notification_form_base
NotificationForm errorNotification = new NotificationForm(model, controller, Locale.get("nowplus.client.java.sms.error.notification.headline"),
Locale.get("nowplus.client.java.sms.error.notification.message"), BaseTabForm.cmdBack, 0, true);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.DISMISS, data);
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.NEXT_GLOBAL, errorNotification);
break;
case Event.SmsEditor.SEND_STARTED:
controller.notifyEvent(Event.Context.NAVIGATION, Event.Navigation.NEXT_GLOBAL, data);
break;
}
}
} catch (IllegalArgumentException e) {
//#debug error
System.out.println("IllegalArgumentException " + e.getMessage());
}
}
public void commandAction(Command command, Displayable displayable)
{
//#debug debug
System.out.println("command:"+command.getLabel());
if (displayable instanceof SmsForm){
if(command == SmsForm.cmdOptions){
getController().notifyEvent(Event.Context.CONTEXTUAL_MENU, Event.ContextualMenu.OPEN, ((SmsForm)displayable).getProfile());
}else
if(command == SmsForm.cmdSubmit) {
final String number = ((SmsForm)displayable).getNumber();
final String message = ((SmsForm)displayable).getMessage();
if (message==null || message.length()==0){
return;
}
sendSms(TextUtilities.stripNonValidChars(TextUtilities.VALID_PHONE_NUMBER_CHARS, number), message);
} else if(command == SmsForm.cmdBack) {
getController().notifyEvent(Event.Context.NAVIGATION, Event.Navigation.BACK_CHECKPOINT);
}
}
}
public void sendSms(final String number, final String message) {
//#style notification_form_progress
NotificationForm sendingNotification = new NotificationForm(model, controller, Locale.get("nowplus.client.java.sms.notification.headline"),
null, null, 0, false, ProgressIndicatorItem.PROGRESS_INFINITE);
getModel().sendSms(number, message, sendingNotification);
}
}
| 5,680 | 0.717368 | 0.714035 | 146 | 38.041096 | 32.97298 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.595891 | false | false |
5
|
5c674ee5890b0e26bdc8cafdc26f96a8110a499b
| 27,479,200,767,270 |
116ba0b8aed5578b1f83164fec8209d9454da6a0
|
/src/io/brace/lightsoutgaming/immortalSilence/Weapon.java
|
b29bd5dcaa00230764d6e93f78f3008a3be5e6b4
|
[] |
no_license
|
taz40/Immortal-Silence
|
https://github.com/taz40/Immortal-Silence
|
1dceb7685b36e0d0e61237f8b89e8bbb25aa4792
|
fa9b6422ab9341d8b58ac38ba35e60376558eb70
|
refs/heads/master
| 2020-05-04T00:33:27.698000 | 2014-09-25T15:43:21 | 2014-09-25T15:43:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.brace.lightsoutgaming.immortalSilence;
import io.brace.lightsoutgaming.engine.Entity;
import io.brace.lightsoutgaming.engine.Network.NetworkUtils;
import io.brace.lightsoutgaming.engine.graphics.Screen;
import io.brace.lightsoutgaming.engine.graphics.Sprite;
import io.brace.lightsoutgaming.engine.input.Keyboard;
import io.brace.lightsoutgaming.immortalSilence.entities.PistolBullet;
import io.brace.lightsoutgaming.immortalSilence.entities.bullet;
import java.awt.event.KeyEvent;
public class Weapon extends Entity {
float damage;
float cooldown;
int range;
float cooldownt;
long lasttime = -1;
int ammo = 0;
int ammoinclip = 0;
int ammoPerClip;
boolean beingHeld = true;
float reloadTime;
float reloadTimer;
boolean reloading = false;
public static Sprite pistol_round = new Sprite(66, 20, 3, 1, 2, Main.main);
public Weapon(float damage, float cooldown, int range, int ammoPerClip, int ammo, float reloadTime){
this.damage = damage;
this.cooldown = cooldown;
cooldownt = cooldown;
this.range = range;
this.ammo = ammo;
this.ammoPerClip = ammoPerClip;
ammoinclip = ammoPerClip;
this.reloadTime = reloadTime;
reloadTimer = reloadTime;
}
@Override
public void update() {
// TODO Auto-generated method stub
if(cooldownt < cooldown){
if(lasttime == -1){
lasttime = System.currentTimeMillis();
}else{
long now = System.currentTimeMillis();
cooldownt += (now - lasttime) / 1000.0;
lasttime = now;
}
}
if(Keyboard.getKey(KeyEvent.VK_R)){
reloading = true;
reloadTimer = 0;
ammo += ammoinclip;
ammoinclip = 0;
lasttime = System.currentTimeMillis();
}
if(reloading){
if(lasttime == -1){
lasttime = System.currentTimeMillis();
}else{
long now = System.currentTimeMillis();
reloadTimer += (now - lasttime) / 1000.0;
lasttime = now;
}
if(reloadTimer >= reloadTime){
reloading = false;
if(ammo >= ammoPerClip){
ammo -= ammoPerClip;
ammoinclip = ammoPerClip;
}else{
ammoinclip = ammo;
ammo = 0;
}
}
}
}
@Override
public void render(Screen s) {
// TODO Auto-generated method stub
}
public void fire(double angle, int x, int y){
if(cooldownt >= cooldown && ammoinclip > 0){
int id = NetworkUtils.createObject(PistolBullet.class, NetworkUtils.serverIP, NetworkUtils.serverPort, Main.socket);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bullet b = (bullet)NetworkUtils.myObjects.get(id);
b.x = x;
b.y = y;
b.rot = Math.toDegrees(angle);
b.vx = PistolBullet.PistolSpeed * Math.cos(angle);
b.vy = PistolBullet.PistolSpeed * Math.sin(angle);
System.out.println("velocity, X: " + b.vx + ", Y: " + b.vy);
ammoinclip--;
System.out.println("bang!");
cooldownt = 0;
lasttime = System.currentTimeMillis();
}
}
}
|
UTF-8
|
Java
| 3,030 |
java
|
Weapon.java
|
Java
|
[] | null |
[] |
package io.brace.lightsoutgaming.immortalSilence;
import io.brace.lightsoutgaming.engine.Entity;
import io.brace.lightsoutgaming.engine.Network.NetworkUtils;
import io.brace.lightsoutgaming.engine.graphics.Screen;
import io.brace.lightsoutgaming.engine.graphics.Sprite;
import io.brace.lightsoutgaming.engine.input.Keyboard;
import io.brace.lightsoutgaming.immortalSilence.entities.PistolBullet;
import io.brace.lightsoutgaming.immortalSilence.entities.bullet;
import java.awt.event.KeyEvent;
public class Weapon extends Entity {
float damage;
float cooldown;
int range;
float cooldownt;
long lasttime = -1;
int ammo = 0;
int ammoinclip = 0;
int ammoPerClip;
boolean beingHeld = true;
float reloadTime;
float reloadTimer;
boolean reloading = false;
public static Sprite pistol_round = new Sprite(66, 20, 3, 1, 2, Main.main);
public Weapon(float damage, float cooldown, int range, int ammoPerClip, int ammo, float reloadTime){
this.damage = damage;
this.cooldown = cooldown;
cooldownt = cooldown;
this.range = range;
this.ammo = ammo;
this.ammoPerClip = ammoPerClip;
ammoinclip = ammoPerClip;
this.reloadTime = reloadTime;
reloadTimer = reloadTime;
}
@Override
public void update() {
// TODO Auto-generated method stub
if(cooldownt < cooldown){
if(lasttime == -1){
lasttime = System.currentTimeMillis();
}else{
long now = System.currentTimeMillis();
cooldownt += (now - lasttime) / 1000.0;
lasttime = now;
}
}
if(Keyboard.getKey(KeyEvent.VK_R)){
reloading = true;
reloadTimer = 0;
ammo += ammoinclip;
ammoinclip = 0;
lasttime = System.currentTimeMillis();
}
if(reloading){
if(lasttime == -1){
lasttime = System.currentTimeMillis();
}else{
long now = System.currentTimeMillis();
reloadTimer += (now - lasttime) / 1000.0;
lasttime = now;
}
if(reloadTimer >= reloadTime){
reloading = false;
if(ammo >= ammoPerClip){
ammo -= ammoPerClip;
ammoinclip = ammoPerClip;
}else{
ammoinclip = ammo;
ammo = 0;
}
}
}
}
@Override
public void render(Screen s) {
// TODO Auto-generated method stub
}
public void fire(double angle, int x, int y){
if(cooldownt >= cooldown && ammoinclip > 0){
int id = NetworkUtils.createObject(PistolBullet.class, NetworkUtils.serverIP, NetworkUtils.serverPort, Main.socket);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bullet b = (bullet)NetworkUtils.myObjects.get(id);
b.x = x;
b.y = y;
b.rot = Math.toDegrees(angle);
b.vx = PistolBullet.PistolSpeed * Math.cos(angle);
b.vy = PistolBullet.PistolSpeed * Math.sin(angle);
System.out.println("velocity, X: " + b.vx + ", Y: " + b.vy);
ammoinclip--;
System.out.println("bang!");
cooldownt = 0;
lasttime = System.currentTimeMillis();
}
}
}
| 3,030 | 0.662046 | 0.652145 | 112 | 25.053572 | 21.363285 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.794643 | false | false |
5
|
1cc5ba9339dfce243e4267c033542298c0521867
| 11,673,721,167,869 |
6275865919461feb536cbafd6d1d99507395b70f
|
/src/main/java/uk/co/codeghost/adventofcode/day3/Position.java
|
66e79fdfbd9b1973abbc2363d9f500e051fcb0fe
|
[] |
no_license
|
rocketstack-matt/advent-of-code
|
https://github.com/rocketstack-matt/advent-of-code
|
ef42ff6fbbd39fd370200270e3403a844d06cda6
|
74fd12444c102db63f873bbfcf48576105349d2a
|
refs/heads/master
| 2022-03-24T12:35:05.581000 | 2019-12-07T22:53:43 | 2019-12-07T22:53:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package uk.co.codeghost.adventofcode.day3;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
@AllArgsConstructor
public class Position {
@Getter
@Setter
private int x;
@Getter
@Setter
private int y;
@Getter
@Setter
private int step;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Position)) return false;
Position position = (Position) o;
return x == position.x &&
y == position.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Position{" +
"x=" + x +
", y=" + y +
", step=" + step +
'}';
}
}
|
UTF-8
|
Java
| 861 |
java
|
Position.java
|
Java
|
[
{
"context": "package uk.co.codeghost.adventofcode.day3;\n\nimport lombok.AllArgsConstruc",
"end": 23,
"score": 0.9965577721595764,
"start": 14,
"tag": "USERNAME",
"value": "codeghost"
}
] | null |
[] |
package uk.co.codeghost.adventofcode.day3;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
@AllArgsConstructor
public class Position {
@Getter
@Setter
private int x;
@Getter
@Setter
private int y;
@Getter
@Setter
private int step;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Position)) return false;
Position position = (Position) o;
return x == position.x &&
y == position.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Position{" +
"x=" + x +
", y=" + y +
", step=" + step +
'}';
}
}
| 861 | 0.538908 | 0.537747 | 43 | 19.023256 | 13.347743 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395349 | false | false |
5
|
6dcbdf30fecd93173bdac46a064885849d87e6f9
| 16,277,926,112,640 |
78cbbde5c80ff28f6830aa605afd543ce2fb2245
|
/app/src/main/java/whattodo/whattodo/MapsActivity.java
|
8168d3782dbcdcaca87555f9ce11ab43a45dd1a3
|
[] |
no_license
|
Zebrap/WhatToDo
|
https://github.com/Zebrap/WhatToDo
|
2461c5f168efb7396a6261c13483054c882dd0bf
|
7c04b4564f85326f21b30a43a6b65af0e2fcdd9e
|
refs/heads/master
| 2020-04-04T21:16:50.119000 | 2019-05-17T15:42:21 | 2019-05-17T15:42:21 | 156,280,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package whattodo.whattodo;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.DirectionsCriteria;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.services.android.navigation.ui.v5.NavigationView;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.OnNavigationReadyCallback;
import com.mapbox.services.android.navigation.ui.v5.instruction.InstructionView;
import com.mapbox.services.android.navigation.ui.v5.listeners.NavigationListener;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgressState;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MapsActivity extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, LocationEngineListener, PermissionsListener, ProgressChangeListener {
private Point origin = Point.fromLngLat( 18.618783,54.372496);
private Point destination = Point.fromLngLat( 18.616432,54.380217);
private NavigationView navigationView;
private InstructionView instructionView;
private PermissionsManager permissionsManager;
private Location originLocation;
private LocationEngine locationEngine;
private DirectionsRoute currentRoute;
private double Long, Lat;
private String attraction_name;
private Boolean endLocation = false;
@Override
@SuppressWarnings("MissingPermission")
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,
"pk.eyJ1IjoiemVicmFwdyIsImEiOiJjam9kNTZkMzkwc3RiM3ZvMTNlNHIya2s2In0.DyQaOsbV8AL0kmYR4TF5KQ");
setContentView(R.layout.activity_maps);
enableLocation();
Location lastLocation = locationEngine.getLastLocation();
locationEngine.activate();
locationEngine.addLocationEngineListener(this);
String location = "";
if (lastLocation != null) {
origin = Point.fromLngLat(originLocation.getLongitude(),originLocation.getLatitude());
}
Intent intent = getIntent();
Long = Double.parseDouble(intent.getStringExtra("Longitude"));
Lat = Double.parseDouble(intent.getStringExtra("Latitude"));
attraction_name = intent.getStringExtra("attraction_name");
instructionView = findViewById(R.id.instructionView);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
navigationView.initialize(this);
}
@Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
@Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
@Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
@Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
@Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
@Override
public void onNavigationReady(boolean isRunning) {
navigationView.findViewById(R.id.feedbackFab).setVisibility(View.GONE);
navigationView.findViewById(R.id.instructionLayout).setEnabled(false);
getRoute();
}
@Override
public void onCancelNavigation() {
onBackPressed();
}
@Override
public void onNavigationFinished() {
}
@Override
public void onNavigationRunning() {
}
@SuppressWarnings("MissingPermission")
private void enableLocation(){
if(permissionsManager.areLocationPermissionsGranted(this)){
initializedLocationEngine();
}else{
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
@SuppressWarnings("MissingPermission")
private void initializedLocationEngine(){
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if(lastLocation!=null){
originLocation = lastLocation;
}else{
locationEngine.addLocationEngineListener(this);
}
}
@SuppressWarnings("MissingPermission")
@Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
if(location!=null){
originLocation = location;
}
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
@Override
public void onPermissionResult(boolean granted) {
if(granted){
enableLocation();
}
}
@Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
if (routeProgress.currentState().equals(RouteProgressState.ROUTE_ARRIVED)) {
if(!endLocation){
endLocation = true;
String name = "nazwa";
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
String username = pref.getString("username", "");
String attraction_id = pref.getString("attraction_id", "");
SharedPreferences.Editor editor = pref.edit();
editor.putString("find","true");
editor.commit();
String url ="https://whattodowebservice.azurewebsites.net/visit?login="+username+"&attractionid="+attraction_id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(stringRequest);
AlertDialog.Builder bulder = new AlertDialog.Builder(MapsActivity.this);
bulder.setMessage("Gratulacje dotarłeś do celu: "+attraction_name+", sprawdź i oceń później")
.setNegativeButton("Ok",null)
.create()
.show();
}
}
}
private void getRoute(){
destination = Point.fromLngLat(Long,Lat);
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if(response.body() == null){
Log.e("tag","No routs found, check right user and access token");
return;
}else if(response.body().routes().size()==0){
Log.e("tag","No routes found");
return;
}
currentRoute = response.body().routes().get(0);
DirectionsRoute directionsRoute = response.body().routes().get(0);
startNavigation(directionsRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e("tag","Error"+t.getMessage());
}
});
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions.Builder options = NavigationViewOptions.builder()
.navigationListener(this)
.directionsRoute(directionsRoute)
.shouldSimulateRoute(true)
.progressChangeListener(this);
navigationView.startNavigation(options.build());
}
}
|
UTF-8
|
Java
| 11,045 |
java
|
MapsActivity.java
|
Java
|
[
{
"context": " Mapbox.getInstance(this,\n \"pk.eyJ1IjoiemVicmFwdyIsImEiOiJjam9kNTZkMzkwc3RiM3ZvMTNlNHIya2s2In0.DyQaOsbV8AL0kmYR4TF5KQ\");\n setContentView(R.layout.activity_maps)",
"end": 3344,
"score": 0.9996818900108337,
"start": 3255,
"tag": "KEY",
"value": "pk.eyJ1IjoiemVicmFwdyIsImEiOiJjam9kNTZkMzkwc3RiM3ZvMTNlNHIya2s2In0.DyQaOsbV8AL0kmYR4TF5KQ"
},
{
"context": " String username = pref.getString(\"username\", \"\");\n String attraction_id = pre",
"end": 7848,
"score": 0.9911054372787476,
"start": 7840,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package whattodo.whattodo;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.DirectionsCriteria;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.services.android.navigation.ui.v5.NavigationView;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.OnNavigationReadyCallback;
import com.mapbox.services.android.navigation.ui.v5.instruction.InstructionView;
import com.mapbox.services.android.navigation.ui.v5.listeners.NavigationListener;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.navigation.v5.routeprogress.ProgressChangeListener;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgressState;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MapsActivity extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, LocationEngineListener, PermissionsListener, ProgressChangeListener {
private Point origin = Point.fromLngLat( 18.618783,54.372496);
private Point destination = Point.fromLngLat( 18.616432,54.380217);
private NavigationView navigationView;
private InstructionView instructionView;
private PermissionsManager permissionsManager;
private Location originLocation;
private LocationEngine locationEngine;
private DirectionsRoute currentRoute;
private double Long, Lat;
private String attraction_name;
private Boolean endLocation = false;
@Override
@SuppressWarnings("MissingPermission")
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,
"<KEY>");
setContentView(R.layout.activity_maps);
enableLocation();
Location lastLocation = locationEngine.getLastLocation();
locationEngine.activate();
locationEngine.addLocationEngineListener(this);
String location = "";
if (lastLocation != null) {
origin = Point.fromLngLat(originLocation.getLongitude(),originLocation.getLatitude());
}
Intent intent = getIntent();
Long = Double.parseDouble(intent.getStringExtra("Longitude"));
Lat = Double.parseDouble(intent.getStringExtra("Latitude"));
attraction_name = intent.getStringExtra("attraction_name");
instructionView = findViewById(R.id.instructionView);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
navigationView.initialize(this);
}
@Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
@Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
@Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
@Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
@Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
@Override
public void onNavigationReady(boolean isRunning) {
navigationView.findViewById(R.id.feedbackFab).setVisibility(View.GONE);
navigationView.findViewById(R.id.instructionLayout).setEnabled(false);
getRoute();
}
@Override
public void onCancelNavigation() {
onBackPressed();
}
@Override
public void onNavigationFinished() {
}
@Override
public void onNavigationRunning() {
}
@SuppressWarnings("MissingPermission")
private void enableLocation(){
if(permissionsManager.areLocationPermissionsGranted(this)){
initializedLocationEngine();
}else{
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
@SuppressWarnings("MissingPermission")
private void initializedLocationEngine(){
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if(lastLocation!=null){
originLocation = lastLocation;
}else{
locationEngine.addLocationEngineListener(this);
}
}
@SuppressWarnings("MissingPermission")
@Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
if(location!=null){
originLocation = location;
}
}
@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
@Override
public void onPermissionResult(boolean granted) {
if(granted){
enableLocation();
}
}
@Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
if (routeProgress.currentState().equals(RouteProgressState.ROUTE_ARRIVED)) {
if(!endLocation){
endLocation = true;
String name = "nazwa";
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
String username = pref.getString("username", "");
String attraction_id = pref.getString("attraction_id", "");
SharedPreferences.Editor editor = pref.edit();
editor.putString("find","true");
editor.commit();
String url ="https://whattodowebservice.azurewebsites.net/visit?login="+username+"&attractionid="+attraction_id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(stringRequest);
AlertDialog.Builder bulder = new AlertDialog.Builder(MapsActivity.this);
bulder.setMessage("Gratulacje dotarłeś do celu: "+attraction_name+", sprawdź i oceń później")
.setNegativeButton("Ok",null)
.create()
.show();
}
}
}
private void getRoute(){
destination = Point.fromLngLat(Long,Lat);
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if(response.body() == null){
Log.e("tag","No routs found, check right user and access token");
return;
}else if(response.body().routes().size()==0){
Log.e("tag","No routes found");
return;
}
currentRoute = response.body().routes().get(0);
DirectionsRoute directionsRoute = response.body().routes().get(0);
startNavigation(directionsRoute);
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
Log.e("tag","Error"+t.getMessage());
}
});
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions.Builder options = NavigationViewOptions.builder()
.navigationListener(this)
.directionsRoute(directionsRoute)
.shouldSimulateRoute(true)
.progressChangeListener(this);
navigationView.startNavigation(options.build());
}
}
| 10,961 | 0.659752 | 0.653592 | 301 | 35.661129 | 28.20755 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54485 | false | false |
5
|
f5380cd1ddfc7f0c064dfbab33ed72c2e687a8f3
| 16,767,552,326,004 |
7c49aac10d156216f9ce21349e2ba60986c95d0b
|
/centit-utils/src/test/java/com/centit/test/TestNumber.java
|
613f23a335a8aa41f2a16110f952e58c405e9b7f
|
[] |
no_license
|
libanxian2017/centit-commons
|
https://github.com/libanxian2017/centit-commons
|
626c0f8011a9019f36f676ea4823824a640e63f4
|
ea797544275ba63605fce221c1ffe75fc523990b
|
refs/heads/master
| 2020-03-24T20:53:19.422000 | 2018-07-20T08:01:17 | 2018-07-20T08:01:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.centit.test;
import com.centit.support.algorithm.ByteBaseOpt;
public class TestNumber {
public static void main(String[] args) {
byte [] buf = new byte[1024];
short s = (short) 62342;
int n = s & 0xFFFF;
System.out.println(n);
ByteBaseOpt.writeUInt16(buf, s, 0);
System.out.println(s);
System.out.println(ByteBaseOpt.readUInt16(buf, 0));
System.out.println(ByteBaseOpt.readInt16(buf, 0));
}
}
|
UTF-8
|
Java
| 484 |
java
|
TestNumber.java
|
Java
|
[] | null |
[] |
package com.centit.test;
import com.centit.support.algorithm.ByteBaseOpt;
public class TestNumber {
public static void main(String[] args) {
byte [] buf = new byte[1024];
short s = (short) 62342;
int n = s & 0xFFFF;
System.out.println(n);
ByteBaseOpt.writeUInt16(buf, s, 0);
System.out.println(s);
System.out.println(ByteBaseOpt.readUInt16(buf, 0));
System.out.println(ByteBaseOpt.readInt16(buf, 0));
}
}
| 484 | 0.619835 | 0.580579 | 19 | 24.473684 | 20.440847 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false |
5
|
28f339b2454792739b4afefd11ae93d92e6f1d1b
| 24,223,615,601,552 |
0c8eab6349c7f07d0bb67a4a5951f478ba463457
|
/src/main/java/com/systemspecs/evoting/infrastructure/persistence/daoImpl/UserDaoImpl.java
|
708b2e39ced4d43e4ed18fcea69d5d32ef3d9472
|
[] |
no_license
|
unclejide1/e-vote-api
|
https://github.com/unclejide1/e-vote-api
|
641c868e8f22724bab5c279dad5fa1fd73feaef8
|
da193c98a97729c1ff08c5902b1d0320c9bba06f
|
refs/heads/master
| 2023-05-03T15:58:21.591000 | 2021-05-24T09:17:44 | 2021-05-24T09:17:44 | 370,272,094 | 0 | 0 | null | false | 2021-05-24T09:17:44 | 2021-05-24T07:54:42 | 2021-05-24T08:00:21 | 2021-05-24T09:17:44 | 104 | 0 | 0 | 0 |
Java
| false | false |
package com.systemspecs.evoting.infrastructure.persistence.daoImpl;
import com.systemspecs.evoting.domain.dao.UserDao;
import com.systemspecs.evoting.domain.entities.User;
import com.systemspecs.evoting.domain.entities.enums.RecordStatusConstant;
import com.systemspecs.evoting.infrastructure.persistence.repository.UserRepository;
import javax.inject.Named;
import java.util.Optional;
@Named
public class UserDaoImpl extends CrudDaoImpl<User, Long> implements UserDao {
private final UserRepository repository;
public UserDaoImpl(UserRepository repository) {
super(repository);
this.repository = repository;
}
@Override
public User getUserByUsername(String username) {
return findUserByUsername(username).orElseThrow(() -> new RuntimeException("Not Found. User with username: " + username));
}
@Override
public Optional<User> findUserByUsername(String username) {
return repository.findFirstByUsernameAndRecordStatus(username, RecordStatusConstant.ACTIVE);
}
@Override
public Optional<User> findUserByPhoneNumber(String phoneNumber) {
return repository.findFirstByPhoneNumber(phoneNumber);
}
@Override
public Boolean existsByUsername(String username) {
return repository.existsByUsernameAndRecordStatus(username, RecordStatusConstant.ACTIVE);
}
}
|
UTF-8
|
Java
| 1,366 |
java
|
UserDaoImpl.java
|
Java
|
[] | null |
[] |
package com.systemspecs.evoting.infrastructure.persistence.daoImpl;
import com.systemspecs.evoting.domain.dao.UserDao;
import com.systemspecs.evoting.domain.entities.User;
import com.systemspecs.evoting.domain.entities.enums.RecordStatusConstant;
import com.systemspecs.evoting.infrastructure.persistence.repository.UserRepository;
import javax.inject.Named;
import java.util.Optional;
@Named
public class UserDaoImpl extends CrudDaoImpl<User, Long> implements UserDao {
private final UserRepository repository;
public UserDaoImpl(UserRepository repository) {
super(repository);
this.repository = repository;
}
@Override
public User getUserByUsername(String username) {
return findUserByUsername(username).orElseThrow(() -> new RuntimeException("Not Found. User with username: " + username));
}
@Override
public Optional<User> findUserByUsername(String username) {
return repository.findFirstByUsernameAndRecordStatus(username, RecordStatusConstant.ACTIVE);
}
@Override
public Optional<User> findUserByPhoneNumber(String phoneNumber) {
return repository.findFirstByPhoneNumber(phoneNumber);
}
@Override
public Boolean existsByUsername(String username) {
return repository.existsByUsernameAndRecordStatus(username, RecordStatusConstant.ACTIVE);
}
}
| 1,366 | 0.768668 | 0.768668 | 41 | 32.317074 | 34.432285 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414634 | false | false |
5
|
f98fcfc43f626fd8723d59d40dffd16ddb2f035e
| 15,333,033,265,333 |
ec5a0d89271d1b38662cb5c4d8138175a83fefe7
|
/lessons/src/main/java/by/cources/spring/task2/spring/repository/BookRepository.java
|
8bfe8feccd6c2dcefc514ef6043cb6c4a33034cd
|
[] |
no_license
|
valeryKonchevich/sp-courses-exam
|
https://github.com/valeryKonchevich/sp-courses-exam
|
d13441e2f59c70608551cea1f48e82ad6aa0bab9
|
dc99145a849d7d009553a3939f298602387aaf5b
|
refs/heads/master
| 2020-06-07T03:15:37.562000 | 2019-06-19T06:32:54 | 2019-06-19T06:32:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.cources.spring.task2.spring.repository;
import by.cources.spring.task2.spring.model.Book;
import java.util.List;
public interface BookRepository {
List<Book> findAll();
Book findById(Long id);
}
|
UTF-8
|
Java
| 214 |
java
|
BookRepository.java
|
Java
|
[] | null |
[] |
package by.cources.spring.task2.spring.repository;
import by.cources.spring.task2.spring.model.Book;
import java.util.List;
public interface BookRepository {
List<Book> findAll();
Book findById(Long id);
}
| 214 | 0.766355 | 0.757009 | 11 | 18.454546 | 18.787634 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
5
|
992ad0b102e5614d6254f9d2afdcc5177a273715
| 20,882,131,009,979 |
20ecce764db9c243018c14df5470e241a70c74f2
|
/src/RBTree.java
|
cf348d618e69d2551a0b1845706fbb042565ab68
|
[] |
no_license
|
waxnkw/RBTree
|
https://github.com/waxnkw/RBTree
|
eac909989c38caab2ad2b776b3725eed860bb907
|
d15522943d4ff30c3c9b6c08c7ce3fa8be69a1f0
|
refs/heads/master
| 2020-12-09T16:38:52.164000 | 2020-01-12T08:24:49 | 2020-01-12T08:24:49 | 160,765,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.*;
/*
* 输入的语法是:
* RBTree ::== '(' RBTree ',' '(' Integer, COLOR ')' ',' RBTree')'
* | "NIL"
* COLOR ::= Black | Red
*
* 其中的key值都是非负整数。
*/
public class RBTree {
static final String inputPath = "inputs/rb0.in";
static final String outputPath = "outputs/rb0.out";
static final boolean LGN = false;
static final int RED = 0;
static final int BLACK = 1;
static final int INSERT = 3;
static final int DELETE = 4;
int key;
RBTree left, right;
int color; //0--red, 1--black
public RBTree(RBTree l, int k, int c, RBTree r) {
this.left = l;
this.key = k;
this.color = c;
this.right = r;
}
static String[] testCases = {
"(NIL, (1,black), NIL)",
"((NIL, (1,red), NIL), (5,black), (NIL, (7,red), NIL))",
"(NIL, (5,black), (NIL, (7,red), NIL))",
"(NIL, (5,black), (NIL, (4,red), NIL))",
"((NIL, (1,black), NIL), (5,black), (NIL, (7,black), NIL))",
"((NIL, (1,black), NIL), (5,red), (NIL, (7,black), NIL))",
"(((NIL, (1,black), NIL), (5,red), (NIL, (7,black), NIL)), (10, black), (NIL, (12,black), NIL))"
};
/*
* 测试
* 从testCases数组中获得各个测试用例,扫描得到RBT,然后检查BlackHeight约束和Color约束,如果都通过了就输出
*/
public static void main(final String[] args) {
long startTime=System.currentTimeMillis(); //获取结束时间
RBTree rbt = null;
String [] cmds = getLinesFromFile(inputPath);
File outFile = new File(outputPath);
try {
FileWriter writer = new FileWriter(outFile);
for(int i=0; i<cmds.length; i++)
{
String s = cmds[i];
if (s == null || s.length()==0){break;}
int mode = RBTree.analysisCommand(s);
int val = RBTree.getVal(s);
if (mode==RBTree.INSERT){
rbt = RBTree.rbsInsert(rbt,val).newTree;
}
else if (mode==RBTree.DELETE){
rbt = RBTree.rbtDelete(rbt,val);
}
else {System.out.println("error");}
rbt.color = RBTree.BLACK;
//判断时间时不写文件
if (LGN){continue;}
writer.write(rbt.toString()+"\n");
}
if (!LGN){writer.flush();}
else {System.out.println(rbt.toString());}
} catch (IOException e) {
e.printStackTrace();
}
long endTime=System.currentTimeMillis(); //获取结束时间
if (LGN){System.out.println("程序运行时间: "+(endTime-startTime)+"ms");}
}
/****************************************************************************************************/
// 下 我的代码区域
/****************************************************************************************************/
static String[] getLinesFromFile(String path){
File file = new File(path);
BufferedReader reader = null;
String [] ret = null;
try {
reader = new BufferedReader(new FileReader(file));
String num = reader.readLine();
int n = Integer.parseInt(num);
ret= new String[n];
for (int i=0; i<n; i++){
ret[i] = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
/**
* 分析命令模式
* */
static int analysisCommand(String command){
String [] ss = command.split(" ");
if (ss[0].equals("a")){return INSERT;}
if (ss[0].equals("d")){return DELETE;}
return -1;
}
/**
* 得到当前的需要操作的值
* */
static int getVal(String command){
return Integer.parseInt(command.split(" ")[1]);
}
/**
* @param rbt 当前的红黑树
* 输出 树 元素个数 黑高度
* 检查 颜色限制 和 高度限制
* */
static boolean checkRBTree(RBTree rbt){
if (rbt==null){
System.out.println("empty tree");
return true;
}
// System.out.println("Output\t" + rbt.toString());
int h = rbt.getBlackHeight();
boolean colorCheck = rbt.checkColor();
// System.out.println("\tColor constraint " + (colorCheck ? "OK" : "broken"));
// System.out.println("\tBlack height " + (h >= 0 ? " is " + h : "constraint broken"));
// System.out.print("\tElements in tree:");
// RBTree.outputElements_Rec(rbt);
boolean orderCheck = RBTree.checkOrder(rbt);
// System.out.println("\n\tOrder constraint " + (orderCheck ? "OK" : "broken"));
// System.out.println();
return orderCheck&colorCheck;
}
/********************** insert *********************************/
static class InsReturn{
public RBTree newTree;
public int status;
}
static final int ok = 0;
static final int rbr = 1;
static final int brb = 2;
static final int rrb = 3;
static final int brr = 4;
/**
* insert
* @param
* */
static InsReturn rbsInsert(RBTree oldTree, int newNode){
InsReturn ans, ansLeft, ansRight;
if (oldTree==null){
ans = new InsReturn();
RBTree rbt = new RBTree(null, newNode, RED, null);
ans.newTree = rbt;
ans.status = brb;
}
else {
if (newNode<oldTree.key){
ansLeft = rbsInsert(oldTree.left, newNode);
ans = repairLeft(oldTree, ansLeft);
}
else {
ansRight = rbsInsert(oldTree.right, newNode);
ans = repairRight(oldTree, ansRight);
}
}
return ans;
}
/**
* repair left
* */
static InsReturn repairLeft(RBTree oldTree, InsReturn ansLeft){
InsReturn ans = new InsReturn();
if (ansLeft.status == ok){
ans.newTree = oldTree;
ans.status = ok;
}
else{
oldTree.left = ansLeft.newTree;
if (ansLeft.status == rbr){
ans.newTree = oldTree;
ans.status = ok;
}
else if(ansLeft.status==brb){
if (oldTree.color==BLACK){
ans.status=ok;
}
else {
ans.status=rrb;
}
ans.newTree = oldTree;
}
else if (colorOf(oldTree.right)==RED){
colorFlip(oldTree);
ans.newTree = oldTree;
ans.status = brb;
}
else {
ans.newTree = rebalLeft(oldTree, ansLeft.status);
ans.status = rbr;
}
}
return ans;
}
/**
* rebal left
* */
static RBTree rebalLeft(RBTree oldTree, int leftStatus){
RBTree l,m,r,lr,rl;
if (leftStatus == rrb){
r = oldTree;
m = oldTree.left;
l = m.left;
rl = m.right;
r.left = rl;
m.right = r;
}
else {
r = oldTree;
l = oldTree.left;
m = l.right;
lr = m.left;
rl = m.right;
r.left = rl;
l.right = lr;
m.right = r;
m.left = l;
}
l.color = RED;
r.color = RED;
m.color = BLACK;
return m;
}
static InsReturn repairRight(RBTree oldTree, InsReturn ansRight){
InsReturn ans = new InsReturn();
if (ansRight.status == ok){
ans.newTree = oldTree;
ans.status = ok;
}
else{
oldTree.right = ansRight.newTree;
if (ansRight.status == rbr){
ans.newTree = oldTree;
ans.status = ok;
}
else if(ansRight.status==brb){
if (oldTree.color==BLACK){
ans.status=ok;
}
else {
ans.status=brr;
}
ans.newTree = oldTree;
}
else if (colorOf(oldTree.left)==RED){
colorFlip(oldTree);
ans.newTree = oldTree;
ans.status = brb;
}
else {
ans.newTree = rebalRight(oldTree, ansRight.status);
ans.status = rbr;
}
}
return ans;
}
/**
* rebal left
* */
static RBTree rebalRight(RBTree oldTree, int rightStatus){
RBTree l,m,r,lr,rl;
if (rightStatus == rrb){
l = oldTree;
r = oldTree.right;
m = r.left;
lr = m.left;
rl = m.right;
l.right = lr;
m.left = l;
m.right = r;
r.left = rl;
}
else { //brr
l = oldTree;
m = oldTree.right;
r = m.right;
lr = m.left;
l.right = lr;
m.left = l;
}
l.color = RED;
r.color = RED;
m.color = BLACK;
return m;
}
/**
* 翻转颜色
* 当前节点 和 左子节点 右子节点的颜色翻转
* */
static void colorFlip(RBTree rbt){
rbt.color = reverseColor(rbt.color);
if (rbt.left!=null){rbt.left.color = reverseColor(rbt.left.color);}
if (rbt.right!=null){rbt.right.color = reverseColor(rbt.right.color);}
}
static int colorOf(RBTree rbt){
if (rbt == null ){return BLACK;}
return rbt.color;
}
/**
* 得到翻转颜色
* */
static int reverseColor(int color){
if (color==RED){return BLACK;}
return RED;
}
/********************** insert end *********************************/
/********************** delete begin *********************************/
/**
* @param val 删除的节点
* */
static RBTree rbtDelete(RBTree rbt,int val){
RBTree cur = rbt;
RBTree parent = null;
boolean needAdj = false;
int subs = val;
//找到节点位置,若能直接删除则删除,不能的话留待调整时递归删除
while(true){
if (cur == null){
System.out.println("don't contain " + val);
return rbt;
}
if (val == cur.key){
//只有一个根节点
if (parent==null && isLeaf(cur)){
return null;
}
//红叶节点: 删掉就行
else if (isLeaf(cur) && cur.color==RED){
if (parent.left==cur){parent.left = null;}
else {parent.right = null;}
return rbt;
}
//无左子树,有右红子树: 红节点补上就行
else if (cur.left == null && cur.right!=null){
cur.key = cur.right.key;
cur.right = null;
return rbt;
}
else if (isLeaf(cur) && cur.color==BLACK){
needAdj = true;
break;
}
//有左子树
else if (cur.left != null){
RBTree deleteNode = findLeftMax(cur);
//左子树的max有左红节点: 左红节点补上即可
if (deleteNode.left != null && deleteNode.left.color==RED){
subs = deleteNode.key;
deleteNode.key = deleteNode.left.key;
deleteNode.left = null;
break;
}
//左max红节点: 后面调整时直接删掉
else if (isLeaf(deleteNode) && deleteNode.color == RED){
subs = deleteNode.key;
needAdj = true;
break;
}
else if (isLeaf(deleteNode) && deleteNode.color == BLACK){
subs = deleteNode.key;
needAdj = true;
break;
}
}
}
if (val < cur.key){
parent = cur;
cur = cur.left;
}
if (val > cur.key){
parent = cur;
cur = cur.right;
}
}
//不需要调整
if (needAdj){
// cur.key = subs;
rbt = delNode(rbt, subs).newTree;
}
cur.key = subs;
return rbt;
}
static final int LOW = 1;
static final int OK = 0;
/**
*
* */
static class DelReturn{
public RBTree newTree;
public int status;
}
/**
*
* */
static DelReturn delNode(RBTree oldTree, int toDelete){
DelReturn ans, ansLeft, ansRight;
if (toDelete<oldTree.key){
ansLeft = delNode(oldTree.left, toDelete);
ans = adjLeft(oldTree, ansLeft);
}
else if (toDelete>oldTree.key){
ansRight = delNode(oldTree.right, toDelete);
ans = adjRight(oldTree, ansRight);
}
//相等时要删掉
else {
ans = new DelReturn();
ans.newTree = null;
if (oldTree.color == BLACK){
ans.status = LOW;
}
//红节点,调整时直接删除
else {
ans.status = OK;
}
}
return ans;
}
static DelReturn adjLeft(RBTree oldTree, DelReturn ansLeft){
DelReturn ret;
oldTree.left = ansLeft.newTree;
// ok的子树高度,无需处理直接返回
if (ansLeft.status==OK){
ret = new DelReturn();
ret.newTree = oldTree;
ret.status = OK;
return ret;
}
//左子树比较低
if (ansLeft.status == LOW){
return delRebalLeft(oldTree);
}
return null;
}
static DelReturn delRebalLeft(RBTree rbt){
DelReturn ret = new DelReturn();
RBTree g,p,s,l,r,ll,lr;
g = rbt.left;
p = rbt;
s = p.right;
l = s!=null?s.left:null;
r = s!=null?s.right:null;
if (colorOf(l)==RED){
ll = l.left;
lr = l.right;
l.color = p.color;
p.color = BLACK;
l.left = p;
p.left = g;
p.right = ll;
s.left =lr;
l.right = s;
ret.newTree = l;
ret.status =OK;
}
else if (colorOf(p)==RED){
s.left = p;
p.left = g;
p.right = l;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(r)==RED){
r.color = BLACK;
s.left = p;
p.right = l;
s.right = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(s)==RED){
s.color = BLACK;
p.color = RED;
s.left = p;
p.right = l;
s.left = delRebalLeft(p).newTree;
ret.newTree = s;
ret.status =OK;
}
else{
s.color = RED;
ret.newTree = p;
ret.status =LOW;
}
return ret;
}
static DelReturn adjRight(RBTree oldTree, DelReturn ansRight){
DelReturn ret;
oldTree.right = ansRight.newTree;
// ok的子树高度,无需处理直接返回
if (ansRight.status==OK){
ret = new DelReturn();
ret.newTree = oldTree;
ret.status = OK;
return ret;
}
//左子树比较低
if (ansRight.status == LOW){
return delRebalRight(oldTree);
}
return null;
}
static DelReturn delRebalRight(RBTree rbt){
DelReturn ret = new DelReturn();
RBTree g,p,s,l,r,ll,lr,rl,rr;
g = rbt.right;
p = rbt;
s = p.left;
l = s!=null?s.left:null;
r = s!=null?s.right:null;
if (colorOf(r)==RED){
rl = r.left;
rr = r.right;
r.color = p.color;
p.color = BLACK;
r.left = s;
s.right = rl;
r.right = p;
p.left = rr;
ret.newTree = r;
ret.status =OK;
}
else if (colorOf(p)==RED){
s.right = p;
p.left = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(l)==RED){
l.color = BLACK;
s.left = l;
s.right = p;
p.left = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(s)==RED){
s.color =BLACK;
p.color = RED;
s.right = p;
p.left = r;
s.right = delRebalRight(p).newTree;
ret.newTree = s;
ret.status =OK;
}
else{
s.color = RED;
ret.newTree = p;
ret.status =LOW;
}
return ret;
}
/**
* 是不是叶节点
* */
static boolean isLeaf(RBTree rbTree){
return rbTree.left==null && rbTree.right==null;
}
/**
* 找到左子树最大值
* */
static RBTree findLeftMax(RBTree rbt){
RBTree cur = rbt.left;
while (cur.right != null){
cur = cur.right;
}
return cur;
}
/********************** delete end *********************************/
/****************************************************************************************************/
// 上 我的代码区域
/****************************************************************************************************/
/*
* 获取Black Height,如果不满足定义(即两棵子树的高度不同),则返回-1;
* 即这个函数同时也可以检查高度约束。
*/
int getBlackHeight()
{
int lHeight;
if(this.left == null)
lHeight = 1;
else
{
lHeight = this.left.getBlackHeight();
if(lHeight < 0)
return -1;
}
int rHeight;
if(this.right == null)
rHeight = 1;
else
{
rHeight = this.right.getBlackHeight();
if(rHeight < 0)
return -1;
}
if(lHeight == rHeight)
return lHeight + (this.color == BLACK ? 1 : 0);
return -1;
}
private static boolean checkOrder(RBTree rbt)
{
curValue = -1;
return checkOrder_Rec(rbt);
}
/*
* 递归地检查大小约束,以中根序遍历红黑树,检查各个结点的key是否递增的。
*/
private static int curValue;
private static boolean checkOrder_Rec(RBTree rbt)
{
if(rbt == null)
return true;
if(!checkOrder_Rec(rbt.left))
return false;
if(rbt.key < curValue)
return false;
curValue = rbt.key;
if(!checkOrder_Rec(rbt.right))
return false;
return true;
}
private static boolean outputElements_Rec(RBTree rbt)
{
if(rbt == null)
return true;
if(!outputElements_Rec(rbt.left))
return false;
System.out.print("\t" + rbt.key);
if(!outputElements_Rec(rbt.right))
return false;
return true;
}
/*
* 检查颜色约束, 但是根节点可以是红色(也就是说,可能是ARB树)
*/
boolean checkColor()
{
int leftColor;
if(this.left == null)
leftColor = BLACK;
else
{
if(!this.left.checkColor())
return false;
leftColor = this.left.color;
}
int rightColor;
if(this.right == null)
rightColor = BLACK;
else
{
if(!this.right.checkColor())
return false;
rightColor = this.right.color;
}
if(this.color == BLACK)
return true;
if(leftColor == RED || rightColor == RED)
return false;
return true;
}
public String toString()
{
String s = "(";
if(this.left == null)
s += "NIL";
else
s += this.left.toString();
s += ", (";
s += "" + this.key + "," + (this.color == RED ? "red" : "black") + "), ";
if(this.right == null)
s += "NIL";
else
s += this.right.toString();
s += ")";
return s;
}
static String errorMsg;
static int nextChar;
static int nextPos;
static char[] inputBuf;
static String scannedInput;
/*
* 扫描分析s,获得一棵红黑树
*/
static RBTree getRBTFromString(String s)
{
inputBuf = s.toCharArray();
errorMsg = null;
nextChar = inputBuf[0];
nextPos = 0;
RBTree rbt = getRBTFromInput_Rec();
if(errorMsg != null)
{
System.out.println("\t" + s.substring(0,nextPos));
System.out.println("\t" + errorMsg);
return null;
}
return rbt;
}
/****************************************************************************************************/
//后面的代码都是用于扫描的子程序,不需要细看,有问题在QQ反映
/****************************************************************************************************/
private static RBTree getRBTFromInput_Rec()
{
if(tryToGetNIL())
return null;
getLeftPara();
if(errorMsg != null)
return null;
RBTree left = getRBTFromInput_Rec();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
getLeftPara();
if(errorMsg != null)
return null;
int key = getInteger();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
int color = getCOLOR();
if(errorMsg != null)
return null;
getRightPara();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
RBTree right = getRBTFromInput_Rec();
if(errorMsg != null)
return null;
getRightPara();
if(errorMsg != null)
return null;
return new RBTree(left, key, color, right);
}
private static void getCOMMA() {
skipBlank();
if(nextChar == ',')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\',\' expected!";
}
}
private static void getLeftPara() {
skipBlank();
if(nextChar == '(')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\'(\' expected!";
}
}
private static void getRightPara() {
skipBlank();
if(nextChar == ')')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\')\' expected!";
}
}
static private boolean tryToGetNIL() {
int prevPos = nextPos;
skipBlank();
String id = getID();
if ("NIL".equals(id))
return true;
nextPos = prevPos;
nextChar = nextPos < inputBuf.length ? inputBuf[nextPos] : -1;
// errorMsg = "\"NIL\" expected.";
return false;
}
private static int getCOLOR() {
skipBlank();
String id = getID();
if("black".equals(id))
return BLACK;
else if("red".equals(id))
return RED;
else
errorMsg = "Black/Red expected.";
return -1;
}
private static String getID() {
String ret = "";
while((nextChar >= 'a' && nextChar <= 'z')|| (nextChar >= 'A' && nextChar <= 'Z'))
{
ret += (char)nextChar;
nextChar = getAChar();
}
return ret;
}
private static int getInteger() {
int ret = 0;
while(nextChar >= '0' && nextChar <= '9')
{
ret = ret * 10 + (nextChar - '0');
nextChar = getAChar();
}
if((nextChar >= 'a' && nextChar <= 'z')|| (nextChar >= 'A' && nextChar == 'Z'))
{
errorMsg = "A char following an integer.";
}
return ret;
}
private static void skipBlank() {
while(nextChar == ' ' || nextChar == '\n' || nextChar == '\t')
nextChar = getAChar();
}
private static int getAChar()
{
nextPos ++;
if(nextPos >= inputBuf.length)
nextChar = -1;
else
nextChar = inputBuf[nextPos];
return nextChar;
}
private static String getALineFromInput() {
String ret = "";
for(;;)
{
int nChar;
try {
nChar = System.in.read();
} catch (IOException e) {
return null;
}
if(nChar == '\n')
break;
ret += (char)nChar;
}
return ret;
}
}
|
UTF-8
|
Java
| 26,156 |
java
|
RBTree.java
|
Java
|
[
{
"context": "l)\n return null;\n\n int key = getInteger();\n if(errorMsg != null)\n retur",
"end": 21683,
"score": 0.604166567325592,
"start": 21676,
"tag": "KEY",
"value": "Integer"
}
] | null |
[] |
import java.io.*;
/*
* 输入的语法是:
* RBTree ::== '(' RBTree ',' '(' Integer, COLOR ')' ',' RBTree')'
* | "NIL"
* COLOR ::= Black | Red
*
* 其中的key值都是非负整数。
*/
public class RBTree {
static final String inputPath = "inputs/rb0.in";
static final String outputPath = "outputs/rb0.out";
static final boolean LGN = false;
static final int RED = 0;
static final int BLACK = 1;
static final int INSERT = 3;
static final int DELETE = 4;
int key;
RBTree left, right;
int color; //0--red, 1--black
public RBTree(RBTree l, int k, int c, RBTree r) {
this.left = l;
this.key = k;
this.color = c;
this.right = r;
}
static String[] testCases = {
"(NIL, (1,black), NIL)",
"((NIL, (1,red), NIL), (5,black), (NIL, (7,red), NIL))",
"(NIL, (5,black), (NIL, (7,red), NIL))",
"(NIL, (5,black), (NIL, (4,red), NIL))",
"((NIL, (1,black), NIL), (5,black), (NIL, (7,black), NIL))",
"((NIL, (1,black), NIL), (5,red), (NIL, (7,black), NIL))",
"(((NIL, (1,black), NIL), (5,red), (NIL, (7,black), NIL)), (10, black), (NIL, (12,black), NIL))"
};
/*
* 测试
* 从testCases数组中获得各个测试用例,扫描得到RBT,然后检查BlackHeight约束和Color约束,如果都通过了就输出
*/
public static void main(final String[] args) {
long startTime=System.currentTimeMillis(); //获取结束时间
RBTree rbt = null;
String [] cmds = getLinesFromFile(inputPath);
File outFile = new File(outputPath);
try {
FileWriter writer = new FileWriter(outFile);
for(int i=0; i<cmds.length; i++)
{
String s = cmds[i];
if (s == null || s.length()==0){break;}
int mode = RBTree.analysisCommand(s);
int val = RBTree.getVal(s);
if (mode==RBTree.INSERT){
rbt = RBTree.rbsInsert(rbt,val).newTree;
}
else if (mode==RBTree.DELETE){
rbt = RBTree.rbtDelete(rbt,val);
}
else {System.out.println("error");}
rbt.color = RBTree.BLACK;
//判断时间时不写文件
if (LGN){continue;}
writer.write(rbt.toString()+"\n");
}
if (!LGN){writer.flush();}
else {System.out.println(rbt.toString());}
} catch (IOException e) {
e.printStackTrace();
}
long endTime=System.currentTimeMillis(); //获取结束时间
if (LGN){System.out.println("程序运行时间: "+(endTime-startTime)+"ms");}
}
/****************************************************************************************************/
// 下 我的代码区域
/****************************************************************************************************/
static String[] getLinesFromFile(String path){
File file = new File(path);
BufferedReader reader = null;
String [] ret = null;
try {
reader = new BufferedReader(new FileReader(file));
String num = reader.readLine();
int n = Integer.parseInt(num);
ret= new String[n];
for (int i=0; i<n; i++){
ret[i] = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
/**
* 分析命令模式
* */
static int analysisCommand(String command){
String [] ss = command.split(" ");
if (ss[0].equals("a")){return INSERT;}
if (ss[0].equals("d")){return DELETE;}
return -1;
}
/**
* 得到当前的需要操作的值
* */
static int getVal(String command){
return Integer.parseInt(command.split(" ")[1]);
}
/**
* @param rbt 当前的红黑树
* 输出 树 元素个数 黑高度
* 检查 颜色限制 和 高度限制
* */
static boolean checkRBTree(RBTree rbt){
if (rbt==null){
System.out.println("empty tree");
return true;
}
// System.out.println("Output\t" + rbt.toString());
int h = rbt.getBlackHeight();
boolean colorCheck = rbt.checkColor();
// System.out.println("\tColor constraint " + (colorCheck ? "OK" : "broken"));
// System.out.println("\tBlack height " + (h >= 0 ? " is " + h : "constraint broken"));
// System.out.print("\tElements in tree:");
// RBTree.outputElements_Rec(rbt);
boolean orderCheck = RBTree.checkOrder(rbt);
// System.out.println("\n\tOrder constraint " + (orderCheck ? "OK" : "broken"));
// System.out.println();
return orderCheck&colorCheck;
}
/********************** insert *********************************/
static class InsReturn{
public RBTree newTree;
public int status;
}
static final int ok = 0;
static final int rbr = 1;
static final int brb = 2;
static final int rrb = 3;
static final int brr = 4;
/**
* insert
* @param
* */
static InsReturn rbsInsert(RBTree oldTree, int newNode){
InsReturn ans, ansLeft, ansRight;
if (oldTree==null){
ans = new InsReturn();
RBTree rbt = new RBTree(null, newNode, RED, null);
ans.newTree = rbt;
ans.status = brb;
}
else {
if (newNode<oldTree.key){
ansLeft = rbsInsert(oldTree.left, newNode);
ans = repairLeft(oldTree, ansLeft);
}
else {
ansRight = rbsInsert(oldTree.right, newNode);
ans = repairRight(oldTree, ansRight);
}
}
return ans;
}
/**
* repair left
* */
static InsReturn repairLeft(RBTree oldTree, InsReturn ansLeft){
InsReturn ans = new InsReturn();
if (ansLeft.status == ok){
ans.newTree = oldTree;
ans.status = ok;
}
else{
oldTree.left = ansLeft.newTree;
if (ansLeft.status == rbr){
ans.newTree = oldTree;
ans.status = ok;
}
else if(ansLeft.status==brb){
if (oldTree.color==BLACK){
ans.status=ok;
}
else {
ans.status=rrb;
}
ans.newTree = oldTree;
}
else if (colorOf(oldTree.right)==RED){
colorFlip(oldTree);
ans.newTree = oldTree;
ans.status = brb;
}
else {
ans.newTree = rebalLeft(oldTree, ansLeft.status);
ans.status = rbr;
}
}
return ans;
}
/**
* rebal left
* */
static RBTree rebalLeft(RBTree oldTree, int leftStatus){
RBTree l,m,r,lr,rl;
if (leftStatus == rrb){
r = oldTree;
m = oldTree.left;
l = m.left;
rl = m.right;
r.left = rl;
m.right = r;
}
else {
r = oldTree;
l = oldTree.left;
m = l.right;
lr = m.left;
rl = m.right;
r.left = rl;
l.right = lr;
m.right = r;
m.left = l;
}
l.color = RED;
r.color = RED;
m.color = BLACK;
return m;
}
static InsReturn repairRight(RBTree oldTree, InsReturn ansRight){
InsReturn ans = new InsReturn();
if (ansRight.status == ok){
ans.newTree = oldTree;
ans.status = ok;
}
else{
oldTree.right = ansRight.newTree;
if (ansRight.status == rbr){
ans.newTree = oldTree;
ans.status = ok;
}
else if(ansRight.status==brb){
if (oldTree.color==BLACK){
ans.status=ok;
}
else {
ans.status=brr;
}
ans.newTree = oldTree;
}
else if (colorOf(oldTree.left)==RED){
colorFlip(oldTree);
ans.newTree = oldTree;
ans.status = brb;
}
else {
ans.newTree = rebalRight(oldTree, ansRight.status);
ans.status = rbr;
}
}
return ans;
}
/**
* rebal left
* */
static RBTree rebalRight(RBTree oldTree, int rightStatus){
RBTree l,m,r,lr,rl;
if (rightStatus == rrb){
l = oldTree;
r = oldTree.right;
m = r.left;
lr = m.left;
rl = m.right;
l.right = lr;
m.left = l;
m.right = r;
r.left = rl;
}
else { //brr
l = oldTree;
m = oldTree.right;
r = m.right;
lr = m.left;
l.right = lr;
m.left = l;
}
l.color = RED;
r.color = RED;
m.color = BLACK;
return m;
}
/**
* 翻转颜色
* 当前节点 和 左子节点 右子节点的颜色翻转
* */
static void colorFlip(RBTree rbt){
rbt.color = reverseColor(rbt.color);
if (rbt.left!=null){rbt.left.color = reverseColor(rbt.left.color);}
if (rbt.right!=null){rbt.right.color = reverseColor(rbt.right.color);}
}
static int colorOf(RBTree rbt){
if (rbt == null ){return BLACK;}
return rbt.color;
}
/**
* 得到翻转颜色
* */
static int reverseColor(int color){
if (color==RED){return BLACK;}
return RED;
}
/********************** insert end *********************************/
/********************** delete begin *********************************/
/**
* @param val 删除的节点
* */
static RBTree rbtDelete(RBTree rbt,int val){
RBTree cur = rbt;
RBTree parent = null;
boolean needAdj = false;
int subs = val;
//找到节点位置,若能直接删除则删除,不能的话留待调整时递归删除
while(true){
if (cur == null){
System.out.println("don't contain " + val);
return rbt;
}
if (val == cur.key){
//只有一个根节点
if (parent==null && isLeaf(cur)){
return null;
}
//红叶节点: 删掉就行
else if (isLeaf(cur) && cur.color==RED){
if (parent.left==cur){parent.left = null;}
else {parent.right = null;}
return rbt;
}
//无左子树,有右红子树: 红节点补上就行
else if (cur.left == null && cur.right!=null){
cur.key = cur.right.key;
cur.right = null;
return rbt;
}
else if (isLeaf(cur) && cur.color==BLACK){
needAdj = true;
break;
}
//有左子树
else if (cur.left != null){
RBTree deleteNode = findLeftMax(cur);
//左子树的max有左红节点: 左红节点补上即可
if (deleteNode.left != null && deleteNode.left.color==RED){
subs = deleteNode.key;
deleteNode.key = deleteNode.left.key;
deleteNode.left = null;
break;
}
//左max红节点: 后面调整时直接删掉
else if (isLeaf(deleteNode) && deleteNode.color == RED){
subs = deleteNode.key;
needAdj = true;
break;
}
else if (isLeaf(deleteNode) && deleteNode.color == BLACK){
subs = deleteNode.key;
needAdj = true;
break;
}
}
}
if (val < cur.key){
parent = cur;
cur = cur.left;
}
if (val > cur.key){
parent = cur;
cur = cur.right;
}
}
//不需要调整
if (needAdj){
// cur.key = subs;
rbt = delNode(rbt, subs).newTree;
}
cur.key = subs;
return rbt;
}
static final int LOW = 1;
static final int OK = 0;
/**
*
* */
static class DelReturn{
public RBTree newTree;
public int status;
}
/**
*
* */
static DelReturn delNode(RBTree oldTree, int toDelete){
DelReturn ans, ansLeft, ansRight;
if (toDelete<oldTree.key){
ansLeft = delNode(oldTree.left, toDelete);
ans = adjLeft(oldTree, ansLeft);
}
else if (toDelete>oldTree.key){
ansRight = delNode(oldTree.right, toDelete);
ans = adjRight(oldTree, ansRight);
}
//相等时要删掉
else {
ans = new DelReturn();
ans.newTree = null;
if (oldTree.color == BLACK){
ans.status = LOW;
}
//红节点,调整时直接删除
else {
ans.status = OK;
}
}
return ans;
}
static DelReturn adjLeft(RBTree oldTree, DelReturn ansLeft){
DelReturn ret;
oldTree.left = ansLeft.newTree;
// ok的子树高度,无需处理直接返回
if (ansLeft.status==OK){
ret = new DelReturn();
ret.newTree = oldTree;
ret.status = OK;
return ret;
}
//左子树比较低
if (ansLeft.status == LOW){
return delRebalLeft(oldTree);
}
return null;
}
static DelReturn delRebalLeft(RBTree rbt){
DelReturn ret = new DelReturn();
RBTree g,p,s,l,r,ll,lr;
g = rbt.left;
p = rbt;
s = p.right;
l = s!=null?s.left:null;
r = s!=null?s.right:null;
if (colorOf(l)==RED){
ll = l.left;
lr = l.right;
l.color = p.color;
p.color = BLACK;
l.left = p;
p.left = g;
p.right = ll;
s.left =lr;
l.right = s;
ret.newTree = l;
ret.status =OK;
}
else if (colorOf(p)==RED){
s.left = p;
p.left = g;
p.right = l;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(r)==RED){
r.color = BLACK;
s.left = p;
p.right = l;
s.right = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(s)==RED){
s.color = BLACK;
p.color = RED;
s.left = p;
p.right = l;
s.left = delRebalLeft(p).newTree;
ret.newTree = s;
ret.status =OK;
}
else{
s.color = RED;
ret.newTree = p;
ret.status =LOW;
}
return ret;
}
static DelReturn adjRight(RBTree oldTree, DelReturn ansRight){
DelReturn ret;
oldTree.right = ansRight.newTree;
// ok的子树高度,无需处理直接返回
if (ansRight.status==OK){
ret = new DelReturn();
ret.newTree = oldTree;
ret.status = OK;
return ret;
}
//左子树比较低
if (ansRight.status == LOW){
return delRebalRight(oldTree);
}
return null;
}
static DelReturn delRebalRight(RBTree rbt){
DelReturn ret = new DelReturn();
RBTree g,p,s,l,r,ll,lr,rl,rr;
g = rbt.right;
p = rbt;
s = p.left;
l = s!=null?s.left:null;
r = s!=null?s.right:null;
if (colorOf(r)==RED){
rl = r.left;
rr = r.right;
r.color = p.color;
p.color = BLACK;
r.left = s;
s.right = rl;
r.right = p;
p.left = rr;
ret.newTree = r;
ret.status =OK;
}
else if (colorOf(p)==RED){
s.right = p;
p.left = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(l)==RED){
l.color = BLACK;
s.left = l;
s.right = p;
p.left = r;
ret.newTree = s;
ret.status =OK;
}
else if (colorOf(s)==RED){
s.color =BLACK;
p.color = RED;
s.right = p;
p.left = r;
s.right = delRebalRight(p).newTree;
ret.newTree = s;
ret.status =OK;
}
else{
s.color = RED;
ret.newTree = p;
ret.status =LOW;
}
return ret;
}
/**
* 是不是叶节点
* */
static boolean isLeaf(RBTree rbTree){
return rbTree.left==null && rbTree.right==null;
}
/**
* 找到左子树最大值
* */
static RBTree findLeftMax(RBTree rbt){
RBTree cur = rbt.left;
while (cur.right != null){
cur = cur.right;
}
return cur;
}
/********************** delete end *********************************/
/****************************************************************************************************/
// 上 我的代码区域
/****************************************************************************************************/
/*
* 获取Black Height,如果不满足定义(即两棵子树的高度不同),则返回-1;
* 即这个函数同时也可以检查高度约束。
*/
int getBlackHeight()
{
int lHeight;
if(this.left == null)
lHeight = 1;
else
{
lHeight = this.left.getBlackHeight();
if(lHeight < 0)
return -1;
}
int rHeight;
if(this.right == null)
rHeight = 1;
else
{
rHeight = this.right.getBlackHeight();
if(rHeight < 0)
return -1;
}
if(lHeight == rHeight)
return lHeight + (this.color == BLACK ? 1 : 0);
return -1;
}
private static boolean checkOrder(RBTree rbt)
{
curValue = -1;
return checkOrder_Rec(rbt);
}
/*
* 递归地检查大小约束,以中根序遍历红黑树,检查各个结点的key是否递增的。
*/
private static int curValue;
private static boolean checkOrder_Rec(RBTree rbt)
{
if(rbt == null)
return true;
if(!checkOrder_Rec(rbt.left))
return false;
if(rbt.key < curValue)
return false;
curValue = rbt.key;
if(!checkOrder_Rec(rbt.right))
return false;
return true;
}
private static boolean outputElements_Rec(RBTree rbt)
{
if(rbt == null)
return true;
if(!outputElements_Rec(rbt.left))
return false;
System.out.print("\t" + rbt.key);
if(!outputElements_Rec(rbt.right))
return false;
return true;
}
/*
* 检查颜色约束, 但是根节点可以是红色(也就是说,可能是ARB树)
*/
boolean checkColor()
{
int leftColor;
if(this.left == null)
leftColor = BLACK;
else
{
if(!this.left.checkColor())
return false;
leftColor = this.left.color;
}
int rightColor;
if(this.right == null)
rightColor = BLACK;
else
{
if(!this.right.checkColor())
return false;
rightColor = this.right.color;
}
if(this.color == BLACK)
return true;
if(leftColor == RED || rightColor == RED)
return false;
return true;
}
public String toString()
{
String s = "(";
if(this.left == null)
s += "NIL";
else
s += this.left.toString();
s += ", (";
s += "" + this.key + "," + (this.color == RED ? "red" : "black") + "), ";
if(this.right == null)
s += "NIL";
else
s += this.right.toString();
s += ")";
return s;
}
static String errorMsg;
static int nextChar;
static int nextPos;
static char[] inputBuf;
static String scannedInput;
/*
* 扫描分析s,获得一棵红黑树
*/
static RBTree getRBTFromString(String s)
{
inputBuf = s.toCharArray();
errorMsg = null;
nextChar = inputBuf[0];
nextPos = 0;
RBTree rbt = getRBTFromInput_Rec();
if(errorMsg != null)
{
System.out.println("\t" + s.substring(0,nextPos));
System.out.println("\t" + errorMsg);
return null;
}
return rbt;
}
/****************************************************************************************************/
//后面的代码都是用于扫描的子程序,不需要细看,有问题在QQ反映
/****************************************************************************************************/
private static RBTree getRBTFromInput_Rec()
{
if(tryToGetNIL())
return null;
getLeftPara();
if(errorMsg != null)
return null;
RBTree left = getRBTFromInput_Rec();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
getLeftPara();
if(errorMsg != null)
return null;
int key = getInteger();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
int color = getCOLOR();
if(errorMsg != null)
return null;
getRightPara();
if(errorMsg != null)
return null;
getCOMMA();
if(errorMsg != null)
return null;
RBTree right = getRBTFromInput_Rec();
if(errorMsg != null)
return null;
getRightPara();
if(errorMsg != null)
return null;
return new RBTree(left, key, color, right);
}
private static void getCOMMA() {
skipBlank();
if(nextChar == ',')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\',\' expected!";
}
}
private static void getLeftPara() {
skipBlank();
if(nextChar == '(')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\'(\' expected!";
}
}
private static void getRightPara() {
skipBlank();
if(nextChar == ')')
{
nextChar = getAChar();
skipBlank();
}
else
{
errorMsg = "\')\' expected!";
}
}
static private boolean tryToGetNIL() {
int prevPos = nextPos;
skipBlank();
String id = getID();
if ("NIL".equals(id))
return true;
nextPos = prevPos;
nextChar = nextPos < inputBuf.length ? inputBuf[nextPos] : -1;
// errorMsg = "\"NIL\" expected.";
return false;
}
private static int getCOLOR() {
skipBlank();
String id = getID();
if("black".equals(id))
return BLACK;
else if("red".equals(id))
return RED;
else
errorMsg = "Black/Red expected.";
return -1;
}
private static String getID() {
String ret = "";
while((nextChar >= 'a' && nextChar <= 'z')|| (nextChar >= 'A' && nextChar <= 'Z'))
{
ret += (char)nextChar;
nextChar = getAChar();
}
return ret;
}
private static int getInteger() {
int ret = 0;
while(nextChar >= '0' && nextChar <= '9')
{
ret = ret * 10 + (nextChar - '0');
nextChar = getAChar();
}
if((nextChar >= 'a' && nextChar <= 'z')|| (nextChar >= 'A' && nextChar == 'Z'))
{
errorMsg = "A char following an integer.";
}
return ret;
}
private static void skipBlank() {
while(nextChar == ' ' || nextChar == '\n' || nextChar == '\t')
nextChar = getAChar();
}
private static int getAChar()
{
nextPos ++;
if(nextPos >= inputBuf.length)
nextChar = -1;
else
nextChar = inputBuf[nextPos];
return nextChar;
}
private static String getALineFromInput() {
String ret = "";
for(;;)
{
int nChar;
try {
nChar = System.in.read();
} catch (IOException e) {
return null;
}
if(nChar == '\n')
break;
ret += (char)nChar;
}
return ret;
}
}
| 26,156 | 0.426978 | 0.424309 | 991 | 24.330978 | 19.008453 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602422 | false | false |
5
|
af529888af692a8f2b49137f6fd1956af92839cc
| 30,769,145,721,058 |
a1cd57508e90ac4852a6c692e94ce05a6bdf8386
|
/TelegramSimulator/src/java/id/dni/pvim/ext/sim/telegram/GetUpdatesServlet.java
|
1f570837d0485cb4ddf7dbd97185350d32cd748c
|
[] |
no_license
|
darryldn/pvimjalin1
|
https://github.com/darryldn/pvimjalin1
|
6e3f831377d26444cffc1b95e7bc8a534caba211
|
cc0f6ff7b22419304f84cf541dac00488a62b4b4
|
refs/heads/master
| 2020-03-19T09:19:49.561000 | 2018-11-02T09:59:53 | 2018-11-02T09:59:53 | 136,278,926 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package id.dni.pvim.ext.sim.telegram;
import com.google.gson.Gson;
import id.dni.pvim.ext.telegram.pojo.TelegramGetUpdatesPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageChatPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageContentPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageFromPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramUpdateObjPOJO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author darryl.sulistyan
*/
@WebServlet(name = "GetUpdatesServlet", urlPatterns = {"/getUpdates/*"})
public class GetUpdatesServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
long offset;
try {
offset = Long.parseLong(request.getParameter("offset"));
} catch (Exception ex) {
offset = 0;
}
List<Chat> chats = ChatRepository.getInstance().getChats();
List<Chat> newChat = new ArrayList<>();
TelegramGetUpdatesPOJO getUpdates = new TelegramGetUpdatesPOJO();
getUpdates.setOk(true);
getUpdates.setResult(new ArrayList<>());
for (Chat chat : chats) {
long updateID = chat.getUpdateID();
if (updateID >= offset) {
TelegramUpdateObjPOJO m = new TelegramUpdateObjPOJO();
m.setUpdate_id(chat.getUpdateID());
TelegramMessageContentPOJO c = new TelegramMessageContentPOJO();
c.setMessage_id(60);
c.setDate(chat.getDate());
c.setText(chat.getText());
TelegramMessageChatPOJO pc = new TelegramMessageChatPOJO();
pc.setFirst_name("whatever");
pc.setLast_name("whatever 2");
pc.setType("private");
pc.setId(chat.getChatID());
TelegramMessageFromPOJO mf = new TelegramMessageFromPOJO();
mf.setFirst_name("whatever");
mf.setLast_name("whatever 2");
mf.setId(chat.getChatID());
mf.setIs_bot(false);
mf.setLanguage_code("en-us");
c.setChat(pc);
c.setFrom(mf);
m.setMessage(c);
getUpdates.getResult().add(m);
newChat.add(chat);
}
}
ChatRepository.getInstance().getChats().clear();
ChatRepository.getInstance().getChats().addAll(newChat);
Gson gson = new Gson();
String json = gson.toJson(getUpdates);
out.write(json);
out.flush();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
UTF-8
|
Java
| 5,246 |
java
|
GetUpdatesServlet.java
|
Java
|
[
{
"context": "t.http.HttpServletResponse;\r\n\r\n/**\r\n *\r\n * @author darryl.sulistyan\r\n */\r\n@WebServlet(name = \"GetUpdatesServlet\", url",
"end": 945,
"score": 0.9986120462417603,
"start": 929,
"tag": "NAME",
"value": "darryl.sulistyan"
},
{
"context": "hatPOJO();\r\n pc.setFirst_name(\"whatever\");\r\n pc.setLast_name(\"whatever",
"end": 2849,
"score": 0.9873771667480469,
"start": 2841,
"tag": "NAME",
"value": "whatever"
},
{
"context": "whatever\");\r\n pc.setLast_name(\"whatever 2\");\r\n pc.setType(\"private\");\r\n ",
"end": 2901,
"score": 0.8990951776504517,
"start": 2891,
"tag": "NAME",
"value": "whatever 2"
},
{
"context": "romPOJO();\r\n mf.setFirst_name(\"whatever\");\r\n mf.setLast_name(\"whatever",
"end": 3128,
"score": 0.9934000968933105,
"start": 3120,
"tag": "NAME",
"value": "whatever"
},
{
"context": "whatever\");\r\n mf.setLast_name(\"whatever 2\");\r\n mf.setId(chat.getChatID()",
"end": 3180,
"score": 0.9218340516090393,
"start": 3170,
"tag": "NAME",
"value": "whatever 2"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package id.dni.pvim.ext.sim.telegram;
import com.google.gson.Gson;
import id.dni.pvim.ext.telegram.pojo.TelegramGetUpdatesPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageChatPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageContentPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramMessageFromPOJO;
import id.dni.pvim.ext.telegram.pojo.TelegramUpdateObjPOJO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author darryl.sulistyan
*/
@WebServlet(name = "GetUpdatesServlet", urlPatterns = {"/getUpdates/*"})
public class GetUpdatesServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
long offset;
try {
offset = Long.parseLong(request.getParameter("offset"));
} catch (Exception ex) {
offset = 0;
}
List<Chat> chats = ChatRepository.getInstance().getChats();
List<Chat> newChat = new ArrayList<>();
TelegramGetUpdatesPOJO getUpdates = new TelegramGetUpdatesPOJO();
getUpdates.setOk(true);
getUpdates.setResult(new ArrayList<>());
for (Chat chat : chats) {
long updateID = chat.getUpdateID();
if (updateID >= offset) {
TelegramUpdateObjPOJO m = new TelegramUpdateObjPOJO();
m.setUpdate_id(chat.getUpdateID());
TelegramMessageContentPOJO c = new TelegramMessageContentPOJO();
c.setMessage_id(60);
c.setDate(chat.getDate());
c.setText(chat.getText());
TelegramMessageChatPOJO pc = new TelegramMessageChatPOJO();
pc.setFirst_name("whatever");
pc.setLast_name("<NAME>");
pc.setType("private");
pc.setId(chat.getChatID());
TelegramMessageFromPOJO mf = new TelegramMessageFromPOJO();
mf.setFirst_name("whatever");
mf.setLast_name("<NAME>");
mf.setId(chat.getChatID());
mf.setIs_bot(false);
mf.setLanguage_code("en-us");
c.setChat(pc);
c.setFrom(mf);
m.setMessage(c);
getUpdates.getResult().add(m);
newChat.add(chat);
}
}
ChatRepository.getInstance().getChats().clear();
ChatRepository.getInstance().getChats().addAll(newChat);
Gson gson = new Gson();
String json = gson.toJson(getUpdates);
out.write(json);
out.flush();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 5,238 | 0.590164 | 0.58902 | 143 | 34.685314 | 25.422422 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48951 | false | false |
5
|
8fa96991f6d14dfd89b1643499b738dd205f7cf7
| 1,365,799,616,866 |
9d16e399e1daa395f6f05f23489d903e9b84d5cc
|
/src/tests/MealItemTest.java
|
b0b4c0b08ee8e4c537792e5addcf1b887f23d8be
|
[] |
no_license
|
qanatke/yomealsProject
|
https://github.com/qanatke/yomealsProject
|
eef5b9a4ba5e256b5e613632d5e10bf478cd564e
|
86ceb4e9a0d78ffa04d80108d7e1c56ebe964ceb
|
refs/heads/master
| 2022-12-28T01:35:02.616000 | 2020-10-06T20:16:16 | 2020-10-06T20:16:16 | 299,397,060 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tests;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import pages.CartSummaryPage;
import pages.LocationPopupPage;
import pages.LoginPage;
import pages.MealPage;
import pages.NotificationSistemPage;
public class MealItemTest extends BasicTest {
@Test(priority = 5)
public void addMealToCartTest() throws Exception {
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
locationPopupPage.hidePopup();
mealPage.addMealToCart(3);
Assert.assertTrue(notification.getMsg().contains("The Following Errors Occurred:"));
Assert.assertTrue(notification.getMsg().contains("Please Select Location"));
notification.waitToDisappear();
locationPopupPage.getLocationForm().click();
locationPopupPage.setLocation(locationName);
// waiting for the location to be set
Thread.sleep(1000);
mealPage.addMealToCart(2);
Assert.assertEquals(notification.getMsg(), "Meal Added To Cart");
}
@Test(priority = 10)
public void addMealToFavouriteTest() throws Exception {
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
LoginPage loginPage = new LoginPage(this.driver, this.js, this.waiter);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
locationPopupPage.hidePopup();
mealPage.addMealToFavourites();
Assert.assertEquals(notification.getMsg(), "Please login first!");
this.driver.navigate().to(baseUrl + "/guest-user/login-form");
loginPage.login(mail, pass);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
mealPage.addMealToFavourites();
Assert.assertEquals(notification.getMsg(), "Product has been added to your favorites.");
}
@Test(priority = 15)
public void clearCartTest() throws Exception {
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
CartSummaryPage cartPage = new CartSummaryPage(this.driver, this.js, this.waiter);
SoftAssert softAssert = new SoftAssert();
File meals = new File("data/Data.xlsx");
FileInputStream fis = new FileInputStream(meals);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet mealsSheet = wb.getSheet("Meals");
this.driver.navigate().to(baseUrl + "/meals");
locationPopupPage.setLocation(locationName);
// waiting for synchronization
Thread.sleep(2000);
for (int i = 1; i <= mealsSheet.getLastRowNum(); i++) {
XSSFRow row = mealsSheet.getRow(i);
String mealUrl = row.getCell(0).getStringCellValue();
this.driver.navigate().to(mealUrl);
double quantity = row.getCell(1).getNumericCellValue();
mealPage.addMealToCart(quantity);
softAssert.assertEquals(notification.getMsg(), "Meal Added To Cart");
}
// waiting for synchronization
Thread.sleep(1000);
cartPage.clearAll();
Assert.assertEquals(notification.getMsg(), "All meals removed from Cart successfully");
}
}
|
UTF-8
|
Java
| 3,797 |
java
|
MealItemTest.java
|
Java
|
[] | null |
[] |
package tests;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import pages.CartSummaryPage;
import pages.LocationPopupPage;
import pages.LoginPage;
import pages.MealPage;
import pages.NotificationSistemPage;
public class MealItemTest extends BasicTest {
@Test(priority = 5)
public void addMealToCartTest() throws Exception {
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
locationPopupPage.hidePopup();
mealPage.addMealToCart(3);
Assert.assertTrue(notification.getMsg().contains("The Following Errors Occurred:"));
Assert.assertTrue(notification.getMsg().contains("Please Select Location"));
notification.waitToDisappear();
locationPopupPage.getLocationForm().click();
locationPopupPage.setLocation(locationName);
// waiting for the location to be set
Thread.sleep(1000);
mealPage.addMealToCart(2);
Assert.assertEquals(notification.getMsg(), "Meal Added To Cart");
}
@Test(priority = 10)
public void addMealToFavouriteTest() throws Exception {
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
LoginPage loginPage = new LoginPage(this.driver, this.js, this.waiter);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
locationPopupPage.hidePopup();
mealPage.addMealToFavourites();
Assert.assertEquals(notification.getMsg(), "Please login first!");
this.driver.navigate().to(baseUrl + "/guest-user/login-form");
loginPage.login(mail, pass);
this.driver.navigate().to(baseUrl + "/meal/lobster-shrimp-chicken-quesadilla-combo");
mealPage.addMealToFavourites();
Assert.assertEquals(notification.getMsg(), "Product has been added to your favorites.");
}
@Test(priority = 15)
public void clearCartTest() throws Exception {
LocationPopupPage locationPopupPage = new LocationPopupPage(this.driver, this.js, this.waiter);
MealPage mealPage = new MealPage(this.driver, this.js, this.waiter);
NotificationSistemPage notification = new NotificationSistemPage(this.driver, this.js, this.waiter);
CartSummaryPage cartPage = new CartSummaryPage(this.driver, this.js, this.waiter);
SoftAssert softAssert = new SoftAssert();
File meals = new File("data/Data.xlsx");
FileInputStream fis = new FileInputStream(meals);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet mealsSheet = wb.getSheet("Meals");
this.driver.navigate().to(baseUrl + "/meals");
locationPopupPage.setLocation(locationName);
// waiting for synchronization
Thread.sleep(2000);
for (int i = 1; i <= mealsSheet.getLastRowNum(); i++) {
XSSFRow row = mealsSheet.getRow(i);
String mealUrl = row.getCell(0).getStringCellValue();
this.driver.navigate().to(mealUrl);
double quantity = row.getCell(1).getNumericCellValue();
mealPage.addMealToCart(quantity);
softAssert.assertEquals(notification.getMsg(), "Meal Added To Cart");
}
// waiting for synchronization
Thread.sleep(1000);
cartPage.clearAll();
Assert.assertEquals(notification.getMsg(), "All meals removed from Cart successfully");
}
}
| 3,797 | 0.763234 | 0.75744 | 112 | 32.901787 | 31.141371 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.901786 | false | false |
5
|
dab8338652e80c50d6102492a10a3ea4ad76bdf3
| 23,699,629,567,051 |
f5d7b8ce59178b8619663d36ec70c03167239413
|
/src/customHTTPPackage/MyHttp.java
|
def1bf8925a598b1274fc448adbac7c934e9753d
|
[] |
no_license
|
kevokario/Javas-Rest-API
|
https://github.com/kevokario/Javas-Rest-API
|
d58edd1ad5fdde650bfea145430f46a2980a2e5d
|
87f1398531aa1bc36b7ad5174c5a8bb4fa370f6f
|
refs/heads/master
| 2020-06-13T08:58:22.443000 | 2019-07-01T13:36:30 | 2019-07-01T13:36:30 | 194,607,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package customHTTPPackage;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class MyHttp {
private String url = "";
private String jsonData = "";
public MyHttp(){
}
public MyHttp(String url, String json){
this.url = url;
this.jsonData = json;
}
public void setUrl(String URL){
this.url = url;
}
public void setJsonData(String json){
this.jsonData = json;
}
public String getJsonData(){
return this.jsonData;
}
public String getUrl(){
return this.url;
}
public String serverSend(){
String ServerResults = "";
try{
URL myurl = new URL(getUrl());
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(7000);
InputStream in = new BufferedInputStream(con.getInputStream());
ServerResults =IOUtils.toString(in);
} catch(Exception ex){
System.err.println(ex);
}
return ServerResults;
}
}
|
UTF-8
|
Java
| 1,333 |
java
|
MyHttp.java
|
Java
|
[] | null |
[] |
package customHTTPPackage;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class MyHttp {
private String url = "";
private String jsonData = "";
public MyHttp(){
}
public MyHttp(String url, String json){
this.url = url;
this.jsonData = json;
}
public void setUrl(String URL){
this.url = url;
}
public void setJsonData(String json){
this.jsonData = json;
}
public String getJsonData(){
return this.jsonData;
}
public String getUrl(){
return this.url;
}
public String serverSend(){
String ServerResults = "";
try{
URL myurl = new URL(getUrl());
HttpURLConnection con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
con.setConnectTimeout(7000);
InputStream in = new BufferedInputStream(con.getInputStream());
ServerResults =IOUtils.toString(in);
} catch(Exception ex){
System.err.println(ex);
}
return ServerResults;
}
}
| 1,333 | 0.585146 | 0.582146 | 55 | 23.236364 | 18.653748 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472727 | false | false |
5
|
5d2dbda65659f342852f22e2b698832ec5a54052
| 4,363,686,793,103 |
31ab81cefe4b0c4a886555610af95b2b7294fbab
|
/CSCI-605 Advanced OO Programming Concepts/my-src/java/pdfCode/C11Thread/ThreadPool/HpSimpleThreadPoolUse_1.java
|
f9f444e4a6b7da9a8c5d6cfc396e5aefb7477dcc
|
[] |
no_license
|
QingqiLei/RIT-Bridge-Courses
|
https://github.com/QingqiLei/RIT-Bridge-Courses
|
ab3b1c18be106cdb2943ce0f99e742ac9788f1e1
|
90e86ce2a2cbc9e05ef8157eefb8f001e22cdb52
|
refs/heads/master
| 2022-11-25T17:06:03.531000 | 2020-08-07T11:07:29 | 2020-08-07T11:07:29 | 270,459,891 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package C11Thread.ThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HpSimpleThreadPoolUse_1 {
public static final int MAX = 2;
public static final int SLEEP_TIME = 1000; // 100
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(MAX);
for (int i = 0; i < MAX * 3; i++) {
if ( i % 2 == 0 )
executor.execute(new HpWorker_1(i, 4 * SLEEP_TIME));
else
executor.execute(new HpWorker_1(i, SLEEP_TIME));
}
executor.shutdown();
// awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
// Blocks until all tasks have completed execution after a
// shutdown request, or the timeout occurs,
// or the current thread is interrupted, whichever happens first.
while ( !executor.isTerminated() ) {
try { Thread.sleep(100); } catch ( Exception e ) { }
}
System.out.println("all threads have terminated");
}
}
|
UTF-8
|
Java
| 1,022 |
java
|
HpSimpleThreadPoolUse_1.java
|
Java
|
[] | null |
[] |
package C11Thread.ThreadPool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HpSimpleThreadPoolUse_1 {
public static final int MAX = 2;
public static final int SLEEP_TIME = 1000; // 100
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(MAX);
for (int i = 0; i < MAX * 3; i++) {
if ( i % 2 == 0 )
executor.execute(new HpWorker_1(i, 4 * SLEEP_TIME));
else
executor.execute(new HpWorker_1(i, SLEEP_TIME));
}
executor.shutdown();
// awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
// Blocks until all tasks have completed execution after a
// shutdown request, or the timeout occurs,
// or the current thread is interrupted, whichever happens first.
while ( !executor.isTerminated() ) {
try { Thread.sleep(100); } catch ( Exception e ) { }
}
System.out.println("all threads have terminated");
}
}
| 1,022 | 0.667319 | 0.646771 | 29 | 34.241379 | 23.554274 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.068966 | false | false |
5
|
5581114641d688a379534873ab12adf7303c6e0c
| 26,345,329,414,309 |
46f6f42a2c8eafb449475807bdef75a9a49a60c2
|
/huayi-commerce-website/src/main/java/com/commerce/huayi/controller/admin/NewsInfoForAdminController.java
|
34e43b9e088dc5feea880a2f97336a930cda2861
|
[] |
no_license
|
yang7988/commerce
|
https://github.com/yang7988/commerce
|
137614646cdbd5f6bbd96de99fdf13b6dedd2efb
|
73e7ef7057bfd358b3490b32d72bd1a8db92b06c
|
refs/heads/master
| 2020-04-28T04:11:35.881000 | 2019-06-10T02:31:44 | 2019-06-10T02:31:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.commerce.huayi.controller.admin;
import com.commerce.huayi.api.ApiResponse;
import com.commerce.huayi.entity.request.DelDataReq;
import com.commerce.huayi.entity.request.NewsInfoReq;
import com.commerce.huayi.entity.request.NewsListReq;
import com.commerce.huayi.entity.response.NewsInfoVo;
import com.commerce.huayi.pagination.Page;
import com.commerce.huayi.service.NewsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/api/admin/newsInfo")
@Api(tags = "新闻中心管理")
public class NewsInfoForAdminController {
@Autowired
private NewsInfoService newsInfoService;
@PostMapping(value = "/getNewsInfos")
@ApiOperation(value = "新闻中心管理", notes = "获取新闻列表")
public ApiResponse<Page<NewsInfoVo>> getNewsInfos(@RequestBody NewsListReq pageRequest) {
return ApiResponse.returnSuccess(newsInfoService.getNewsInfos(pageRequest));
}
@PostMapping(value = "/getNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "获取新闻明细")
public ApiResponse<NewsInfoVo> getNewsInfo(@RequestBody DelDataReq param) {
return ApiResponse.returnSuccess(newsInfoService.getNewsInfo(param.getId()));
}
@PostMapping(value = "/addNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "添加新闻")
public ApiResponse addNewsInfo(@RequestBody NewsInfoReq newsInfoReq) {
newsInfoService.addNewsInfo(newsInfoReq);
return ApiResponse.returnSuccess();
}
@PostMapping(value = "/delNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "删除新闻")
public ApiResponse delNewsInfo(@RequestBody DelDataReq param) {
newsInfoService.delNewsInfo(param.getId());
return ApiResponse.returnSuccess();
}
@PostMapping(value = "/updateNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "更新新闻明细")
public ApiResponse updateNewsInfo(@RequestBody NewsInfoReq newsInfoReq) {
newsInfoService.updateNewsInfo(newsInfoReq);
return ApiResponse.returnSuccess();
}
}
|
UTF-8
|
Java
| 2,465 |
java
|
NewsInfoForAdminController.java
|
Java
|
[] | null |
[] |
package com.commerce.huayi.controller.admin;
import com.commerce.huayi.api.ApiResponse;
import com.commerce.huayi.entity.request.DelDataReq;
import com.commerce.huayi.entity.request.NewsInfoReq;
import com.commerce.huayi.entity.request.NewsListReq;
import com.commerce.huayi.entity.response.NewsInfoVo;
import com.commerce.huayi.pagination.Page;
import com.commerce.huayi.service.NewsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/api/admin/newsInfo")
@Api(tags = "新闻中心管理")
public class NewsInfoForAdminController {
@Autowired
private NewsInfoService newsInfoService;
@PostMapping(value = "/getNewsInfos")
@ApiOperation(value = "新闻中心管理", notes = "获取新闻列表")
public ApiResponse<Page<NewsInfoVo>> getNewsInfos(@RequestBody NewsListReq pageRequest) {
return ApiResponse.returnSuccess(newsInfoService.getNewsInfos(pageRequest));
}
@PostMapping(value = "/getNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "获取新闻明细")
public ApiResponse<NewsInfoVo> getNewsInfo(@RequestBody DelDataReq param) {
return ApiResponse.returnSuccess(newsInfoService.getNewsInfo(param.getId()));
}
@PostMapping(value = "/addNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "添加新闻")
public ApiResponse addNewsInfo(@RequestBody NewsInfoReq newsInfoReq) {
newsInfoService.addNewsInfo(newsInfoReq);
return ApiResponse.returnSuccess();
}
@PostMapping(value = "/delNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "删除新闻")
public ApiResponse delNewsInfo(@RequestBody DelDataReq param) {
newsInfoService.delNewsInfo(param.getId());
return ApiResponse.returnSuccess();
}
@PostMapping(value = "/updateNewsInfo")
@ApiOperation(value = "新闻中心管理", notes = "更新新闻明细")
public ApiResponse updateNewsInfo(@RequestBody NewsInfoReq newsInfoReq) {
newsInfoService.updateNewsInfo(newsInfoReq);
return ApiResponse.returnSuccess();
}
}
| 2,465 | 0.759932 | 0.759932 | 59 | 38.677967 | 25.818428 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491525 | false | false |
5
|
0394c9277a3fb1be0f113271a3322aca08e19cd7
| 22,162,031,266,384 |
bf2f2bdc768bd702e7ab519889f410984ec86eab
|
/dummy3/src/main/java/com/dummy/java/dummy3/App.java
|
cc359b06fe284dd484458bc5ac3b26e9ab3edb53
|
[] |
no_license
|
dummyjava/dummy3
|
https://github.com/dummyjava/dummy3
|
1d85d95739f2cc570c809ef9c2bfedef244ca668
|
288a22f8886e280eee0af35ea248443c9c7dd527
|
refs/heads/master
| 2020-03-25T19:05:28.520000 | 2018-08-11T23:07:03 | 2018-08-11T23:07:03 | 144,064,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dummy.java.dummy3;
import java.util.ArrayList;
import java.util.Stack;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("test result:");
System.out.println(reverseString("hello"));
System.out.println(reverseString1("hello1"));
System.out.println(reverseString2("hello2"));
System.out.println(reverseString3("hello3"));
System.out.println("is Hello palindrome:"+palindrome("hello"));
System.out.println("is civic palindrome:"+palindrome("civic"));
System.out.println("find first repeat char:"+findfirstrepeat("heello"));
}
@SuppressWarnings("null")
public static String reverseString(String origin)
{
int len = origin.length();
char originchars[] = origin.toCharArray();
char resultchars[] = new char[len];
int i = len;
int j = 0;
for ( ;i>=1; i--)
{
resultchars[j] = originchars[i-1];
j++;
}
return String.copyValueOf(resultchars);
}
public static String reverseString1(String origin) {
StringBuffer stringbuffer = new StringBuffer(origin);
stringbuffer.reverse();
return stringbuffer.toString();
}
public static String reverseString2(String origin)
{
Stack<Character> stack = new Stack<Character>();
for(int i=0; i< origin.length(); i++) {
stack.push(origin.charAt(i));
}
String result = "";
char temp;
while(!stack.isEmpty()){
temp = (char) stack.pop();
result = result + String.valueOf(temp);
}
return result;
}
public static String reverseString3(String origin)
{
ArrayList<String> alist = new ArrayList<String>();
for(int i=0; i< origin.length();i++)
{
alist.add(String.valueOf(origin.charAt(i)));
}
String result = "";
alist.stream().filter( s -> s.contains("h"));
return result;
}
public static boolean palindrome(String origin)
{
String reverse = reverseString1(origin);
if (reverse.equals(origin))
{
return true;
}
return false;
}
public static char findfirstrepeat(String origin)
{
int len = origin.toCharArray().length;
char chararray[] = origin.toCharArray();
String string = "";
for (int i=0; i<= len; i++)
{
if(string.startsWith(String.valueOf(chararray[i])))
{
return chararray[i];
}
string = String.valueOf(chararray[i]) + string;
}
return ' ';
}
}
|
UTF-8
|
Java
| 2,572 |
java
|
App.java
|
Java
|
[] | null |
[] |
package com.dummy.java.dummy3;
import java.util.ArrayList;
import java.util.Stack;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("test result:");
System.out.println(reverseString("hello"));
System.out.println(reverseString1("hello1"));
System.out.println(reverseString2("hello2"));
System.out.println(reverseString3("hello3"));
System.out.println("is Hello palindrome:"+palindrome("hello"));
System.out.println("is civic palindrome:"+palindrome("civic"));
System.out.println("find first repeat char:"+findfirstrepeat("heello"));
}
@SuppressWarnings("null")
public static String reverseString(String origin)
{
int len = origin.length();
char originchars[] = origin.toCharArray();
char resultchars[] = new char[len];
int i = len;
int j = 0;
for ( ;i>=1; i--)
{
resultchars[j] = originchars[i-1];
j++;
}
return String.copyValueOf(resultchars);
}
public static String reverseString1(String origin) {
StringBuffer stringbuffer = new StringBuffer(origin);
stringbuffer.reverse();
return stringbuffer.toString();
}
public static String reverseString2(String origin)
{
Stack<Character> stack = new Stack<Character>();
for(int i=0; i< origin.length(); i++) {
stack.push(origin.charAt(i));
}
String result = "";
char temp;
while(!stack.isEmpty()){
temp = (char) stack.pop();
result = result + String.valueOf(temp);
}
return result;
}
public static String reverseString3(String origin)
{
ArrayList<String> alist = new ArrayList<String>();
for(int i=0; i< origin.length();i++)
{
alist.add(String.valueOf(origin.charAt(i)));
}
String result = "";
alist.stream().filter( s -> s.contains("h"));
return result;
}
public static boolean palindrome(String origin)
{
String reverse = reverseString1(origin);
if (reverse.equals(origin))
{
return true;
}
return false;
}
public static char findfirstrepeat(String origin)
{
int len = origin.toCharArray().length;
char chararray[] = origin.toCharArray();
String string = "";
for (int i=0; i<= len; i++)
{
if(string.startsWith(String.valueOf(chararray[i])))
{
return chararray[i];
}
string = String.valueOf(chararray[i]) + string;
}
return ' ';
}
}
| 2,572 | 0.605365 | 0.598756 | 95 | 26.073685 | 20.166279 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.789474 | false | false |
5
|
21bc3b4901d246e56f9a114a7a9728fdfb32c5e0
| 18,837,726,584,383 |
4b5632cc2cb166977e417b62aff84c3a7210c37f
|
/src/Tester.java
|
2b9e14c3aca7ca67d8bdb9ffe13cae08442b023d
|
[] |
no_license
|
sandeep8978/san
|
https://github.com/sandeep8978/san
|
8a91d987eb3641d737abd3fdd95cae26647674c7
|
219ce269973477942a6c758c6acea18c7102a333
|
refs/heads/master
| 2021-01-10T00:07:30.936000 | 2017-05-29T11:11:02 | 2017-05-29T11:11:30 | 92,732,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class sandeep{
int amount=20000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw.....");
if(this.amount<amount){
System.out.println("less balance,waiting for deposit");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.amount -=amount;
System.out.println("withdraw is completed");
}
synchronized void deposit(int amount){
System.out.println("going to deposit");
this.amount +=amount;
System.out.println("deposit is completed");
notify();
}
}
public class Tester {
public static void main(String[] args) {
final sandeep c=new sandeep();
new Thread(){
public void run(){
c.withdraw(1000);
}
}
.start();
new Thread(){
public void run(){
c.deposit(200);
}
}
.start();
}
}
|
UTF-8
|
Java
| 847 |
java
|
Tester.java
|
Java
|
[] | null |
[] |
class sandeep{
int amount=20000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw.....");
if(this.amount<amount){
System.out.println("less balance,waiting for deposit");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.amount -=amount;
System.out.println("withdraw is completed");
}
synchronized void deposit(int amount){
System.out.println("going to deposit");
this.amount +=amount;
System.out.println("deposit is completed");
notify();
}
}
public class Tester {
public static void main(String[] args) {
final sandeep c=new sandeep();
new Thread(){
public void run(){
c.withdraw(1000);
}
}
.start();
new Thread(){
public void run(){
c.deposit(200);
}
}
.start();
}
}
| 847 | 0.61157 | 0.597403 | 40 | 19.174999 | 15.711282 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.4 | false | false |
5
|
c298f2d13f8658db9ac2c115d85595f5a578eafa
| 18,837,726,587,429 |
8f35769993897fe203601d264152efa094996ed4
|
/src/main/java/com/jtripled/voxen/block/BlockBase.java
|
971b7b86bb52c91a4ee70a7a6ad510b9f3377f78
|
[] |
no_license
|
Anoyomouse/SimpleFactory
|
https://github.com/Anoyomouse/SimpleFactory
|
2b9350b9c41dc10188a4444bb84665a34875ac13
|
9cae7b0b21ce40bda1d61f8389e9c9bf1ff83c27
|
refs/heads/master
| 2021-07-14T17:21:21.715000 | 2017-10-17T16:13:25 | 2017-10-17T16:13:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jtripled.voxen.block;
import com.jtripled.voxen.item.ItemBase;
import com.jtripled.voxen.item.ItemBlockBase;
import com.jtripled.voxen.mod.VoxenMod;
import com.jtripled.voxen.registry.RegistrationHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import com.jtripled.voxen.gui.GUIHolder;
/**
*
* @author jtripled
*/
public class BlockBase extends Block implements IBlockBase
{
private final String name;
private ItemBlockBase item;
private int guiID;
public BlockBase(Material material, String name)
{
this(material, material.getMaterialMapColor(), name);
}
public BlockBase(Material material, MapColor mapColor, String name)
{
super(material, mapColor);
this.name = name;
this.setUnlocalizedName(name);
this.setRegistryName(new ResourceLocation(VoxenMod.ID, name));
if (this instanceof GUIHolder)
{
guiID = RegistrationHandler.nextGUIID();
}
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
if (!world.isRemote)
{
if (this instanceof GUIHolder)
((GUIHolder) this).openGUI(player, world, pos.getX(), pos.getY(), pos.getZ());
}
return true;
}
@Override
public String getName()
{
return name;
}
public int getGUIID()
{
return guiID;
}
public void setItem()
{
this.item = new ItemBlockBase(this);
this.item.setUnlocalizedName(this.getUnlocalizedName());
this.item.setRegistryName(this.getRegistryName());
}
@Override
public boolean hasTileEntity(IBlockState state)
{
return getTileClass() != null;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state)
{
if (hasTileEntity(state))
{
try
{
return getTileClass().newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
Logger.getLogger(BlockBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
@Override
public ItemBase getItem()
{
return item;
}
}
|
UTF-8
|
Java
| 2,994 |
java
|
BlockBase.java
|
Java
|
[
{
"context": "ripled.voxen.gui.GUIHolder;\r\n\r\n/**\r\n *\r\n * @author jtripled\r\n */\r\npublic class BlockBase extends Block implem",
"end": 832,
"score": 0.999678909778595,
"start": 824,
"tag": "USERNAME",
"value": "jtripled"
}
] | null |
[] |
package com.jtripled.voxen.block;
import com.jtripled.voxen.item.ItemBase;
import com.jtripled.voxen.item.ItemBlockBase;
import com.jtripled.voxen.mod.VoxenMod;
import com.jtripled.voxen.registry.RegistrationHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import com.jtripled.voxen.gui.GUIHolder;
/**
*
* @author jtripled
*/
public class BlockBase extends Block implements IBlockBase
{
private final String name;
private ItemBlockBase item;
private int guiID;
public BlockBase(Material material, String name)
{
this(material, material.getMaterialMapColor(), name);
}
public BlockBase(Material material, MapColor mapColor, String name)
{
super(material, mapColor);
this.name = name;
this.setUnlocalizedName(name);
this.setRegistryName(new ResourceLocation(VoxenMod.ID, name));
if (this instanceof GUIHolder)
{
guiID = RegistrationHandler.nextGUIID();
}
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
if (!world.isRemote)
{
if (this instanceof GUIHolder)
((GUIHolder) this).openGUI(player, world, pos.getX(), pos.getY(), pos.getZ());
}
return true;
}
@Override
public String getName()
{
return name;
}
public int getGUIID()
{
return guiID;
}
public void setItem()
{
this.item = new ItemBlockBase(this);
this.item.setUnlocalizedName(this.getUnlocalizedName());
this.item.setRegistryName(this.getRegistryName());
}
@Override
public boolean hasTileEntity(IBlockState state)
{
return getTileClass() != null;
}
@Override
public TileEntity createTileEntity(World world, IBlockState state)
{
if (hasTileEntity(state))
{
try
{
return getTileClass().newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
Logger.getLogger(BlockBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
@Override
public ItemBase getItem()
{
return item;
}
}
| 2,994 | 0.630261 | 0.630261 | 106 | 26.245283 | 25.846722 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59434 | false | false |
5
|
2fb786295f284d98b2d4fb0ff4c701c188f36012
| 25,606,595,054,358 |
5bedbc9dd0c44205369341bf5d62a2b8d1e119d2
|
/src/main/java/com/ctart/app/test/code/service/CodeTestService.java
|
0b7d007a74ace86c389303d2646cd19ae9c33a0c
|
[] |
no_license
|
jangseungil/combye
|
https://github.com/jangseungil/combye
|
3bcabbe7e2e86689483115e712a2c4813604b6db
|
76cf3743efe205f4fafbfaed3fc353492e85a17e
|
refs/heads/master
| 2020-12-24T14:53:03.581000 | 2015-08-21T16:20:05 | 2015-08-21T16:20:05 | 34,833,552 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ctart.app.test.code.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ctart.app.test.code.dao.CodeTestDao;
import com.ctart.app.test.code.vo.CodeTestVo;
@Service
public class CodeTestService {
@Autowired
private CodeTestDao testDao;
public List<CodeTestVo> selectCodeList() throws SQLException {
return testDao.selectCodeList();
}
}
|
UTF-8
|
Java
| 492 |
java
|
CodeTestService.java
|
Java
|
[] | null |
[] |
package com.ctart.app.test.code.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ctart.app.test.code.dao.CodeTestDao;
import com.ctart.app.test.code.vo.CodeTestVo;
@Service
public class CodeTestService {
@Autowired
private CodeTestDao testDao;
public List<CodeTestVo> selectCodeList() throws SQLException {
return testDao.selectCodeList();
}
}
| 492 | 0.800813 | 0.800813 | 21 | 22.428572 | 21.395531 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false |
5
|
dcebaaaa50bb6bcae9485a4ed6d07a0748652d6d
| 7,129,645,734,013 |
94b6d617a7c4cf19938db51a707a4a8bc9f36277
|
/src/JikJik/Pages/ChatPage.java
|
091dd390c055a66966805fd8d6ac274bfedc8dc5
|
[] |
no_license
|
Mortrest/JikJik
|
https://github.com/Mortrest/JikJik
|
3c7ee3a996159e56d535fa193c06bfa1db9501c5
|
3291a5c627ea0e67cda5ee2b1cc8ef020886b30b
|
refs/heads/master
| 2023-03-30T11:18:24.685000 | 2021-03-27T09:30:18 | 2021-03-27T09:30:18 | 352,032,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package JikJik.Pages;
import JikJik.Models.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;
public class ChatPage extends Page {
Users users;
User currentUser;
public ChatPage(Users users, User currentUser) {
super();
this.users = users;
this.currentUser = currentUser;
}
public void eachRoom(String roomID){
LinkedList<Chat> chats = users.getChats().showChats(roomID);
users.getChats().seen(currentUser.getUsername(),roomID);
if (chats == null){
System.out.println("No Chats!");
} else {
int i = 0;
for (Chat chat : chats) {
System.out.println("["+ (i+1) + "] "+chat.getOwner() + ": " + chat.getText());
i++;
}
}
System.out.println("[0] For chat mode");
System.out.println("* Double back for return");
Scanner ss = new Scanner(System.in);
boolean a = true;
while (a) {
boolean b = true;
String str = ss.next();
if (!str.equals("0")) {
try {
int n = Integer.parseInt(str);
assert chats != null;
if (n <= chats.size() && n >= 1) {
users.getChats().makeChat(chats.get(n-1).getText(), chats.get(n-1).getOwner(), users.getChats().searchRoom(currentUser.getUsername(), "Saved Messages").getRoomID());
System.out.println("Forwarded!");
b = false;
}
} catch (Exception e) {
}
}
switch (str) {
case "back" -> {
a = false;
break;
}
case "0" -> {
a = false;
Scanner sss = new Scanner(System.in);
String text = sss.nextLine();
users.getChats().makeChat(text, currentUser.getUsername(), roomID);
eachRoom(roomID);
break;
}
}
if (a && b) {
System.out.println("Invalid command!");
}
}
}
public void showRoom() {
users.log("Chat page");
LinkedList<Room> tw = users.getChats().userRoom(currentUser.getUsername());
System.out.println("\t\t\tYour Chats:\n");
if (tw.isEmpty()) {
System.out.println("No Chats");
} else {
int i = 0;
for (Room room : tw) {
try {
if (users.searchUsername(room.getOwner1()).isActive() && users.searchUsername(room.getOwner2()).isActive()) {
if (!users.searchUsername(room.getOwner2()).getBlackList().contains(room.getOwner1()) && !users.searchUsername(room.getOwner1()).getBlackList().contains(room.getOwner2())) {
System.out.println("\n" + "[" + (i + 1) + "] " + room.getOwner1() + "-" + room.getOwner2() + " " + (room.getOwner1().equals(currentUser.getUsername()) ? room.getUnread1() : room.getUnread2()));
i++;
}
}
}catch (Exception e){
}
}
}
Scanner ss = new Scanner(System.in);
boolean a = true;
boolean b = false;
while (a) {
String str = ss.next();
try {
int n = Integer.parseInt(str);
if (n <= tw.size() && n >= 1) {
eachRoom(tw.get(n-1).getRoomID());
b = true;
}
} catch (Exception e) {
}
if (str.equals("back")) {
a = false;
// b = false;
break;
}
if (a && !b) {
System.out.println("Invalid command!");
} else if (b){
showRoom();
}
}
}
}
|
UTF-8
|
Java
| 4,088 |
java
|
ChatPage.java
|
Java
|
[] | null |
[] |
package JikJik.Pages;
import JikJik.Models.*;
import java.util.Date;
import java.util.LinkedList;
import java.util.Random;
import java.util.Scanner;
public class ChatPage extends Page {
Users users;
User currentUser;
public ChatPage(Users users, User currentUser) {
super();
this.users = users;
this.currentUser = currentUser;
}
public void eachRoom(String roomID){
LinkedList<Chat> chats = users.getChats().showChats(roomID);
users.getChats().seen(currentUser.getUsername(),roomID);
if (chats == null){
System.out.println("No Chats!");
} else {
int i = 0;
for (Chat chat : chats) {
System.out.println("["+ (i+1) + "] "+chat.getOwner() + ": " + chat.getText());
i++;
}
}
System.out.println("[0] For chat mode");
System.out.println("* Double back for return");
Scanner ss = new Scanner(System.in);
boolean a = true;
while (a) {
boolean b = true;
String str = ss.next();
if (!str.equals("0")) {
try {
int n = Integer.parseInt(str);
assert chats != null;
if (n <= chats.size() && n >= 1) {
users.getChats().makeChat(chats.get(n-1).getText(), chats.get(n-1).getOwner(), users.getChats().searchRoom(currentUser.getUsername(), "Saved Messages").getRoomID());
System.out.println("Forwarded!");
b = false;
}
} catch (Exception e) {
}
}
switch (str) {
case "back" -> {
a = false;
break;
}
case "0" -> {
a = false;
Scanner sss = new Scanner(System.in);
String text = sss.nextLine();
users.getChats().makeChat(text, currentUser.getUsername(), roomID);
eachRoom(roomID);
break;
}
}
if (a && b) {
System.out.println("Invalid command!");
}
}
}
public void showRoom() {
users.log("Chat page");
LinkedList<Room> tw = users.getChats().userRoom(currentUser.getUsername());
System.out.println("\t\t\tYour Chats:\n");
if (tw.isEmpty()) {
System.out.println("No Chats");
} else {
int i = 0;
for (Room room : tw) {
try {
if (users.searchUsername(room.getOwner1()).isActive() && users.searchUsername(room.getOwner2()).isActive()) {
if (!users.searchUsername(room.getOwner2()).getBlackList().contains(room.getOwner1()) && !users.searchUsername(room.getOwner1()).getBlackList().contains(room.getOwner2())) {
System.out.println("\n" + "[" + (i + 1) + "] " + room.getOwner1() + "-" + room.getOwner2() + " " + (room.getOwner1().equals(currentUser.getUsername()) ? room.getUnread1() : room.getUnread2()));
i++;
}
}
}catch (Exception e){
}
}
}
Scanner ss = new Scanner(System.in);
boolean a = true;
boolean b = false;
while (a) {
String str = ss.next();
try {
int n = Integer.parseInt(str);
if (n <= tw.size() && n >= 1) {
eachRoom(tw.get(n-1).getRoomID());
b = true;
}
} catch (Exception e) {
}
if (str.equals("back")) {
a = false;
// b = false;
break;
}
if (a && !b) {
System.out.println("Invalid command!");
} else if (b){
showRoom();
}
}
}
}
| 4,088 | 0.441292 | 0.435665 | 117 | 33.931625 | 34.016769 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false |
5
|
095280049d91b3eddc6cc05b6a69035348653383
| 3,453,153,737,813 |
4601780bbc7a4ba16e80d6b4d4350ce22b465c0e
|
/healthTimetable3/src/health/timetable/task/DigitalClockInf.java
|
0738fa156ca35c4bf9c4ead0a790d45e1ec22a4f
|
[] |
no_license
|
selifecn/healthtime
|
https://github.com/selifecn/healthtime
|
d17e85e33c252386a24882d5f737566a4210c7cd
|
be5b35a0c53ec7f1f4cdd97398e6f0f661ae82a1
|
refs/heads/master
| 2020-12-24T18:42:35.918000 | 2016-04-24T07:37:01 | 2016-04-24T07:37:01 | 56,657,588 | 0 | 0 | null | false | 2016-04-21T01:11:20 | 2016-04-20T05:21:42 | 2016-04-20T05:29:53 | 2016-04-21T01:11:19 | 15,181 | 0 | 0 | 0 |
Java
| null | null |
package health.timetable.task;
import android.content.Context;
public class DigitalClockInf {
public String startDay;
public String startTime;
public String exitDay;
public String exitTime;
public String CycleStyle;//提醒周期
public int ClockStyle;//提醒类型
public Context context;
public String taskName;
}
|
UTF-8
|
Java
| 332 |
java
|
DigitalClockInf.java
|
Java
|
[] | null |
[] |
package health.timetable.task;
import android.content.Context;
public class DigitalClockInf {
public String startDay;
public String startTime;
public String exitDay;
public String exitTime;
public String CycleStyle;//提醒周期
public int ClockStyle;//提醒类型
public Context context;
public String taskName;
}
| 332 | 0.789809 | 0.789809 | 15 | 19.933332 | 12.233651 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.266667 | false | false |
5
|
2a51b6976e3e372ca6084e47be41b5a7250eaec5
| 18,373,870,160,894 |
acb609146588d0cb03e87d75533e5c12acb56be8
|
/src/com/company/model/User.java
|
164b3d5630f4cabd61dafca6725fa382ec97904e
|
[] |
no_license
|
ChairfaceChippendale/htttpServer
|
https://github.com/ChairfaceChippendale/htttpServer
|
f8161274a14eca094c7bc08c120fcb4896b0d3e1
|
8cb55da552001dc9b8a8cc7f770c874b0f47c67a
|
refs/heads/master
| 2021-01-10T18:16:24.055000 | 2016-02-28T15:55:35 | 2016-02-28T15:55:35 | 52,716,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company.model;
import java.util.ArrayList;
import java.util.List;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static List<User> random(int count){
if(count < 1){
throw new IllegalArgumentException("Argument \'count\' can't be lower than one!");
}
List<User> users = new ArrayList<User>();
String[] names = {"Артем", "Максим", "Алексей", "Никита", "Иван", "Александр", "Владислав", "Даниил", "Дмитрий", "Кирилл"};
for(int i = 1; i <= count; i++){
User user = new User();
user.id = i;
user.name = names[((int) (Math.random() * names.length))];
users.add(user);
}
return users;
}
}
|
WINDOWS-1251
|
Java
| 1,069 |
java
|
User.java
|
Java
|
[
{
"context": "ew ArrayList<User>();\n\n String[] names = {\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Алексан",
"end": 661,
"score": 0.999863862991333,
"start": 656,
"tag": "NAME",
"value": "Артем"
},
{
"context": "ist<User>();\n\n String[] names = {\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Влад",
"end": 671,
"score": 0.9998571872711182,
"start": 665,
"tag": "NAME",
"value": "Максим"
},
{
"context": ");\n\n String[] names = {\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Да",
"end": 682,
"score": 0.9998430013656616,
"start": 675,
"tag": "NAME",
"value": "Алексей"
},
{
"context": " String[] names = {\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дм",
"end": 692,
"score": 0.9998548626899719,
"start": 686,
"tag": "NAME",
"value": "Никита"
},
{
"context": "names = {\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", ",
"end": 700,
"score": 0.9998440146446228,
"start": 696,
"tag": "NAME",
"value": "Иван"
},
{
"context": "{\"Артем\", \"Максим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", \"Кирилл\"};\n ",
"end": 713,
"score": 0.999851644039154,
"start": 704,
"tag": "NAME",
"value": "Александр"
},
{
"context": "ксим\", \"Алексей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", \"Кирилл\"};\n for(int",
"end": 726,
"score": 0.9998655319213867,
"start": 717,
"tag": "NAME",
"value": "Владислав"
},
{
"context": "ей\", \"Никита\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", \"Кирилл\"};\n for(int i = 1; i ",
"end": 736,
"score": 0.9998480677604675,
"start": 730,
"tag": "NAME",
"value": "Даниил"
},
{
"context": "та\", \"Иван\", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", \"Кирилл\"};\n for(int i = 1; i <= count; i",
"end": 747,
"score": 0.9998096227645874,
"start": 740,
"tag": "NAME",
"value": "Дмитрий"
},
{
"context": ", \"Александр\", \"Владислав\", \"Даниил\", \"Дмитрий\", \"Кирилл\"};\n for(int i = 1; i <= count; i++){\n ",
"end": 757,
"score": 0.9998486042022705,
"start": 751,
"tag": "NAME",
"value": "Кирилл"
}
] | null |
[] |
package com.company.model;
import java.util.ArrayList;
import java.util.List;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static List<User> random(int count){
if(count < 1){
throw new IllegalArgumentException("Argument \'count\' can't be lower than one!");
}
List<User> users = new ArrayList<User>();
String[] names = {"Артем", "Максим", "Алексей", "Никита", "Иван", "Александр", "Владислав", "Даниил", "Дмитрий", "Кирилл"};
for(int i = 1; i <= count; i++){
User user = new User();
user.id = i;
user.name = names[((int) (Math.random() * names.length))];
users.add(user);
}
return users;
}
}
| 1,069 | 0.541833 | 0.539841 | 44 | 21.818182 | 25.848574 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false |
5
|
0fccf59b50d6d06aab0c5ad0543df0f657bf690e
| 8,340,826,532,156 |
99612920ccc58ba91db5a08b44af0abde632a720
|
/mall/src/main/java/com/soubao/dao/BrandTypeMapper.java
|
ba2805aba5665396beb44258553cf1dd5809b2b8
|
[] |
no_license
|
shanghaif/eshop
|
https://github.com/shanghaif/eshop
|
d5a32e89a181f583cc93852325ec32c61425b7f1
|
105662255d647e4637b1e774ad7ca98dcaee0c9e
|
refs/heads/master
| 2023-03-21T21:07:04.659000 | 2020-11-04T05:31:21 | 2020-11-04T05:31:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.soubao.dao;
import com.soubao.entity.BrandType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 商品类型与品牌对应表 Mapper 接口
* </p>
*
* @author dyr
* @since 2019-11-22
*/
public interface BrandTypeMapper extends BaseMapper<BrandType> {
}
|
UTF-8
|
Java
| 296 |
java
|
BrandTypeMapper.java
|
Java
|
[
{
"context": " <p>\n * 商品类型与品牌对应表 Mapper 接口\n * </p>\n *\n * @author dyr\n * @since 2019-11-22\n */\npublic interface BrandTy",
"end": 178,
"score": 0.9996403455734253,
"start": 175,
"tag": "USERNAME",
"value": "dyr"
}
] | null |
[] |
package com.soubao.dao;
import com.soubao.entity.BrandType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 商品类型与品牌对应表 Mapper 接口
* </p>
*
* @author dyr
* @since 2019-11-22
*/
public interface BrandTypeMapper extends BaseMapper<BrandType> {
}
| 296 | 0.716912 | 0.6875 | 16 | 16 | 19.384272 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false |
5
|
1412359bd7684498fad1f520efd5ce29dda5b602
| 28,613,072,154,602 |
ae941f7684d98dd47f0425e728183d90f5784ec8
|
/app/src/main/java/com/unlockchecker/unlockchecker/fragment/HomeFragment.java
|
f1a73f4c4aa013e346385d573259e0234b7ae0fe
|
[] |
no_license
|
onecodelabs/UnlockCounter
|
https://github.com/onecodelabs/UnlockCounter
|
b09216216f5587835ee06b9ddba5d07a2e9c62eb
|
0a00da2cdecb163c51bb4b17218ad124b079f0a8
|
refs/heads/master
| 2022-08-09T11:45:57.923000 | 2016-05-21T18:54:17 | 2016-05-21T18:54:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.unlockchecker.unlockchecker.fragment;
import com.unlockchecker.unlockchecker.R;
import com.unlockchecker.unlockchecker.activity.SettingsActivity;
import com.unlockchecker.unlockchecker.activity.StatisticsActivity;
import com.unlockchecker.unlockchecker.presenter.HomePresenter;
import com.unlockchecker.unlockchecker.presenter.impl.HomePresenterImpl;
import com.unlockchecker.unlockchecker.util.NavigationUtils;
import com.unlockchecker.unlockchecker.view.HomeView;
import butterknife.OnClick;
public class HomeFragment extends BaseFragment implements HomeView {
private HomePresenter homePresenter;
public static HomeFragment instance() {
HomeFragment f = new HomeFragment();
return f;
}
@Override
protected int layout() {
return R.layout.fragment_home;
}
@Override
protected void init() {
homePresenter = new HomePresenterImpl(this);
}
@Override
protected void populate() {
}
@OnClick(R.id.fragment_home_statistics_button)
public void onStatisticsPressed() {
homePresenter.onStatisticsPressed();
}
@OnClick(R.id.fragment_home_settings_button)
public void onSettingsPressed() {
homePresenter.onSettingsPressed();
}
@Override
public void navigateToStatistics() {
NavigationUtils.jumpTo(getActivity(), StatisticsActivity.class);
}
@Override
public void navigateToSettings() {
NavigationUtils.jumpTo(getActivity(), SettingsActivity.class);
}
}
|
UTF-8
|
Java
| 1,527 |
java
|
HomeFragment.java
|
Java
|
[] | null |
[] |
package com.unlockchecker.unlockchecker.fragment;
import com.unlockchecker.unlockchecker.R;
import com.unlockchecker.unlockchecker.activity.SettingsActivity;
import com.unlockchecker.unlockchecker.activity.StatisticsActivity;
import com.unlockchecker.unlockchecker.presenter.HomePresenter;
import com.unlockchecker.unlockchecker.presenter.impl.HomePresenterImpl;
import com.unlockchecker.unlockchecker.util.NavigationUtils;
import com.unlockchecker.unlockchecker.view.HomeView;
import butterknife.OnClick;
public class HomeFragment extends BaseFragment implements HomeView {
private HomePresenter homePresenter;
public static HomeFragment instance() {
HomeFragment f = new HomeFragment();
return f;
}
@Override
protected int layout() {
return R.layout.fragment_home;
}
@Override
protected void init() {
homePresenter = new HomePresenterImpl(this);
}
@Override
protected void populate() {
}
@OnClick(R.id.fragment_home_statistics_button)
public void onStatisticsPressed() {
homePresenter.onStatisticsPressed();
}
@OnClick(R.id.fragment_home_settings_button)
public void onSettingsPressed() {
homePresenter.onSettingsPressed();
}
@Override
public void navigateToStatistics() {
NavigationUtils.jumpTo(getActivity(), StatisticsActivity.class);
}
@Override
public void navigateToSettings() {
NavigationUtils.jumpTo(getActivity(), SettingsActivity.class);
}
}
| 1,527 | 0.735429 | 0.735429 | 56 | 26.267857 | 24.251282 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
5
|
ea6750e9e35f5069ff5d35e0e350acf90d025752
| 13,718,125,596,109 |
4c3e131ada7e786a509cc67db2041f9eb242ea5b
|
/src/au/com/woolworths/mcr/bizact/LoginFromCC.java
|
0cab1e74970d4b90bfc56f4dc03e7fd21fae29a0
|
[] |
no_license
|
skumarv/myrepo
|
https://github.com/skumarv/myrepo
|
695430c116b8c811bcc3e2b5b44065b66352d792
|
63aae4851eef0fefd8793e8e46a8f788feba233e
|
refs/heads/master
| 2016-05-31T05:42:07.098000 | 2014-08-23T14:35:16 | 2014-08-23T14:35:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (C) 2009 Woolworths Limited
*
* 1 Woolworths Way Bella Vista NSW 2153 Australia
* All rights reserved.
* This software is the confidential and proprietary information of Woolworths Limited. You shall not disclose
* such confidential information and shall use it only in accordance with the terms of the licence agreement
* you entered into with Woolworths Limited.
* No part of this document may be presented, reproduced or copied in any form or by any means (graphical,
* electronic or mechanical including photocopying, recording tape or by any information storage and
* retrieval system) without the express written permission of Woolworths Ltd.
* Unpublished work.
*/
package au.com.woolworths.mcr.bizact;
import java.util.Calendar;
import java.util.TimeZone;
import com.bluemartini.bizact.Login;
import com.bluemartini.core.BMUtil;
import com.bluemartini.database.BindArray;
import com.bluemartini.database.DBUtil;
import com.bluemartini.dna.BMContext;
import com.bluemartini.dna.BMException;
import com.bluemartini.dna.BMLog;
import com.bluemartini.dna.BusinessObject;
import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAStringArray;
import com.bluemartini.util.BasicBusinessObjectUtil;
import com.bluemartini.util.MerchantUtil;
import com.bluemartini.wf.WorkflowUtil;
/**
* This class is used for overriding the out of box bizact "Login" It validates
* the current user,checks for the user existence and sets a boolean flag
* accordingly.
*
* @param - DNAList
* @return - htmlRsponse
*
* @author TCS version 1.0
*/
public class LoginFromCC extends Login {
@Override
public void initInstance() {
}
@Override
public DNAList execute(DNAList dnaIn) throws BMException {
BusinessObject boLogin = dnaIn.getBusinessObject("LOGIN");
String userid = boLogin.getString("userid");
DNAStringArray types = boLogin.getAsStringArray("type_cd");
boolean updateDB = boLogin.getBoolean("updateLoginDB", true);
DNAList dnaOut = validateLogin(userid, types, updateDB);
dnaOut.setBoolean("multiMerchantEnabled",
MerchantUtil.isMultiMerchantEnabled());
return dnaOut;
}
private static DNAList validateLogin(String userid, DNAStringArray types,
boolean updateDB) throws BMException {
String sLCName = BMUtil.toLowerCase(userid);
BindArray bindArray = new BindArray();
StringBuffer clause = new StringBuffer();
clause.append("USA_NM_LOWER=?\n");
bindArray.addString(sLCName);
clause.append(" AND ");
BasicBusinessObjectUtil.appendObjectNotDiscardedFilter(clause,
bindArray, "USA");
int size = (types != null) ? types.size() : 0;
if (size > 0) {
clause.append("\nAND USA_TYPE_CD IN (");
for (int i = 0; i < size; ++i) {
clause.append("?,");
bindArray.addString(types.elementAt(i));
}
int len = clause.length();
clause.setLength(len - 1);
clause.append(")");
}
int nFailureReason = 3;
boolean bResetStatus = false;
BusinessObject boLogin = DBUtil.selectBusinessObject("LOGIN",
clause.toString(), bindArray);
DNAList dnaOut = new DNAList();
if (boLogin != null) {
// int nFailures = boLogin.getInteger("loginFailureCount", 0);
// long usa_id = boLogin.getLong("usa_id", -1L);
String sStatus = boLogin.getString("status_cd", "I");
if (sStatus.equals("I")) {
nFailureReason = 2;
// incrementFailureCount(nFailures, usa_id);
boLogin = null;
BMLog.log(BMLog.COMPONENT_BIZACT, 1, "LOGIN_FAILED_DISABLED",
(DNAList) null);
} else if (sStatus.equals("L")) {
String userID = boLogin.getString("userid");
if ((userID.length() == 4)
&& (userID.regionMatches(0, "blue", 0, 4))) {
Calendar modifyDt = (Calendar) boLogin.getDateTime(
"modifyDt").clone();
int secs = BMContext.getAppConfig().getInteger(
"lockedOutSeconds", 30);
modifyDt.add(13, secs);
modifyDt.set(14, modifyDt.get(14));
Calendar now = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
if (!(now.before(modifyDt))) {
bResetStatus = true;
}
}
if (!(bResetStatus)) {
nFailureReason = 1;
// incrementFailureCount(nFailures, usa_id);
boLogin = null;
BMLog.log(BMLog.COMPONENT_BIZACT, 1,
"LOGIN_FAILED_LOCKEDOUT", (DNAList) null);
}
} else if (!(sStatus.equals("A"))) {
boLogin = null;
}
} else {
BMLog.log(BMLog.COMPONENT_BIZACT, 1, "LOGIN_FAILED_USERID",
(DNAList) null);
}
if (boLogin == null) {
dnaOut.setInteger("failureReason", nFailureReason);
}
dnaOut.setList("LOGIN", boLogin);
dnaOut.setBoolean("validLogin", boLogin != null);
dnaOut.setBoolean("workflowEnabled", WorkflowUtil.isWorkflowEnabled());
return dnaOut;
}
}
|
UTF-8
|
Java
| 4,860 |
java
|
LoginFromCC.java
|
Java
|
[] | null |
[] |
/*
* Copyright (C) 2009 Woolworths Limited
*
* 1 Woolworths Way Bella Vista NSW 2153 Australia
* All rights reserved.
* This software is the confidential and proprietary information of Woolworths Limited. You shall not disclose
* such confidential information and shall use it only in accordance with the terms of the licence agreement
* you entered into with Woolworths Limited.
* No part of this document may be presented, reproduced or copied in any form or by any means (graphical,
* electronic or mechanical including photocopying, recording tape or by any information storage and
* retrieval system) without the express written permission of Woolworths Ltd.
* Unpublished work.
*/
package au.com.woolworths.mcr.bizact;
import java.util.Calendar;
import java.util.TimeZone;
import com.bluemartini.bizact.Login;
import com.bluemartini.core.BMUtil;
import com.bluemartini.database.BindArray;
import com.bluemartini.database.DBUtil;
import com.bluemartini.dna.BMContext;
import com.bluemartini.dna.BMException;
import com.bluemartini.dna.BMLog;
import com.bluemartini.dna.BusinessObject;
import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAStringArray;
import com.bluemartini.util.BasicBusinessObjectUtil;
import com.bluemartini.util.MerchantUtil;
import com.bluemartini.wf.WorkflowUtil;
/**
* This class is used for overriding the out of box bizact "Login" It validates
* the current user,checks for the user existence and sets a boolean flag
* accordingly.
*
* @param - DNAList
* @return - htmlRsponse
*
* @author TCS version 1.0
*/
public class LoginFromCC extends Login {
@Override
public void initInstance() {
}
@Override
public DNAList execute(DNAList dnaIn) throws BMException {
BusinessObject boLogin = dnaIn.getBusinessObject("LOGIN");
String userid = boLogin.getString("userid");
DNAStringArray types = boLogin.getAsStringArray("type_cd");
boolean updateDB = boLogin.getBoolean("updateLoginDB", true);
DNAList dnaOut = validateLogin(userid, types, updateDB);
dnaOut.setBoolean("multiMerchantEnabled",
MerchantUtil.isMultiMerchantEnabled());
return dnaOut;
}
private static DNAList validateLogin(String userid, DNAStringArray types,
boolean updateDB) throws BMException {
String sLCName = BMUtil.toLowerCase(userid);
BindArray bindArray = new BindArray();
StringBuffer clause = new StringBuffer();
clause.append("USA_NM_LOWER=?\n");
bindArray.addString(sLCName);
clause.append(" AND ");
BasicBusinessObjectUtil.appendObjectNotDiscardedFilter(clause,
bindArray, "USA");
int size = (types != null) ? types.size() : 0;
if (size > 0) {
clause.append("\nAND USA_TYPE_CD IN (");
for (int i = 0; i < size; ++i) {
clause.append("?,");
bindArray.addString(types.elementAt(i));
}
int len = clause.length();
clause.setLength(len - 1);
clause.append(")");
}
int nFailureReason = 3;
boolean bResetStatus = false;
BusinessObject boLogin = DBUtil.selectBusinessObject("LOGIN",
clause.toString(), bindArray);
DNAList dnaOut = new DNAList();
if (boLogin != null) {
// int nFailures = boLogin.getInteger("loginFailureCount", 0);
// long usa_id = boLogin.getLong("usa_id", -1L);
String sStatus = boLogin.getString("status_cd", "I");
if (sStatus.equals("I")) {
nFailureReason = 2;
// incrementFailureCount(nFailures, usa_id);
boLogin = null;
BMLog.log(BMLog.COMPONENT_BIZACT, 1, "LOGIN_FAILED_DISABLED",
(DNAList) null);
} else if (sStatus.equals("L")) {
String userID = boLogin.getString("userid");
if ((userID.length() == 4)
&& (userID.regionMatches(0, "blue", 0, 4))) {
Calendar modifyDt = (Calendar) boLogin.getDateTime(
"modifyDt").clone();
int secs = BMContext.getAppConfig().getInteger(
"lockedOutSeconds", 30);
modifyDt.add(13, secs);
modifyDt.set(14, modifyDt.get(14));
Calendar now = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
if (!(now.before(modifyDt))) {
bResetStatus = true;
}
}
if (!(bResetStatus)) {
nFailureReason = 1;
// incrementFailureCount(nFailures, usa_id);
boLogin = null;
BMLog.log(BMLog.COMPONENT_BIZACT, 1,
"LOGIN_FAILED_LOCKEDOUT", (DNAList) null);
}
} else if (!(sStatus.equals("A"))) {
boLogin = null;
}
} else {
BMLog.log(BMLog.COMPONENT_BIZACT, 1, "LOGIN_FAILED_USERID",
(DNAList) null);
}
if (boLogin == null) {
dnaOut.setInteger("failureReason", nFailureReason);
}
dnaOut.setList("LOGIN", boLogin);
dnaOut.setBoolean("validLogin", boLogin != null);
dnaOut.setBoolean("workflowEnabled", WorkflowUtil.isWorkflowEnabled());
return dnaOut;
}
}
| 4,860 | 0.684979 | 0.677778 | 149 | 30.630873 | 24.42585 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.610738 | false | false |
5
|
a96d6d96d52e6062e84c348f2158c1baf42cd33a
| 17,471,927,025,161 |
4639c4b60d5a67e4cf045c00d95ed3dd61062cfe
|
/Web Service/ca-ws-sdk/rest/java/test2_auths/HMACUtil.java
|
a1324ed13821caae9800beac7e47950147d5a355
|
[] |
no_license
|
cerebnismus/python3.7-practice
|
https://github.com/cerebnismus/python3.7-practice
|
57589e0bac81d7b7c37c894734192a1202034cda
|
75566149bbb6e1d871e04c777af94e065c6024d4
|
refs/heads/master
| 2023-01-03T09:09:40.008000 | 2021-12-29T19:53:54 | 2021-12-29T19:53:54 | 202,933,740 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 CA. All rights reserved.
//
// This software and all information contained therein is confidential and
// proprietary and shall not be duplicated, used, disclosed or disseminated
// in any way except as authorized by the applicable license agreement,
// without the express written permission of CA. All authorized
// reproductions must be marked with this language.
//
// EXCEPT AS SET FORTH IN THE APPLICABLE LICENSE AGREEMENT, TO THE EXTENT
// PERMITTED BY APPLICABLE LAW, CA PROVIDES THIS SOFTWARE WITHOUT WARRANTY
// OF ANY KIND, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL
// CA BE LIABLE TO THE END USER OR ANY THIRD PARTY FOR ANY LOSS OR DAMAGE,
// DIRECT OR INDIRECT, FROM THE USE OF THIS SOFTWARE, INCLUDING WITHOUT
// LIMITATION, LOST PROFITS, BUSINESS INTERRUPTION, GOODWILL, OR LOST DATA,
// EVEN IF CA IS EXPRESSLY ADVISED OF SUCH LOSS OR DAMAGE.
///////////////////////////////////////////////////////////////////////////
// $Id: $
// Module : HMACUtil.java
// Created : 2012/04/11 12:24:25
// Java Ver : 1.6
// Description:
//
///////////////////////////////////////////////////////////////////////////
// README! README! README! README! README! README!
//
// Description:
// This class file contains sample code for invoking Service Desk REST Web Services.
//
// THIS SHOULD BE RUN IN A TEST ENVIRONMENT AGAINST A TEST SERVICE DESK SERVER!
// The routines in this file will create and modify Service Desk objects!
//
/////////////////////////////////////////////////////////////////////////
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* Utility class for signing requests for SDM custom authentication.
*
* @author valre03
* @version $Revision: ASPEN.0 $
*/
public class HMACUtil
{
private static final String UTF8_CHARSET = "UTF-8";
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA1";
private String secretKey = null;
private Mac mac = null;
public HMACUtil(String secretKey)
{
this.secretKey = secretKey;
try {
init();
} catch (Exception e) {
this.secretKey = null;
this.mac = null;
e.printStackTrace();
}
}
private void init()
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException
{
byte[] secretyKeyBytes = this.secretKey.getBytes(UTF8_CHARSET);
this.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
this.mac.init(new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM));
}
public String signHeader(String method, String uri, Map<String, String> params)
{
String toSign = method + "\n" + uri;
if ( ! params.isEmpty() ) {
SortedMap<String, String> sortedParamMap = new TreeMap<String, String>(params);
toSign += "\n" + canonicalize(sortedParamMap);
}
return percentEncodeRfc3986(hmac(toSign));
}
private static String canonicalize(SortedMap<String, String> sortedParamMap)
{
if ( sortedParamMap.isEmpty() )
return "";
StringBuffer buffer = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry<String, String> kvpair = iter.next();
buffer.append(percentEncodeRfc3986(kvpair.getKey()));
buffer.append("=");
buffer.append(percentEncodeRfc3986(kvpair.getValue()));
if ( iter.hasNext() )
buffer.append("&");
}
return buffer.toString();
}
private static String percentEncodeRfc3986(String s) {
String out;
try {
out = URLEncoder.encode(s, UTF8_CHARSET)
.replace("+", "%20")
.replace("*", "%2A")
.replace("%7E", "~");
} catch (UnsupportedEncodingException e) {
out = s;
e.printStackTrace();
}
return out;
}
private String hmac(String stringToSign)
{
String signature = null;
try {
byte[] data = stringToSign.getBytes(UTF8_CHARSET);
byte[] rawHmac = this.mac.doFinal(data);
signature = new String(new Base64().encode(rawHmac));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return signature;
}
}
|
UTF-8
|
Java
| 4,653 |
java
|
HMACUtil.java
|
Java
|
[
{
"context": "sts for SDM custom authentication.\r\n *\r\n * @author valre03\r\n * @version $Revision: ASPEN.0 $\r\n */\r\npublic cl",
"end": 2256,
"score": 0.9995498061180115,
"start": 2249,
"tag": "USERNAME",
"value": "valre03"
}
] | null |
[] |
////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 CA. All rights reserved.
//
// This software and all information contained therein is confidential and
// proprietary and shall not be duplicated, used, disclosed or disseminated
// in any way except as authorized by the applicable license agreement,
// without the express written permission of CA. All authorized
// reproductions must be marked with this language.
//
// EXCEPT AS SET FORTH IN THE APPLICABLE LICENSE AGREEMENT, TO THE EXTENT
// PERMITTED BY APPLICABLE LAW, CA PROVIDES THIS SOFTWARE WITHOUT WARRANTY
// OF ANY KIND, INCLUDING WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL
// CA BE LIABLE TO THE END USER OR ANY THIRD PARTY FOR ANY LOSS OR DAMAGE,
// DIRECT OR INDIRECT, FROM THE USE OF THIS SOFTWARE, INCLUDING WITHOUT
// LIMITATION, LOST PROFITS, BUSINESS INTERRUPTION, GOODWILL, OR LOST DATA,
// EVEN IF CA IS EXPRESSLY ADVISED OF SUCH LOSS OR DAMAGE.
///////////////////////////////////////////////////////////////////////////
// $Id: $
// Module : HMACUtil.java
// Created : 2012/04/11 12:24:25
// Java Ver : 1.6
// Description:
//
///////////////////////////////////////////////////////////////////////////
// README! README! README! README! README! README!
//
// Description:
// This class file contains sample code for invoking Service Desk REST Web Services.
//
// THIS SHOULD BE RUN IN A TEST ENVIRONMENT AGAINST A TEST SERVICE DESK SERVER!
// The routines in this file will create and modify Service Desk objects!
//
/////////////////////////////////////////////////////////////////////////
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
* Utility class for signing requests for SDM custom authentication.
*
* @author valre03
* @version $Revision: ASPEN.0 $
*/
public class HMACUtil
{
private static final String UTF8_CHARSET = "UTF-8";
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA1";
private String secretKey = null;
private Mac mac = null;
public HMACUtil(String secretKey)
{
this.secretKey = secretKey;
try {
init();
} catch (Exception e) {
this.secretKey = null;
this.mac = null;
e.printStackTrace();
}
}
private void init()
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException
{
byte[] secretyKeyBytes = this.secretKey.getBytes(UTF8_CHARSET);
this.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
this.mac.init(new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM));
}
public String signHeader(String method, String uri, Map<String, String> params)
{
String toSign = method + "\n" + uri;
if ( ! params.isEmpty() ) {
SortedMap<String, String> sortedParamMap = new TreeMap<String, String>(params);
toSign += "\n" + canonicalize(sortedParamMap);
}
return percentEncodeRfc3986(hmac(toSign));
}
private static String canonicalize(SortedMap<String, String> sortedParamMap)
{
if ( sortedParamMap.isEmpty() )
return "";
StringBuffer buffer = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry<String, String> kvpair = iter.next();
buffer.append(percentEncodeRfc3986(kvpair.getKey()));
buffer.append("=");
buffer.append(percentEncodeRfc3986(kvpair.getValue()));
if ( iter.hasNext() )
buffer.append("&");
}
return buffer.toString();
}
private static String percentEncodeRfc3986(String s) {
String out;
try {
out = URLEncoder.encode(s, UTF8_CHARSET)
.replace("+", "%20")
.replace("*", "%2A")
.replace("%7E", "~");
} catch (UnsupportedEncodingException e) {
out = s;
e.printStackTrace();
}
return out;
}
private String hmac(String stringToSign)
{
String signature = null;
try {
byte[] data = stringToSign.getBytes(UTF8_CHARSET);
byte[] rawHmac = this.mac.doFinal(data);
signature = new String(new Base64().encode(rawHmac));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return signature;
}
}
| 4,653 | 0.645175 | 0.63185 | 149 | 29.214766 | 27.0266 | 85 | false | false | 0 | 0 | 0 | 0 | 76 | 0.064904 | 1.597315 | false | false |
5
|
c4a20272a373fa8830aff07a6ac30678fa621ad1
| 29,738,353,595,441 |
36beaf5682aca1bf08867e953d9dbf058afa5fe9
|
/vendor/amlogic/common/external/DTVKit/android-inputsource/app/src/main/droidlogic/java/com/droidlogic/fragment/dialog/DialogItemListView.java
|
2f837dc51c873c001bfd529d784890cdac7c29cf
|
[] |
no_license
|
toneywoo/BPI-S905X3-Android9
|
https://github.com/toneywoo/BPI-S905X3-Android9
|
64f8f1673de0728e2bb1d6018b1260168564e856
|
b190a356b062c1119e8a78ac369da99162429371
|
refs/heads/master
| 2023-06-23T05:11:26.210000 | 2023-04-24T03:42:48 | 2023-04-24T03:42:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.droidlogic.fragment.dialog;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.droidlogic.fragment.ParameterMananer;
//import com.droidlogic.fragment.R;
import org.dtvkit.inputsource.R;
public class DialogItemListView extends ListView implements OnItemSelectedListener/*, AdapterView.OnItemClickListener, , View.OnFocusChangeListener*/ {
private static final String TAG = "DialogItemListView";
private Context mContext;
private ViewGroup rootView = null;
//private ListItemSelectedListener mListItemSelectedListener;
//private ListItemFocusedListener mListItemFocusedListener;
private String mTitle = null;
private String mKey = null;
private int selectedPosition = 0;
private DialogCallBack mDialogCallBack = null;
private CustomDialog.DialogUiCallBack mDialogUiCallBack = null;
public DialogItemListView(Context context) {
super(context);
mContext = context;
setRootView();
setOnItemSelectedListener(this);
}
public DialogItemListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setRootView();
setOnItemSelectedListener(this);
}
public void setDialogCallBack(DialogCallBack callback) {
mDialogCallBack = callback;
}
public void setDialogUiCallBack(CustomDialog.DialogUiCallBack callback) {
mDialogUiCallBack = callback;
}
public boolean dispatchKeyEvent (KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
if (selectedPosition == 0)
return true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectedPosition == getAdapter().getCount() - 1)
return true;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
//if (ParameterMananer.KEY_UNICABLE.equals(getKey())) {
Bundle bundle1 = new Bundle();
bundle1.putString("action", event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT ? "left" : "right");
bundle1.putInt("position", getSelectedItemPosition());
bundle1.putString("title", mTitle);
bundle1.putString("key", mKey);
mDialogCallBack.onStatusChange(getSelectedView(), mKey, bundle1);
return true;
//}
//return super.dispatchKeyEvent(event);
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_NUMPAD_ENTER:
if (mDialogCallBack != null) {
int position = getSelectedItemPosition();
/*if ((ParameterMananer.KEY_SATALLITE.equals(getKey()) && position == 0) || (ParameterMananer.KEY_TRANSPONDER.equals(getKey()) && position == 1)) {
Log.d(TAG, "satellite or transponder no response");
return true;
}*/
Bundle bundle2 = new Bundle();
bundle2.putString("action", "selected");
bundle2.putInt("position", position);
bundle2.putString("title", mTitle);
bundle2.putString("key", mKey);
mDialogCallBack.onStatusChange(getSelectedView(), mKey, bundle2);
}
return true;
}
View selectedView = getSelectedView();
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
if ( selectedView != null) {
clearChoosed(selectedView);
}
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
if ( selectedView != null) {
//setItemTextColor(selectedView, false);
}
break;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected view = " + view +", position = " + position + ", id = " + id);
selectedPosition = position;
if (view != null) {
setChoosed(view);
}
/*etDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
if (view != null) {
EditText edit = (EditText)view.findViewById(R.id.editText);
if (edit != null) {
edit.requestFocus();
}
}*/
if (mDialogCallBack != null) {
Bundle bundle = new Bundle();
bundle.putString("action", "focused");
bundle.putInt("position", position);
bundle.putString("title", mTitle);
bundle.putString("key", mKey);
mDialogCallBack.onStatusChange(view, mKey, bundle);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d(TAG, "onNothingSelected");
/*setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);*/
}
@Override
protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
Log.d(TAG, "onFocusChanged gainFocus = " + gainFocus +", direction = " + direction + ", previouslyFocusedRect = "+ previouslyFocusedRect);
}
/*@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d(TAG, "onFocusChange view = " + v +", hasFocus = " + hasFocus);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick view = " + view +", position = " + position);
}*/
private void setItemTextColor (View view, boolean focused) {
if (focused) {
int color_text_focused = mContext.getResources().getColor(R.color.common_focus);
for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
View child = ((ViewGroup)view).getChildAt(i);
if (child instanceof TextView) {
((TextView)child).setTextColor(color_text_focused);
}
}
} else {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
View child = ((ViewGroup)view).getChildAt(i);
if (child instanceof TextView) {
((TextView)child).setTextColor(color_text_item);
}
}
}
}
private void setRootView() {
rootView = ((ViewGroup)((Activity)mContext).findViewById(android.R.id.content));
}
private boolean hasNextFocusView(int dec) {
if (FocusFinder.getInstance().findNextFocus(rootView, this, dec) == null) {
return false;
} else {
return true;
}
}
public void cleanChoosed() {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
for (int i = 0; i < getChildCount(); i ++) {
View view = getChildAt(i);
view.setBackgroundColor(color_text_item);
}
}
public void clearChoosed(View view) {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
view.setBackgroundColor(color_text_item);
}
public void setChoosed(View view) {
int color_text_focused = mContext.getResources().getColor(R.color.common_focus);
view.setBackgroundColor(color_text_focused);
}
public void setTitle(String title) {
mTitle = title;
}
public void setKey(String key) {
mKey = key;
}
public String getTitle() {
return mTitle;
}
public String getKey() {
return mKey;
}
/*public void setListItemSelectedListener(ListItemSelectedListener l) {
mListItemSelectedListener = l;
}
public void setListItemFocusedListener(ListItemFocusedListener l) {
mListItemFocusedListener = l;
}
public interface ListItemSelectedListener {
void onListItemSelected(int position, String type);
}
public interface ListItemFocusedListener {
void onListItemFocused(View parent, int position, String type);
}*/
}
|
UTF-8
|
Java
| 9,248 |
java
|
DialogItemListView.java
|
Java
|
[] | null |
[] |
package com.droidlogic.fragment.dialog;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.droidlogic.fragment.ParameterMananer;
//import com.droidlogic.fragment.R;
import org.dtvkit.inputsource.R;
public class DialogItemListView extends ListView implements OnItemSelectedListener/*, AdapterView.OnItemClickListener, , View.OnFocusChangeListener*/ {
private static final String TAG = "DialogItemListView";
private Context mContext;
private ViewGroup rootView = null;
//private ListItemSelectedListener mListItemSelectedListener;
//private ListItemFocusedListener mListItemFocusedListener;
private String mTitle = null;
private String mKey = null;
private int selectedPosition = 0;
private DialogCallBack mDialogCallBack = null;
private CustomDialog.DialogUiCallBack mDialogUiCallBack = null;
public DialogItemListView(Context context) {
super(context);
mContext = context;
setRootView();
setOnItemSelectedListener(this);
}
public DialogItemListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setRootView();
setOnItemSelectedListener(this);
}
public void setDialogCallBack(DialogCallBack callback) {
mDialogCallBack = callback;
}
public void setDialogUiCallBack(CustomDialog.DialogUiCallBack callback) {
mDialogUiCallBack = callback;
}
public boolean dispatchKeyEvent (KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
if (selectedPosition == 0)
return true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectedPosition == getAdapter().getCount() - 1)
return true;
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
//if (ParameterMananer.KEY_UNICABLE.equals(getKey())) {
Bundle bundle1 = new Bundle();
bundle1.putString("action", event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT ? "left" : "right");
bundle1.putInt("position", getSelectedItemPosition());
bundle1.putString("title", mTitle);
bundle1.putString("key", mKey);
mDialogCallBack.onStatusChange(getSelectedView(), mKey, bundle1);
return true;
//}
//return super.dispatchKeyEvent(event);
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_NUMPAD_ENTER:
if (mDialogCallBack != null) {
int position = getSelectedItemPosition();
/*if ((ParameterMananer.KEY_SATALLITE.equals(getKey()) && position == 0) || (ParameterMananer.KEY_TRANSPONDER.equals(getKey()) && position == 1)) {
Log.d(TAG, "satellite or transponder no response");
return true;
}*/
Bundle bundle2 = new Bundle();
bundle2.putString("action", "selected");
bundle2.putInt("position", position);
bundle2.putString("title", mTitle);
bundle2.putString("key", mKey);
mDialogCallBack.onStatusChange(getSelectedView(), mKey, bundle2);
}
return true;
}
View selectedView = getSelectedView();
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
if ( selectedView != null) {
clearChoosed(selectedView);
}
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
if ( selectedView != null) {
//setItemTextColor(selectedView, false);
}
break;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected view = " + view +", position = " + position + ", id = " + id);
selectedPosition = position;
if (view != null) {
setChoosed(view);
}
/*etDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
if (view != null) {
EditText edit = (EditText)view.findViewById(R.id.editText);
if (edit != null) {
edit.requestFocus();
}
}*/
if (mDialogCallBack != null) {
Bundle bundle = new Bundle();
bundle.putString("action", "focused");
bundle.putInt("position", position);
bundle.putString("title", mTitle);
bundle.putString("key", mKey);
mDialogCallBack.onStatusChange(view, mKey, bundle);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d(TAG, "onNothingSelected");
/*setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);*/
}
@Override
protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
Log.d(TAG, "onFocusChanged gainFocus = " + gainFocus +", direction = " + direction + ", previouslyFocusedRect = "+ previouslyFocusedRect);
}
/*@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d(TAG, "onFocusChange view = " + v +", hasFocus = " + hasFocus);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick view = " + view +", position = " + position);
}*/
private void setItemTextColor (View view, boolean focused) {
if (focused) {
int color_text_focused = mContext.getResources().getColor(R.color.common_focus);
for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
View child = ((ViewGroup)view).getChildAt(i);
if (child instanceof TextView) {
((TextView)child).setTextColor(color_text_focused);
}
}
} else {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
View child = ((ViewGroup)view).getChildAt(i);
if (child instanceof TextView) {
((TextView)child).setTextColor(color_text_item);
}
}
}
}
private void setRootView() {
rootView = ((ViewGroup)((Activity)mContext).findViewById(android.R.id.content));
}
private boolean hasNextFocusView(int dec) {
if (FocusFinder.getInstance().findNextFocus(rootView, this, dec) == null) {
return false;
} else {
return true;
}
}
public void cleanChoosed() {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
for (int i = 0; i < getChildCount(); i ++) {
View view = getChildAt(i);
view.setBackgroundColor(color_text_item);
}
}
public void clearChoosed(View view) {
int color_text_item = mContext.getResources().getColor(R.color.common_item_background);
view.setBackgroundColor(color_text_item);
}
public void setChoosed(View view) {
int color_text_focused = mContext.getResources().getColor(R.color.common_focus);
view.setBackgroundColor(color_text_focused);
}
public void setTitle(String title) {
mTitle = title;
}
public void setKey(String key) {
mKey = key;
}
public String getTitle() {
return mTitle;
}
public String getKey() {
return mKey;
}
/*public void setListItemSelectedListener(ListItemSelectedListener l) {
mListItemSelectedListener = l;
}
public void setListItemFocusedListener(ListItemFocusedListener l) {
mListItemFocusedListener = l;
}
public interface ListItemSelectedListener {
void onListItemSelected(int position, String type);
}
public interface ListItemFocusedListener {
void onListItemFocused(View parent, int position, String type);
}*/
}
| 9,248 | 0.589857 | 0.587695 | 246 | 36.585365 | 29.797262 | 171 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.686992 | false | false |
5
|
76bc89ad7941e3b5174872233a529b05bf5c65fd
| 14,929,306,366,573 |
fd2e6d17fe8abad8585d996894db9957757fa019
|
/High-availability-Internet-collection-system-and-distributed-search-application/src/main/java/com/sdu/repository/ModelRepository.java
|
670a31e541641f493e5d42a6b046274b14cbda96
|
[] |
no_license
|
SparkJiao/High-availability-Internet-collection-system-and-distributed-search-application
|
https://github.com/SparkJiao/High-availability-Internet-collection-system-and-distributed-search-application
|
b0d18b7ad59a3ee0a01a2c4a101e73fac444ced5
|
86b24531f0b571514105dfe827a441e555e47714
|
refs/heads/master
| 2020-03-22T02:36:40.951000 | 2018-07-25T09:11:05 | 2018-07-25T09:11:05 | 139,382,279 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sdu.repository;
import com.sdu.entity.Model;
import com.sdu.utils.MatchModel;
import com.sdu.utils.MatchView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by kkkkkk on 2018/7/16.
*/
public interface ModelRepository extends JpaRepository<Model, Integer>{
List<Model> findModelsByStartUrlAndCurrentLevelOrderByCurrentLevel(String startUrl, int currentLevel);
List<Model> findModelsByStartUrlOrderByCurrentLevel(String startUrl);
@Transactional
void deleteModelsByStartUrl(String startUrl);
}
|
UTF-8
|
Java
| 699 |
java
|
ModelRepository.java
|
Java
|
[
{
"context": "tional;\n\nimport java.util.List;\n\n/**\n * Created by kkkkkk on 2018/7/16.\n */\npublic interface ModelRepositor",
"end": 353,
"score": 0.9993256330490112,
"start": 347,
"tag": "USERNAME",
"value": "kkkkkk"
}
] | null |
[] |
package com.sdu.repository;
import com.sdu.entity.Model;
import com.sdu.utils.MatchModel;
import com.sdu.utils.MatchView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by kkkkkk on 2018/7/16.
*/
public interface ModelRepository extends JpaRepository<Model, Integer>{
List<Model> findModelsByStartUrlAndCurrentLevelOrderByCurrentLevel(String startUrl, int currentLevel);
List<Model> findModelsByStartUrlOrderByCurrentLevel(String startUrl);
@Transactional
void deleteModelsByStartUrl(String startUrl);
}
| 699 | 0.812589 | 0.802575 | 23 | 29.391304 | 29.668808 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false |
5
|
4d8e3db6822abc8125fe2b9f62ebaba22ecbbd2f
| 13,091,060,375,830 |
6bb3001ed2d99155380864e011ba69270e09f60b
|
/src/main/java/red/niloy/blog/web/editor/PostEditor.java
|
488b7a9a069f8a9715be16f3bcda7f85e77422ed
|
[] |
no_license
|
shadowxiehao/SpringMVC-Hibernate-Gradle-Project
|
https://github.com/shadowxiehao/SpringMVC-Hibernate-Gradle-Project
|
6283931422becfb37a4fb13698ff5afa8a33d4c6
|
9e45e44037be68cfd15d3124b247eccd2cb11249
|
refs/heads/master
| 2023-03-16T03:29:51.422000 | 2020-02-22T09:41:29 | 2020-02-22T09:41:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package red.niloy.blog.web.editor;
import red.niloy.blog.domain.Post;
import red.niloy.blog.service.PostService;
import java.beans.PropertyEditorSupport;
import java.util.Objects;
/**
* @author sajjad.ahmed
* @since 9/24/19.
*/
public class PostEditor extends PropertyEditorSupport {
private PostService postService;
public PostEditor(PostService postService) {
this.postService = postService;
}
public String getAsText() {
Post post = (Post) this.getValue();
return Objects.nonNull(post) ? String.valueOf(post.getId()) : null;
}
public void setAsText(String text) {
if (text.isEmpty()) {
setValue(null);
return;
}
int id = Integer.parseInt(text);
if (id > 0) {
Post post = postService.find(Long.parseLong(text)).get();
setValue(post);
}
}
}
|
UTF-8
|
Java
| 892 |
java
|
PostEditor.java
|
Java
|
[
{
"context": "Support;\nimport java.util.Objects;\n\n/**\n * @author sajjad.ahmed\n * @since 9/24/19.\n */\npublic class PostEditor ex",
"end": 210,
"score": 0.987246036529541,
"start": 198,
"tag": "NAME",
"value": "sajjad.ahmed"
}
] | null |
[] |
package red.niloy.blog.web.editor;
import red.niloy.blog.domain.Post;
import red.niloy.blog.service.PostService;
import java.beans.PropertyEditorSupport;
import java.util.Objects;
/**
* @author sajjad.ahmed
* @since 9/24/19.
*/
public class PostEditor extends PropertyEditorSupport {
private PostService postService;
public PostEditor(PostService postService) {
this.postService = postService;
}
public String getAsText() {
Post post = (Post) this.getValue();
return Objects.nonNull(post) ? String.valueOf(post.getId()) : null;
}
public void setAsText(String text) {
if (text.isEmpty()) {
setValue(null);
return;
}
int id = Integer.parseInt(text);
if (id > 0) {
Post post = postService.find(Long.parseLong(text)).get();
setValue(post);
}
}
}
| 892 | 0.624439 | 0.617713 | 37 | 23.108109 | 20.332087 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.378378 | false | false |
5
|
da6c9da83eb5bdb373d63a9f7211418dcfea4044
| 1,846,835,990,119 |
c6043b7f1572b6e356da373c1dc82a4a0f41dc35
|
/app/src/main/java/com/example/paginationtutorial/utils/NetworkCall.java
|
30d8f7f557b5958f4b97d05684a6a05ef5f8d047
|
[] |
no_license
|
PoroshMondal/PaginationTutorial
|
https://github.com/PoroshMondal/PaginationTutorial
|
db18a5e069f4d4751b3b20196bcc7934cd9a6dd7
|
94cebb197e6a4f2eeb5cda3bd610902d401dac6c
|
refs/heads/master
| 2020-04-20T15:27:21.545000 | 2019-02-03T09:57:06 | 2019-02-03T09:57:06 | 168,930,418 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.paginationtutorial.utils;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.paginationtutorial.interfaces.VolleyCallback;
public class NetworkCall {
private Context context;
private VolleyCallback volleyCallback;
public NetworkCall(Context context) {
this.context = context;
}
public void setVolleyCallbackListener(VolleyCallback volleyCallback) {
this.volleyCallback = volleyCallback;
}
public void requestToServer(String url) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
volleyCallback.onSuccessResponse(response);
//Log.d("json_data",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Failed to fetch data !", Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(context.getApplicationContext()).addToRequestQueue(stringRequest);
}
}
|
UTF-8
|
Java
| 1,421 |
java
|
NetworkCall.java
|
Java
|
[] | null |
[] |
package com.example.paginationtutorial.utils;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.paginationtutorial.interfaces.VolleyCallback;
public class NetworkCall {
private Context context;
private VolleyCallback volleyCallback;
public NetworkCall(Context context) {
this.context = context;
}
public void setVolleyCallbackListener(VolleyCallback volleyCallback) {
this.volleyCallback = volleyCallback;
}
public void requestToServer(String url) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
volleyCallback.onSuccessResponse(response);
//Log.d("json_data",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Failed to fetch data !", Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(context.getApplicationContext()).addToRequestQueue(stringRequest);
}
}
| 1,421 | 0.658691 | 0.658691 | 44 | 31.295454 | 27.20426 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522727 | false | false |
5
|
e1121e686098fb1feb694de73c8cef954a5a393f
| 6,073,083,816,511 |
6b95be426d7c078cd4a7b70efef786e77131bc1a
|
/Portlet/vsitemap-portlet/docroot/WEB-INF/src/com/vportal/portal/util/ImageUtilExt.java
|
f8c886cb45773a6cab58c663c813ff6a60023ba5
|
[] |
no_license
|
thaond/eGov_Portal
|
https://github.com/thaond/eGov_Portal
|
abf93cf2c04aff76f3833d2ab38db77b8b71d08e
|
00071bb4f657b6ae8fe763308dc3391e6e58a49a
|
refs/heads/master
| 2020-12-31T05:24:47.121000 | 2013-08-23T07:32:43 | 2013-08-23T07:32:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Copyright (c) Vietsoftware, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.vportal.portal.util;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.persistence.ImageUtil;
/**
* @author
* @version 1.0.00, May 15, 2007
*/
public class ImageUtilExt extends ImageUtil {
public static void saveOriginalImage(long largePhotoKey, byte[] photoBytes) {
if (photoBytes != null && Validator.isNotNull(String.valueOf(largePhotoKey))) {
try {
ImageLocalServiceUtil.updateImage(largePhotoKey, photoBytes);
} catch (Exception ce) {
ce.printStackTrace();
}
}
}
public static void saveThumbnail(long thumbnailKey,
BufferedImage bufferedImage, String contentType, int maxWidth,
int maxHeight) {
if (bufferedImage != null && Validator.isNotNull(String.valueOf(thumbnailKey))) {
BufferedImage thumbnail = advancedScale(bufferedImage, maxHeight,
maxWidth);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (contentType.indexOf("gif") != -1) {
// ImageUtil.encodeGIF(thumbnail, baos);
} else if (contentType.indexOf("jpg") != -1
|| contentType.indexOf("jpeg") != -1) {
ImageIO.write(thumbnail, "jpeg", baos);
} else if (contentType.indexOf("png") != -1) {
ImageIO.write(thumbnail, "png", baos);
}
ImageLocalServiceUtil.updateImage(thumbnailKey, baos.toByteArray());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
public static void deleteImage(long photoKey) {
try {
com.liferay.portal.model.Image image = ImageLocalServiceUtil.getImage(photoKey);
ImageLocalServiceUtil.deleteImage(image.getImageId());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public static boolean isImage(String contentType) {
if (Validator.isNull(contentType)) {
return false;
}
return !(contentType.indexOf("gif") == -1
&& contentType.indexOf("jpg") == -1
&& contentType.indexOf("jpeg") == -1 && contentType
.indexOf("png") == -1);
}
public static BufferedImage advancedScale(BufferedImage src, int maxHeight,
int maxWidth) {
int imageHeight = src.getHeight();
int imageWidth = src.getWidth();
if (maxHeight == 0) {
maxHeight = imageHeight;
}
if (maxWidth == 0) {
maxWidth = imageWidth;
}
if ((imageHeight <= maxHeight) && (imageWidth <= maxWidth)) {
return src;
}
double factor = 0.1;
int heightDelta = imageHeight - maxHeight;
int widthDelta = imageWidth - maxWidth;
if (heightDelta > widthDelta) {
factor = (double) maxHeight / imageHeight;
} else {
factor = (double) maxWidth / imageWidth;
}
RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
ParameterBlock paramBlock = new ParameterBlock();
paramBlock.addSource(src);
paramBlock.add(factor); // xscale
paramBlock.add(factor); // yscale
RenderedOp resizedImage = JAI.create("SubsampleAverage", paramBlock,
qualityHints);
return resizedImage.getAsBufferedImage();
}
}
|
UTF-8
|
Java
| 3,918 |
java
|
ImageUtilExt.java
|
Java
|
[] | null |
[] |
/**
* Copyright (c) Vietsoftware, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.vportal.portal.util;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.service.ImageLocalServiceUtil;
import com.liferay.portal.service.persistence.ImageUtil;
/**
* @author
* @version 1.0.00, May 15, 2007
*/
public class ImageUtilExt extends ImageUtil {
public static void saveOriginalImage(long largePhotoKey, byte[] photoBytes) {
if (photoBytes != null && Validator.isNotNull(String.valueOf(largePhotoKey))) {
try {
ImageLocalServiceUtil.updateImage(largePhotoKey, photoBytes);
} catch (Exception ce) {
ce.printStackTrace();
}
}
}
public static void saveThumbnail(long thumbnailKey,
BufferedImage bufferedImage, String contentType, int maxWidth,
int maxHeight) {
if (bufferedImage != null && Validator.isNotNull(String.valueOf(thumbnailKey))) {
BufferedImage thumbnail = advancedScale(bufferedImage, maxHeight,
maxWidth);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
if (contentType.indexOf("gif") != -1) {
// ImageUtil.encodeGIF(thumbnail, baos);
} else if (contentType.indexOf("jpg") != -1
|| contentType.indexOf("jpeg") != -1) {
ImageIO.write(thumbnail, "jpeg", baos);
} else if (contentType.indexOf("png") != -1) {
ImageIO.write(thumbnail, "png", baos);
}
ImageLocalServiceUtil.updateImage(thumbnailKey, baos.toByteArray());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
public static void deleteImage(long photoKey) {
try {
com.liferay.portal.model.Image image = ImageLocalServiceUtil.getImage(photoKey);
ImageLocalServiceUtil.deleteImage(image.getImageId());
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public static boolean isImage(String contentType) {
if (Validator.isNull(contentType)) {
return false;
}
return !(contentType.indexOf("gif") == -1
&& contentType.indexOf("jpg") == -1
&& contentType.indexOf("jpeg") == -1 && contentType
.indexOf("png") == -1);
}
public static BufferedImage advancedScale(BufferedImage src, int maxHeight,
int maxWidth) {
int imageHeight = src.getHeight();
int imageWidth = src.getWidth();
if (maxHeight == 0) {
maxHeight = imageHeight;
}
if (maxWidth == 0) {
maxWidth = imageWidth;
}
if ((imageHeight <= maxHeight) && (imageWidth <= maxWidth)) {
return src;
}
double factor = 0.1;
int heightDelta = imageHeight - maxHeight;
int widthDelta = imageWidth - maxWidth;
if (heightDelta > widthDelta) {
factor = (double) maxHeight / imageHeight;
} else {
factor = (double) maxWidth / imageWidth;
}
RenderingHints qualityHints = new RenderingHints(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
ParameterBlock paramBlock = new ParameterBlock();
paramBlock.addSource(src);
paramBlock.add(factor); // xscale
paramBlock.add(factor); // yscale
RenderedOp resizedImage = JAI.create("SubsampleAverage", paramBlock,
qualityHints);
return resizedImage.getAsBufferedImage();
}
}
| 3,918 | 0.708525 | 0.702399 | 145 | 26.020689 | 25.690592 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.034483 | false | false |
5
|
b680eabc4a0ad9695d95af46b86cf38ccd147604
| 22,789,096,490,365 |
987f985014e3ff385a7dcd7a3ddc67a91490f658
|
/src/main/java/org/aerogear/kryptowire/BinaryInfo.java
|
19579ba52145ba03ed13451c02d892aa357d934c
|
[
"Apache-2.0"
] |
permissive
|
jenkinsci/kryptowire-plugin
|
https://github.com/jenkinsci/kryptowire-plugin
|
adc7b703b320380bbb10323c4186d8aed96040b3
|
42b92e3fa7765b4347db0a8991b0345fa3b524a6
|
refs/heads/master
| 2023-06-29T02:49:50.535000 | 2018-06-29T09:23:35 | 2018-06-29T09:23:35 | 138,909,697 | 1 | 2 |
Apache-2.0
| true | 2019-09-11T21:24:04 | 2018-06-27T16:59:07 | 2019-03-06T01:34:16 | 2019-09-11T21:24:03 | 554 | 1 | 1 | 1 |
Java
| false | false |
package org.aerogear.kryptowire;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
public class BinaryInfo {
private String pkg;
private String uuid;
private String platform;
private String version;
private String hash;
public BinaryInfo(String pkg, String uuid, String platform, String version, String hash) {
this.pkg = pkg;
this.uuid = uuid;
this.platform = platform;
this.version = version;
this.hash = hash;
}
public static BinaryInfo fromJSONObject(JSONObject obj) {
String uuid = obj.getString("uuid");
String platform = obj.getString("platform");
String pkg = obj.getString("package");
String version = obj.getString("version");
String hash = obj.getString("hash");
return new BinaryInfo(pkg, uuid, platform, version, hash);
}
public String getPkg() {
return pkg;
}
public void setPkg(String pkg) {
this.pkg = pkg;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}
|
UTF-8
|
Java
| 1,576 |
java
|
BinaryInfo.java
|
Java
|
[] | null |
[] |
package org.aerogear.kryptowire;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
public class BinaryInfo {
private String pkg;
private String uuid;
private String platform;
private String version;
private String hash;
public BinaryInfo(String pkg, String uuid, String platform, String version, String hash) {
this.pkg = pkg;
this.uuid = uuid;
this.platform = platform;
this.version = version;
this.hash = hash;
}
public static BinaryInfo fromJSONObject(JSONObject obj) {
String uuid = obj.getString("uuid");
String platform = obj.getString("platform");
String pkg = obj.getString("package");
String version = obj.getString("version");
String hash = obj.getString("hash");
return new BinaryInfo(pkg, uuid, platform, version, hash);
}
public String getPkg() {
return pkg;
}
public void setPkg(String pkg) {
this.pkg = pkg;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}
| 1,576 | 0.609137 | 0.609137 | 71 | 21.183098 | 19.394575 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521127 | false | false |
5
|
1f7f8689341f02a244e3a228aab1f081b473dbb0
| 18,966,575,579,750 |
1c2df8be2b423d3cb1786e717533829d640d50d6
|
/Selenium/loadTest/src/main/java/com/sin/scenario/Test002.java
|
c51f6ff5bbf389704cb1b5683e1de1a08d5ddc61
|
[] |
no_license
|
Anmols085/Take4
|
https://github.com/Anmols085/Take4
|
3da7ada474029330ecc143e5b9c7ed8a92055524
|
0c9e9e2bf20b62336fa225ca9ec28a7c1ec79180
|
refs/heads/master
| 2021-04-09T13:14:03.744000 | 2018-06-23T08:29:32 | 2018-06-23T08:29:32 | 125,642,409 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sin.scenario;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.sin.beans.PropertyBean;
import com.sin.edx.EdxLoginFlow;
import com.sin.utility.BasePage;
import com.sin.utility.ReadPropertiesFile;
import com.sin.utility.Screenshots;
public class Test002 {
private EdxLoginFlow loginToEdx = null;
private BasePage baseTest = new BasePage();
private PropertyBean properties = new PropertyBean();
Screenshots screenshot = new Screenshots();
private final static Logger logger = Logger.getLogger(Test002.class);
@BeforeSuite
public void beforeSuite() {
try {
PropertyBean.setProperties(ReadPropertiesFile.setProperties());
} catch (Exception e) {
}
baseTest.generateWebDriver(properties);
}
@AfterSuite
public void afterClass() {
baseTest.quitDriver();
}
@BeforeClass
public void printName() {
System.out.println("Test002 in play");
logger.info("Test002 in play");
}
@Test // Verify Google home page
public void verifySearchButton() {
System.out.println(properties.getProperty("favoriteFood"));
System.out.println("Inside test002, Google section");
baseTest.getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
baseTest.getDriver().get(properties.getProperty("GoogleUrl"));
String search_text = properties.getProperty("ExpectedGoogleHeadingTestCase002");
WebElement search_button = baseTest.getDriver().findElement(By.name("btnK"));
String text = search_button.getAttribute("value");
screenshot.switchToFrame();
Assert.assertNotEquals(text, search_text, "Text not found!");
}
@Test // Verify login error message from EDX
(dependsOnMethods = { "verifySearchButton" })
public void loginEdx(){
System.out.println("Inside test002, Edx section");
loginToEdx = new EdxLoginFlow();
baseTest.getDriver().get(properties.getProperty("EdxUrl"));
loginToEdx.navigateToLoginPage();
}
}
|
UTF-8
|
Java
| 2,166 |
java
|
Test002.java
|
Java
|
[] | null |
[] |
package com.sin.scenario;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import com.sin.beans.PropertyBean;
import com.sin.edx.EdxLoginFlow;
import com.sin.utility.BasePage;
import com.sin.utility.ReadPropertiesFile;
import com.sin.utility.Screenshots;
public class Test002 {
private EdxLoginFlow loginToEdx = null;
private BasePage baseTest = new BasePage();
private PropertyBean properties = new PropertyBean();
Screenshots screenshot = new Screenshots();
private final static Logger logger = Logger.getLogger(Test002.class);
@BeforeSuite
public void beforeSuite() {
try {
PropertyBean.setProperties(ReadPropertiesFile.setProperties());
} catch (Exception e) {
}
baseTest.generateWebDriver(properties);
}
@AfterSuite
public void afterClass() {
baseTest.quitDriver();
}
@BeforeClass
public void printName() {
System.out.println("Test002 in play");
logger.info("Test002 in play");
}
@Test // Verify Google home page
public void verifySearchButton() {
System.out.println(properties.getProperty("favoriteFood"));
System.out.println("Inside test002, Google section");
baseTest.getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
baseTest.getDriver().get(properties.getProperty("GoogleUrl"));
String search_text = properties.getProperty("ExpectedGoogleHeadingTestCase002");
WebElement search_button = baseTest.getDriver().findElement(By.name("btnK"));
String text = search_button.getAttribute("value");
screenshot.switchToFrame();
Assert.assertNotEquals(text, search_text, "Text not found!");
}
@Test // Verify login error message from EDX
(dependsOnMethods = { "verifySearchButton" })
public void loginEdx(){
System.out.println("Inside test002, Edx section");
loginToEdx = new EdxLoginFlow();
baseTest.getDriver().get(properties.getProperty("EdxUrl"));
loginToEdx.navigateToLoginPage();
}
}
| 2,166 | 0.765928 | 0.754848 | 71 | 29.507042 | 22.748394 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.521127 | false | false |
5
|
68f7304b0f5f14ed4e7050e41ca75c641ee772a0
| 28,046,136,498,191 |
d7ce1539d29705cd15fde4913b71535fc58cde7b
|
/java-example-restkv/restkv/src/main/java/cn/ctyun/bigdata/restkv/utility/UIdCardType.java
|
4c38a49b0926caaa563bf4aa8835b57232ac3da4
|
[] |
no_license
|
zhanghw89/examples
|
https://github.com/zhanghw89/examples
|
9d0b790ac7d3a02cb624d7c131d6447eacc5ba98
|
de7b7b4ac0af39f2d71a8414a289e72d0861abdb
|
refs/heads/master
| 2017-05-06T03:07:50.350000 | 2016-11-24T10:46:49 | 2016-11-24T10:46:49 | 41,340,560 | 0 | 0 | null | false | 2017-07-14T00:20:16 | 2015-08-25T03:21:12 | 2016-03-11T18:12:00 | 2017-07-14T00:16:47 | 202,608 | 0 | 0 | 0 |
Java
| null | null |
package cn.ctyun.bigdata.restkv.utility;
public enum UIdCardType {
SHEN_FEN_ZHENG(1, "身份证"), //
JUN_GUAN_ZHENG(2, "军官证"), //
HU_ZHAO(3, "护照"), //
GAT_TONG_XING_ZHENG(4, "港澳台通行证"), //
BU_DUI_GAN_BU_LI_XIU_ZHENG(5, "部队干部离休证"), //
GONG_SHANG_ZHI_ZHAO(6, "工商执照"), //
DAN_WEI_ZHENG_MING(7, "单位证明(含公章)"), //
JIA_SHI_ZHENG(9, "驾驶证"), //
XUE_SHENG_ZHENG(10, "学生证"), //
JIAO_SHI_ZHENG(11, "教师证"), //
HU_KOU_BEI_JIU_ZHU_ZHENG(12, "户口本/居住证"), //
LAO_REN_ZHENG(13, "老人证"), //
SHI_BING_ZHENG(14, "士兵证"), //
ZHU_ZHI_JI_GOU_DAI_MA_ZHENG(15, "组织机构代码证"), //
GONG_ZUO_ZHENG(17, "工作证"), //
ZHAN_ZHU_ZHENG(18, "暂住证"), //
JIN_GUAN_ZHENG(22, "警官证"), //
ICP_JING_YING_XU_KE_ZHENG(23, "ICP经营许可证"), //
HUI_XIANG_ZHENG(24, "回乡证"), //
SHE_BAO_KA(25, "社保卡"), //
CAN_JI_ZHENG(26, "残疾证"), //
SHI_YE_DAN_WEI_BIAN_MA(27, "事业单位编码"), //
REN_CAI_JU_ZHU_ZHENG(28, "市政府人才居住证"), //
CN_ZHU_ZHI_JI_GOU_DAI_MA_ZHENG(29, "中华人民共和国组织机构代码证"), //
FANG_CHAN_ZHENG(30, "房产证"), //
JI_ZHE_ZHENG(31, "记者证"), //
YI_LIAO_ZHENG(32, "医疗证"), //
JIU_LIU_ZHENG(33, "居留证"), //
FA_REN_ZHENG(34, "事业单位法人证书"), //
TW_SHEN_FEN_ZHENG(35, "台湾身份证"), //
MO_SHEN_FEN_ZHENG(36, "澳门身份证"), //
HK_SHEN_FEN_ZHENG(37, "香港身份证"), //
XU_NI_ZHENG_JIAN(38, "虚拟证件"), //
SHUI_WU_DENG_JI_HAO(39, "税务登记号"), //
QI_TA(99, "其他"), //
UNKNOWN(-1, "未知");
private int code;
private String displayName;
private static UIdCardType[] CODE_MAP;
static {
int maxCode = 0;
for (UIdCardType t : UIdCardType.values()) {
if (t.code > maxCode) {
maxCode = t.code;
}
}
maxCode++;
CODE_MAP = new UIdCardType[maxCode];
for (UIdCardType t : UIdCardType.values()) {
CODE_MAP[t.code] = t;
}
}
private UIdCardType(int code, String displayName) {
this.code = code;
this.displayName = displayName;
}
public static UIdCardType valueOfCode(int code) {
if (code < 0 || code >= CODE_MAP.length) {
return null;
}
return CODE_MAP[code];
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
|
UTF-8
|
Java
| 2,486 |
java
|
UIdCardType.java
|
Java
|
[] | null |
[] |
package cn.ctyun.bigdata.restkv.utility;
public enum UIdCardType {
SHEN_FEN_ZHENG(1, "身份证"), //
JUN_GUAN_ZHENG(2, "军官证"), //
HU_ZHAO(3, "护照"), //
GAT_TONG_XING_ZHENG(4, "港澳台通行证"), //
BU_DUI_GAN_BU_LI_XIU_ZHENG(5, "部队干部离休证"), //
GONG_SHANG_ZHI_ZHAO(6, "工商执照"), //
DAN_WEI_ZHENG_MING(7, "单位证明(含公章)"), //
JIA_SHI_ZHENG(9, "驾驶证"), //
XUE_SHENG_ZHENG(10, "学生证"), //
JIAO_SHI_ZHENG(11, "教师证"), //
HU_KOU_BEI_JIU_ZHU_ZHENG(12, "户口本/居住证"), //
LAO_REN_ZHENG(13, "老人证"), //
SHI_BING_ZHENG(14, "士兵证"), //
ZHU_ZHI_JI_GOU_DAI_MA_ZHENG(15, "组织机构代码证"), //
GONG_ZUO_ZHENG(17, "工作证"), //
ZHAN_ZHU_ZHENG(18, "暂住证"), //
JIN_GUAN_ZHENG(22, "警官证"), //
ICP_JING_YING_XU_KE_ZHENG(23, "ICP经营许可证"), //
HUI_XIANG_ZHENG(24, "回乡证"), //
SHE_BAO_KA(25, "社保卡"), //
CAN_JI_ZHENG(26, "残疾证"), //
SHI_YE_DAN_WEI_BIAN_MA(27, "事业单位编码"), //
REN_CAI_JU_ZHU_ZHENG(28, "市政府人才居住证"), //
CN_ZHU_ZHI_JI_GOU_DAI_MA_ZHENG(29, "中华人民共和国组织机构代码证"), //
FANG_CHAN_ZHENG(30, "房产证"), //
JI_ZHE_ZHENG(31, "记者证"), //
YI_LIAO_ZHENG(32, "医疗证"), //
JIU_LIU_ZHENG(33, "居留证"), //
FA_REN_ZHENG(34, "事业单位法人证书"), //
TW_SHEN_FEN_ZHENG(35, "台湾身份证"), //
MO_SHEN_FEN_ZHENG(36, "澳门身份证"), //
HK_SHEN_FEN_ZHENG(37, "香港身份证"), //
XU_NI_ZHENG_JIAN(38, "虚拟证件"), //
SHUI_WU_DENG_JI_HAO(39, "税务登记号"), //
QI_TA(99, "其他"), //
UNKNOWN(-1, "未知");
private int code;
private String displayName;
private static UIdCardType[] CODE_MAP;
static {
int maxCode = 0;
for (UIdCardType t : UIdCardType.values()) {
if (t.code > maxCode) {
maxCode = t.code;
}
}
maxCode++;
CODE_MAP = new UIdCardType[maxCode];
for (UIdCardType t : UIdCardType.values()) {
CODE_MAP[t.code] = t;
}
}
private UIdCardType(int code, String displayName) {
this.code = code;
this.displayName = displayName;
}
public static UIdCardType valueOfCode(int code) {
if (code < 0 || code >= CODE_MAP.length) {
return null;
}
return CODE_MAP[code];
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
| 2,486 | 0.611368 | 0.581331 | 87 | 23.873564 | 15.841023 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.218391 | false | false |
5
|
ac0441c22040b95fc93a610d941887b4c279a983
| 27,006,754,389,546 |
66db98ef824ff04f441b6905f1b73760413a588a
|
/tester/trunk/src/main/java/org/immunizationsoftware/dqa/tester/manager/hl7/segments/ORC.java
|
274bdea63bbec74203664a14916c2893d09a2e33
|
[] |
no_license
|
nathanbunker/ois-dqa
|
https://github.com/nathanbunker/ois-dqa
|
7d90d27444027aa2659130d5910e10f6102b7684
|
f09ccf2c9ae66b7d5f7a4fc6dabf319016606677
|
refs/heads/master
| 2021-01-10T07:00:21.298000 | 2017-10-05T23:42:32 | 2017-10-05T23:42:32 | 54,055,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.immunizationsoftware.dqa.tester.manager.hl7.segments;
import org.immunizationsoftware.dqa.tester.manager.hl7.Cardinality;
import org.immunizationsoftware.dqa.tester.manager.hl7.HL7Component;
import org.immunizationsoftware.dqa.tester.manager.hl7.ItemType;
import org.immunizationsoftware.dqa.tester.manager.hl7.UsageType;
import org.immunizationsoftware.dqa.tester.manager.hl7.ValueSet;
import org.immunizationsoftware.dqa.tester.manager.hl7.conformance.ExactValue;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CNE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CWE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.EI;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.EIP;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.ID;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.PL;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.TQ;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.TS;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XAD;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XCN;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XON;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XTN;
public class ORC extends HL7Component
{
private ID orderControl = null;
private EI placerOrderNumber = null;
private EI fillerOrderNumber = null;
private EI placerGroupNumber = null;
private ID orderStatus = null;
private ID responseFlag = null;
private TQ quantityTiming = null;
private EIP parent = null;
private TS dateTimeOfTransaction = null;
private XCN enteredBy = null;
private XCN verifiedBy = null;
private XCN orderingProvider = null;
private PL enterersLocation = null;
private XTN callBackPhoneNumber = null;
private TS orderEffectiveDateTime = null;
private CE orderControlCodeReason = null;
private CE enteringOrganization = null;
private CE enteringDevice = null;
private XCN actionBy = null;
private CE advancedBeneficiaryNoticeCode = null;
private XON orderingFacilityName = null;
private XAD orderingFacilityAddress = null;
private XTN orderingFacilityPhoneNumber = null;
private XAD orderingProviderAddress = null;
private CWE orderStatusModifier = null;
private CWE advancedBeneficiaryNoticeOverrideReason = null;
private TS fillersExpectedAvailabilityDateTime = null;
private CWE confidentialityCode = null;
private CWE orderType = null;
private CNE entererAuthorizationMode = null;
private CWE parentUniversalServiceIdentifier = null;
public ID getOrderControl() {
return orderControl;
}
public void setOrderControl(ID orderControl) {
this.orderControl = orderControl;
}
public EI getPlacerOrderNumber() {
return placerOrderNumber;
}
public void setPlacerOrderNumber(EI placerOrderNumber) {
this.placerOrderNumber = placerOrderNumber;
}
public EI getFillerOrderNumber() {
return fillerOrderNumber;
}
public void setFillerOrderNumber(EI fillerOrderNumber) {
this.fillerOrderNumber = fillerOrderNumber;
}
public EI getPlacerGroupNumber() {
return placerGroupNumber;
}
public void setPlacerGroupNumber(EI placerGroupNumber) {
this.placerGroupNumber = placerGroupNumber;
}
public ID getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(ID orderStatus) {
this.orderStatus = orderStatus;
}
public ID getResponseFlag() {
return responseFlag;
}
public void setResponseFlag(ID responseFlag) {
this.responseFlag = responseFlag;
}
public TQ getQuantityTiming() {
return quantityTiming;
}
public void setQuantityTiming(TQ quantityTiming) {
this.quantityTiming = quantityTiming;
}
public EIP getParent() {
return parent;
}
public void setParent(EIP parent) {
this.parent = parent;
}
public TS getDateTimeOfTransaction() {
return dateTimeOfTransaction;
}
public void setDateTimeOfTransaction(TS dateTimeOfTransaction) {
this.dateTimeOfTransaction = dateTimeOfTransaction;
}
public XCN getEnteredBy() {
return enteredBy;
}
public void setEnteredBy(XCN enteredBy) {
this.enteredBy = enteredBy;
}
public XCN getVerifiedBy() {
return verifiedBy;
}
public void setVerifiedBy(XCN verifiedBy) {
this.verifiedBy = verifiedBy;
}
public XCN getOrderingProvider() {
return orderingProvider;
}
public void setOrderingProvider(XCN orderingProvider) {
this.orderingProvider = orderingProvider;
}
public PL getEnterersLocation() {
return enterersLocation;
}
public void setEnterersLocation(PL enterersLocation) {
this.enterersLocation = enterersLocation;
}
public XTN getCallBackPhoneNumber() {
return callBackPhoneNumber;
}
public void setCallBackPhoneNumber(XTN callBackPhoneNumber) {
this.callBackPhoneNumber = callBackPhoneNumber;
}
public TS getOrderEffectiveDateTime() {
return orderEffectiveDateTime;
}
public void setOrderEffectiveDateTime(TS orderEffectiveDateTime) {
this.orderEffectiveDateTime = orderEffectiveDateTime;
}
public CE getOrderControlCodeReason() {
return orderControlCodeReason;
}
public void setOrderControlCodeReason(CE orderControlCodeReason) {
this.orderControlCodeReason = orderControlCodeReason;
}
public CE getEnteringOrganization() {
return enteringOrganization;
}
public void setEnteringOrganization(CE enteringOrganization) {
this.enteringOrganization = enteringOrganization;
}
public CE getEnteringDevice() {
return enteringDevice;
}
public void setEnteringDevice(CE enteringDevice) {
this.enteringDevice = enteringDevice;
}
public XCN getActionBy() {
return actionBy;
}
public void setActionBy(XCN actionBy) {
this.actionBy = actionBy;
}
public CE getAdvancedBeneficiaryNoticeCode() {
return advancedBeneficiaryNoticeCode;
}
public void setAdvancedBeneficiaryNoticeCode(CE advancedBeneficiaryNoticeCode) {
this.advancedBeneficiaryNoticeCode = advancedBeneficiaryNoticeCode;
}
public XON getOrderingFacilityName() {
return orderingFacilityName;
}
public void setOrderingFacilityName(XON orderingFacilityName) {
this.orderingFacilityName = orderingFacilityName;
}
public XAD getOrderingFacilityAddress() {
return orderingFacilityAddress;
}
public void setOrderingFacilityAddress(XAD orderingFacilityAddress) {
this.orderingFacilityAddress = orderingFacilityAddress;
}
public XTN getOrderingFacilityPhoneNumber() {
return orderingFacilityPhoneNumber;
}
public void setOrderingFacilityPhoneNumber(XTN orderingFacilityPhoneNumber) {
this.orderingFacilityPhoneNumber = orderingFacilityPhoneNumber;
}
public XAD getOrderingProviderAddress() {
return orderingProviderAddress;
}
public void setOrderingProviderAddress(XAD orderingProviderAddress) {
this.orderingProviderAddress = orderingProviderAddress;
}
public CWE getOrderStatusModifier() {
return orderStatusModifier;
}
public void setOrderStatusModifier(CWE orderStatusModifier) {
this.orderStatusModifier = orderStatusModifier;
}
public CWE getAdvancedBeneficiaryNoticeOverrideReason() {
return advancedBeneficiaryNoticeOverrideReason;
}
public void setAdvancedBeneficiaryNoticeOverrideReason(CWE advancedBeneficiaryNoticeOverrideReason) {
this.advancedBeneficiaryNoticeOverrideReason = advancedBeneficiaryNoticeOverrideReason;
}
public TS getFillersExpectedAvailabilityDateTime() {
return fillersExpectedAvailabilityDateTime;
}
public void setFillersExpectedAvailabilityDateTime(TS fillersExpectedAvailabilityDateTime) {
this.fillersExpectedAvailabilityDateTime = fillersExpectedAvailabilityDateTime;
}
public CWE getConfidentialityCode() {
return confidentialityCode;
}
public void setConfidentialityCode(CWE confidentialityCode) {
this.confidentialityCode = confidentialityCode;
}
public CWE getOrderType() {
return orderType;
}
public void setOrderType(CWE orderType) {
this.orderType = orderType;
}
public CNE getEntererAuthorizationMode() {
return entererAuthorizationMode;
}
public void setEntererAuthorizationMode(CNE entererAuthorizationMode) {
this.entererAuthorizationMode = entererAuthorizationMode;
}
public CWE getParentUniversalServiceIdentifier() {
return parentUniversalServiceIdentifier;
}
public void setParentUniversalServiceIdentifier(CWE parentUniversalServiceIdentifier) {
this.parentUniversalServiceIdentifier = parentUniversalServiceIdentifier;
}
@Override
public HL7Component makeAnother() {
return new ORC(this);
}
public ORC(ORC copy) {
super(copy);
init();
}
public ORC(UsageType usageType, Cardinality cardinality) {
super(ItemType.SEGMENT, "ORC", "Order Request Segment", "Order Request Segment", 31, usageType, cardinality);
init();
}
@Override
public void init() {
setChild(1, orderControl = new ID("Order Control", UsageType.R, Cardinality.ONE_TIME_ONLY, ValueSet.HL70119));
orderControl.addConformanceStatement(new ExactValue("IZ-25: ORC.1 (Order Control) SHALL contain the value \"RE\"", "RE"));
setChild(2, placerOrderNumber = new EI("Placer Order Number", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(3, fillerOrderNumber = new EI("Filler Order Number", UsageType.R, Cardinality.ONE_TIME_ONLY));
setChild(4, placerGroupNumber = new EI("Placer Group NUmber", UsageType.O));
setChild(5, orderStatus = new ID("Order Status", UsageType.O));
setChild(6, responseFlag = new ID("Response Flag", UsageType.O));
setChild(7, quantityTiming = new TQ("Quantity/Timing", UsageType.X));
setChild(8, parent = new EIP("Parent", UsageType.O));
setChild(9, dateTimeOfTransaction = new TS("Date/Time of Transaction", UsageType.O));
setChild(10, enteredBy = new XCN("Entered By", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(11, verifiedBy = new XCN("Verified By", UsageType.O));
setChild(12, orderingProvider = new XCN("Ordering Provider", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(13, enterersLocation = new PL("Enterer's Location", UsageType.O));
setChild(14, callBackPhoneNumber = new XTN("Call Back Phone Number", UsageType.O));
setChild(15, orderEffectiveDateTime = new TS("Order Effective Date/Time", UsageType.O));
setChild(16, orderControlCodeReason = new CE("Order Control Code Reason", UsageType.O));
setChild(17, enteringOrganization = new CE("Entering Organization", UsageType.O));
setChild(18, enteringDevice = new CE("Entering Device", UsageType.O));
setChild(19, actionBy = new XCN("Action By", UsageType.O));
setChild(20, advancedBeneficiaryNoticeCode = new CE("Advanced Beneficiary Notice Code", UsageType.O));
setChild(21, orderingFacilityName = new XON("Ordering Facility Name", UsageType.O));
setChild(22, orderingFacilityAddress = new XAD("Ordering Facility Address", UsageType.O));
setChild(23, orderingFacilityPhoneNumber = new XTN("Ordering Facility Phone Number", UsageType.O));
setChild(24, orderingProviderAddress = new XAD("Ordering Provider Address", UsageType.O));
setChild(25, orderStatusModifier = new CWE("Order Status Modifier", UsageType.O));
setChild(26, advancedBeneficiaryNoticeOverrideReason = new CWE("Advanced Beneficiary Notice Override Reason",
UsageType.O));
setChild(27, fillersExpectedAvailabilityDateTime = new TS("Filler's Expected Availability Date/Time", UsageType.O));
setChild(28, confidentialityCode = new CWE("Confidentiality Code", UsageType.O));
setChild(29, orderType = new CWE("Order Type", UsageType.O));
setChild(30, entererAuthorizationMode = new CNE("Enterer Authorization Mode", UsageType.O));
setChild(31, parentUniversalServiceIdentifier = new CWE("Parent Universal Service Identifier", UsageType.O));
}
}
|
UTF-8
|
Java
| 12,088 |
java
|
ORC.java
|
Java
|
[] | null |
[] |
package org.immunizationsoftware.dqa.tester.manager.hl7.segments;
import org.immunizationsoftware.dqa.tester.manager.hl7.Cardinality;
import org.immunizationsoftware.dqa.tester.manager.hl7.HL7Component;
import org.immunizationsoftware.dqa.tester.manager.hl7.ItemType;
import org.immunizationsoftware.dqa.tester.manager.hl7.UsageType;
import org.immunizationsoftware.dqa.tester.manager.hl7.ValueSet;
import org.immunizationsoftware.dqa.tester.manager.hl7.conformance.ExactValue;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CNE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.CWE;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.EI;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.EIP;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.ID;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.PL;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.TQ;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.TS;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XAD;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XCN;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XON;
import org.immunizationsoftware.dqa.tester.manager.hl7.datatypes.XTN;
public class ORC extends HL7Component
{
private ID orderControl = null;
private EI placerOrderNumber = null;
private EI fillerOrderNumber = null;
private EI placerGroupNumber = null;
private ID orderStatus = null;
private ID responseFlag = null;
private TQ quantityTiming = null;
private EIP parent = null;
private TS dateTimeOfTransaction = null;
private XCN enteredBy = null;
private XCN verifiedBy = null;
private XCN orderingProvider = null;
private PL enterersLocation = null;
private XTN callBackPhoneNumber = null;
private TS orderEffectiveDateTime = null;
private CE orderControlCodeReason = null;
private CE enteringOrganization = null;
private CE enteringDevice = null;
private XCN actionBy = null;
private CE advancedBeneficiaryNoticeCode = null;
private XON orderingFacilityName = null;
private XAD orderingFacilityAddress = null;
private XTN orderingFacilityPhoneNumber = null;
private XAD orderingProviderAddress = null;
private CWE orderStatusModifier = null;
private CWE advancedBeneficiaryNoticeOverrideReason = null;
private TS fillersExpectedAvailabilityDateTime = null;
private CWE confidentialityCode = null;
private CWE orderType = null;
private CNE entererAuthorizationMode = null;
private CWE parentUniversalServiceIdentifier = null;
public ID getOrderControl() {
return orderControl;
}
public void setOrderControl(ID orderControl) {
this.orderControl = orderControl;
}
public EI getPlacerOrderNumber() {
return placerOrderNumber;
}
public void setPlacerOrderNumber(EI placerOrderNumber) {
this.placerOrderNumber = placerOrderNumber;
}
public EI getFillerOrderNumber() {
return fillerOrderNumber;
}
public void setFillerOrderNumber(EI fillerOrderNumber) {
this.fillerOrderNumber = fillerOrderNumber;
}
public EI getPlacerGroupNumber() {
return placerGroupNumber;
}
public void setPlacerGroupNumber(EI placerGroupNumber) {
this.placerGroupNumber = placerGroupNumber;
}
public ID getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(ID orderStatus) {
this.orderStatus = orderStatus;
}
public ID getResponseFlag() {
return responseFlag;
}
public void setResponseFlag(ID responseFlag) {
this.responseFlag = responseFlag;
}
public TQ getQuantityTiming() {
return quantityTiming;
}
public void setQuantityTiming(TQ quantityTiming) {
this.quantityTiming = quantityTiming;
}
public EIP getParent() {
return parent;
}
public void setParent(EIP parent) {
this.parent = parent;
}
public TS getDateTimeOfTransaction() {
return dateTimeOfTransaction;
}
public void setDateTimeOfTransaction(TS dateTimeOfTransaction) {
this.dateTimeOfTransaction = dateTimeOfTransaction;
}
public XCN getEnteredBy() {
return enteredBy;
}
public void setEnteredBy(XCN enteredBy) {
this.enteredBy = enteredBy;
}
public XCN getVerifiedBy() {
return verifiedBy;
}
public void setVerifiedBy(XCN verifiedBy) {
this.verifiedBy = verifiedBy;
}
public XCN getOrderingProvider() {
return orderingProvider;
}
public void setOrderingProvider(XCN orderingProvider) {
this.orderingProvider = orderingProvider;
}
public PL getEnterersLocation() {
return enterersLocation;
}
public void setEnterersLocation(PL enterersLocation) {
this.enterersLocation = enterersLocation;
}
public XTN getCallBackPhoneNumber() {
return callBackPhoneNumber;
}
public void setCallBackPhoneNumber(XTN callBackPhoneNumber) {
this.callBackPhoneNumber = callBackPhoneNumber;
}
public TS getOrderEffectiveDateTime() {
return orderEffectiveDateTime;
}
public void setOrderEffectiveDateTime(TS orderEffectiveDateTime) {
this.orderEffectiveDateTime = orderEffectiveDateTime;
}
public CE getOrderControlCodeReason() {
return orderControlCodeReason;
}
public void setOrderControlCodeReason(CE orderControlCodeReason) {
this.orderControlCodeReason = orderControlCodeReason;
}
public CE getEnteringOrganization() {
return enteringOrganization;
}
public void setEnteringOrganization(CE enteringOrganization) {
this.enteringOrganization = enteringOrganization;
}
public CE getEnteringDevice() {
return enteringDevice;
}
public void setEnteringDevice(CE enteringDevice) {
this.enteringDevice = enteringDevice;
}
public XCN getActionBy() {
return actionBy;
}
public void setActionBy(XCN actionBy) {
this.actionBy = actionBy;
}
public CE getAdvancedBeneficiaryNoticeCode() {
return advancedBeneficiaryNoticeCode;
}
public void setAdvancedBeneficiaryNoticeCode(CE advancedBeneficiaryNoticeCode) {
this.advancedBeneficiaryNoticeCode = advancedBeneficiaryNoticeCode;
}
public XON getOrderingFacilityName() {
return orderingFacilityName;
}
public void setOrderingFacilityName(XON orderingFacilityName) {
this.orderingFacilityName = orderingFacilityName;
}
public XAD getOrderingFacilityAddress() {
return orderingFacilityAddress;
}
public void setOrderingFacilityAddress(XAD orderingFacilityAddress) {
this.orderingFacilityAddress = orderingFacilityAddress;
}
public XTN getOrderingFacilityPhoneNumber() {
return orderingFacilityPhoneNumber;
}
public void setOrderingFacilityPhoneNumber(XTN orderingFacilityPhoneNumber) {
this.orderingFacilityPhoneNumber = orderingFacilityPhoneNumber;
}
public XAD getOrderingProviderAddress() {
return orderingProviderAddress;
}
public void setOrderingProviderAddress(XAD orderingProviderAddress) {
this.orderingProviderAddress = orderingProviderAddress;
}
public CWE getOrderStatusModifier() {
return orderStatusModifier;
}
public void setOrderStatusModifier(CWE orderStatusModifier) {
this.orderStatusModifier = orderStatusModifier;
}
public CWE getAdvancedBeneficiaryNoticeOverrideReason() {
return advancedBeneficiaryNoticeOverrideReason;
}
public void setAdvancedBeneficiaryNoticeOverrideReason(CWE advancedBeneficiaryNoticeOverrideReason) {
this.advancedBeneficiaryNoticeOverrideReason = advancedBeneficiaryNoticeOverrideReason;
}
public TS getFillersExpectedAvailabilityDateTime() {
return fillersExpectedAvailabilityDateTime;
}
public void setFillersExpectedAvailabilityDateTime(TS fillersExpectedAvailabilityDateTime) {
this.fillersExpectedAvailabilityDateTime = fillersExpectedAvailabilityDateTime;
}
public CWE getConfidentialityCode() {
return confidentialityCode;
}
public void setConfidentialityCode(CWE confidentialityCode) {
this.confidentialityCode = confidentialityCode;
}
public CWE getOrderType() {
return orderType;
}
public void setOrderType(CWE orderType) {
this.orderType = orderType;
}
public CNE getEntererAuthorizationMode() {
return entererAuthorizationMode;
}
public void setEntererAuthorizationMode(CNE entererAuthorizationMode) {
this.entererAuthorizationMode = entererAuthorizationMode;
}
public CWE getParentUniversalServiceIdentifier() {
return parentUniversalServiceIdentifier;
}
public void setParentUniversalServiceIdentifier(CWE parentUniversalServiceIdentifier) {
this.parentUniversalServiceIdentifier = parentUniversalServiceIdentifier;
}
@Override
public HL7Component makeAnother() {
return new ORC(this);
}
public ORC(ORC copy) {
super(copy);
init();
}
public ORC(UsageType usageType, Cardinality cardinality) {
super(ItemType.SEGMENT, "ORC", "Order Request Segment", "Order Request Segment", 31, usageType, cardinality);
init();
}
@Override
public void init() {
setChild(1, orderControl = new ID("Order Control", UsageType.R, Cardinality.ONE_TIME_ONLY, ValueSet.HL70119));
orderControl.addConformanceStatement(new ExactValue("IZ-25: ORC.1 (Order Control) SHALL contain the value \"RE\"", "RE"));
setChild(2, placerOrderNumber = new EI("Placer Order Number", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(3, fillerOrderNumber = new EI("Filler Order Number", UsageType.R, Cardinality.ONE_TIME_ONLY));
setChild(4, placerGroupNumber = new EI("Placer Group NUmber", UsageType.O));
setChild(5, orderStatus = new ID("Order Status", UsageType.O));
setChild(6, responseFlag = new ID("Response Flag", UsageType.O));
setChild(7, quantityTiming = new TQ("Quantity/Timing", UsageType.X));
setChild(8, parent = new EIP("Parent", UsageType.O));
setChild(9, dateTimeOfTransaction = new TS("Date/Time of Transaction", UsageType.O));
setChild(10, enteredBy = new XCN("Entered By", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(11, verifiedBy = new XCN("Verified By", UsageType.O));
setChild(12, orderingProvider = new XCN("Ordering Provider", UsageType.RE, Cardinality.ZERO_OR_ONE));
setChild(13, enterersLocation = new PL("Enterer's Location", UsageType.O));
setChild(14, callBackPhoneNumber = new XTN("Call Back Phone Number", UsageType.O));
setChild(15, orderEffectiveDateTime = new TS("Order Effective Date/Time", UsageType.O));
setChild(16, orderControlCodeReason = new CE("Order Control Code Reason", UsageType.O));
setChild(17, enteringOrganization = new CE("Entering Organization", UsageType.O));
setChild(18, enteringDevice = new CE("Entering Device", UsageType.O));
setChild(19, actionBy = new XCN("Action By", UsageType.O));
setChild(20, advancedBeneficiaryNoticeCode = new CE("Advanced Beneficiary Notice Code", UsageType.O));
setChild(21, orderingFacilityName = new XON("Ordering Facility Name", UsageType.O));
setChild(22, orderingFacilityAddress = new XAD("Ordering Facility Address", UsageType.O));
setChild(23, orderingFacilityPhoneNumber = new XTN("Ordering Facility Phone Number", UsageType.O));
setChild(24, orderingProviderAddress = new XAD("Ordering Provider Address", UsageType.O));
setChild(25, orderStatusModifier = new CWE("Order Status Modifier", UsageType.O));
setChild(26, advancedBeneficiaryNoticeOverrideReason = new CWE("Advanced Beneficiary Notice Override Reason",
UsageType.O));
setChild(27, fillersExpectedAvailabilityDateTime = new TS("Filler's Expected Availability Date/Time", UsageType.O));
setChild(28, confidentialityCode = new CWE("Confidentiality Code", UsageType.O));
setChild(29, orderType = new CWE("Order Type", UsageType.O));
setChild(30, entererAuthorizationMode = new CNE("Enterer Authorization Mode", UsageType.O));
setChild(31, parentUniversalServiceIdentifier = new CWE("Parent Universal Service Identifier", UsageType.O));
}
}
| 12,088 | 0.766214 | 0.7591 | 358 | 32.765362 | 31.08909 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631285 | false | false |
5
|
4d944992f36b468b6e7e99a3b2de4f719578c8ea
| 29,437,705,891,158 |
446ffc23d22e0c3bc3d8bdd9ae981bb1fd1b6f04
|
/src/main/java/egerton/hospital/model/admit/Admission.java
|
e17eb6a49721a0bfe839662aef256c0c23bd5f20
|
[] |
no_license
|
sir-kolly/san
|
https://github.com/sir-kolly/san
|
beded363f1405901e11531155009f8831383b1dd
|
2834cddcd32d6bf555a947dc26e560721b17acbc
|
refs/heads/master
| 2020-03-24T04:17:12.707000 | 2018-09-13T14:46:42 | 2018-09-13T14:46:42 | 142,419,078 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package egerton.hospital.model.admit;
import egerton.hospital.model.employe.Employee;
import egerton.hospital.model.illness.Disease;
import egerton.hospital.model.patient.Patient;
import egerton.hospital.model.room.Bed;
import egerton.hospital.model.room.Room;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
@Entity
@Table
@NamedQueries({
@NamedQuery(name = "patientPreviousAdmissionDetails",query = "from Admission adm join fetch adm.patient p where adm.date!=:date and p.patientNumber=:number"),
@NamedQuery(name = "patientAdmissionInfo",query = "from Admission adm join fetch adm.patient p where adm.date=:date and p.patientNumber=:number"),
@NamedQuery(name = "checkIfAdmittedAlready",query = "from Admission adm join fetch adm.patient p where p.patientNumber=:number and date=:date")})
public class Admission {
private String admissionNumber,section,reason;
private Date date,time;
private Room room;
private Bed bed;
private Patient patient;
private Employee doc;
private Set<Disease>illnesses;
public Admission() {
}
public Admission(String admissionNumber, String section, String reason,Date date,Date time, Room room, Bed bed, Patient patient, Employee doc) {
this.admissionNumber = admissionNumber;
this.section = section;
this.reason=reason;
this.date = date;
this.time=time;
this.room = room;
this.bed = bed;
this.patient = patient;
this.doc = doc;
}
@Id
@Column(name = "admission_number",length = 15,nullable = false)
public String getAdmissionNumber() {
return admissionNumber;
}
@Column(name = "section",length = 50,nullable = false)
public String getSection() {
return section;
}
@Column(name = "reason",length = 300,nullable = false)
public String getReason() {
return reason;
}
@Temporal(TemporalType.DATE)
@Column(name = "date",nullable = false)
public Date getDate() {
return date;
}
@Temporal(TemporalType.TIME)
@Column(name = "time",nullable = false)
public Date getTime() {
return time;
}
@ManyToOne
@JoinColumn(name = "room",nullable = false,foreignKey = @ForeignKey(name = "RM_AD_FK"))
public Room getRoom() {
return room;
}
@ManyToOne
@JoinColumn(name = "bed",nullable = false,foreignKey = @ForeignKey(name = "BD_AD_FK"))
public Bed getBed() {
return bed;
}
@ManyToOne
@JoinColumn(name = "patient_number",nullable = false,foreignKey = @ForeignKey(name = "P_AD_FK"))
public Patient getPatient() {
return patient;
}
@ManyToOne
@JoinColumn(name = "doc_number",nullable = false,foreignKey = @ForeignKey(name = "DOC_AD_FK"))
public Employee getDoc() {
return doc;
}
@OneToMany(mappedBy = "admission",cascade = CascadeType.ALL)
public Set<Disease> getIllnesses() {
return illnesses;
}
public void setIllnesses(Set<Disease> illnesses) {
this.illnesses = illnesses;
}
public void setDoc(Employee doc) {
this.doc = doc;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public void setAdmissionNumber(String admissionNumber) {
this.admissionNumber = admissionNumber;
}
public void setTime(Date time) {
this.time = time;
}
public void setSection(String section) {
this.section = section;
}
public void setDate(Date date) {
this.date = date;
}
public void setRoom(Room room) {
this.room = room;
}
public void setBed(Bed bed) {
this.bed = bed;
}
public void setReason(String reason) {
this.reason = reason;
}
}
|
UTF-8
|
Java
| 3,816 |
java
|
Admission.java
|
Java
|
[] | null |
[] |
package egerton.hospital.model.admit;
import egerton.hospital.model.employe.Employee;
import egerton.hospital.model.illness.Disease;
import egerton.hospital.model.patient.Patient;
import egerton.hospital.model.room.Bed;
import egerton.hospital.model.room.Room;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
@Entity
@Table
@NamedQueries({
@NamedQuery(name = "patientPreviousAdmissionDetails",query = "from Admission adm join fetch adm.patient p where adm.date!=:date and p.patientNumber=:number"),
@NamedQuery(name = "patientAdmissionInfo",query = "from Admission adm join fetch adm.patient p where adm.date=:date and p.patientNumber=:number"),
@NamedQuery(name = "checkIfAdmittedAlready",query = "from Admission adm join fetch adm.patient p where p.patientNumber=:number and date=:date")})
public class Admission {
private String admissionNumber,section,reason;
private Date date,time;
private Room room;
private Bed bed;
private Patient patient;
private Employee doc;
private Set<Disease>illnesses;
public Admission() {
}
public Admission(String admissionNumber, String section, String reason,Date date,Date time, Room room, Bed bed, Patient patient, Employee doc) {
this.admissionNumber = admissionNumber;
this.section = section;
this.reason=reason;
this.date = date;
this.time=time;
this.room = room;
this.bed = bed;
this.patient = patient;
this.doc = doc;
}
@Id
@Column(name = "admission_number",length = 15,nullable = false)
public String getAdmissionNumber() {
return admissionNumber;
}
@Column(name = "section",length = 50,nullable = false)
public String getSection() {
return section;
}
@Column(name = "reason",length = 300,nullable = false)
public String getReason() {
return reason;
}
@Temporal(TemporalType.DATE)
@Column(name = "date",nullable = false)
public Date getDate() {
return date;
}
@Temporal(TemporalType.TIME)
@Column(name = "time",nullable = false)
public Date getTime() {
return time;
}
@ManyToOne
@JoinColumn(name = "room",nullable = false,foreignKey = @ForeignKey(name = "RM_AD_FK"))
public Room getRoom() {
return room;
}
@ManyToOne
@JoinColumn(name = "bed",nullable = false,foreignKey = @ForeignKey(name = "BD_AD_FK"))
public Bed getBed() {
return bed;
}
@ManyToOne
@JoinColumn(name = "patient_number",nullable = false,foreignKey = @ForeignKey(name = "P_AD_FK"))
public Patient getPatient() {
return patient;
}
@ManyToOne
@JoinColumn(name = "doc_number",nullable = false,foreignKey = @ForeignKey(name = "DOC_AD_FK"))
public Employee getDoc() {
return doc;
}
@OneToMany(mappedBy = "admission",cascade = CascadeType.ALL)
public Set<Disease> getIllnesses() {
return illnesses;
}
public void setIllnesses(Set<Disease> illnesses) {
this.illnesses = illnesses;
}
public void setDoc(Employee doc) {
this.doc = doc;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public void setAdmissionNumber(String admissionNumber) {
this.admissionNumber = admissionNumber;
}
public void setTime(Date time) {
this.time = time;
}
public void setSection(String section) {
this.section = section;
}
public void setDate(Date date) {
this.date = date;
}
public void setRoom(Room room) {
this.room = room;
}
public void setBed(Bed bed) {
this.bed = bed;
}
public void setReason(String reason) {
this.reason = reason;
}
}
| 3,816 | 0.647799 | 0.645964 | 131 | 28.12977 | 30.592718 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.59542 | false | false |
5
|
ffee355456277bc1747b8f835c8a5dcfca388a5a
| 10,264,971,875,829 |
d633bd37a2f7624757b95857ce8c83bb04fc1778
|
/demos/src/main/java/com/java/utils/test/testXml.java
|
9a045d047c436e12e291f9064e8423f5ddbd74b2
|
[
"Apache-2.0"
] |
permissive
|
outskywind/myproject
|
https://github.com/outskywind/myproject
|
03128b8a8359179b037df51bfab4bb180e629308
|
c17dc74c0781b9ab08c32fa10d305bed9b521fb4
|
refs/heads/master
| 2020-06-14T01:47:06.719000 | 2020-03-11T11:06:58 | 2020-03-11T11:06:58 | 75,526,534 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.java.utils.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class testXml {
@Test
public void main() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream in = new FileInputStream("D:/ws/PA18Shopauto1.42.0/src/config/config-dmz/web/web-context-payment.xml");
InputSource is = new InputSource(in);
Document doc=builder.parse(is);
Element root=doc.getDocumentElement();
List<Element> nodes=testXml.getElement(root, "bean");
for(int i=0;i<nodes.size(); i++) {
Element bean=nodes.get(i);
String beanid = bean.getAttribute("name");
if(beanid==null) {
beanid = bean.getAttribute("id");
}
System.out.println(beanid);
List<Element> properties =testXml.getElement(bean, "property");
for(int j=0;j<properties.size();j++) {
Element property = properties.get(j);
List<Element> refs = testXml.getElement(property, "ref");
if(refs.size()==0) {
continue;
}
String attr = refs.get(0).getAttribute("bean");
System.out.println("++"+attr);
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List<Element> getElement(Element root,String elementName) {
List<Element> elements = new ArrayList<Element>();
NodeList nodes = root.getChildNodes();
for(int i=0;i<nodes.getLength();i++) {
Node node = nodes.item(i);
if(node instanceof Element) {
Element e = (Element)node;
if(e.getNodeName().equals(elementName)) {
elements.add(e);
}
}
}
return elements;
}
@Test
public void testLoaderLog4j() {
try {
URL[] urls= {
new File("D:/ws/PA18Shopauto1.42.0/dist/weblogic/pa18shopauto/APP-INF/lib/log4j-1.2.15.jar").toURI().toURL(),
new File("D:/ws/PA18Shopauto1.42.0/dist/weblogic/pa18shopauto/APP-INF/lib/commons-logging.jar").toURI().toURL()};
//and if set the classloader in contextclassloader,
//if the class was loaded by
//如果是junit 测试 ,会自动将 lib下的commons-logging.jar 添加到默认的 classpath下。
//启动 junit 测试时,这些类将会被 System AppClassLoader 加载 。 fuck。
MyClassLoader loader = new MyClassLoader(urls);
//first delegate to parent classloader to load this class ,if loaded ,then return ;
//if all parent classloader loaded failed ,finally invoke the
//user-defined calssloader's method findClass(String clazz) to find and load it .
//
Class clazz=loader.loadClass("org.apache.commons.logging.impl.LogFactoryImpl");
Thread.currentThread().setContextClassLoader(loader);
System.out.println(clazz.getClassLoader()+";;classpath="+clazz.getClassLoader().getResource(""));
Class[] parameterTypes = new Class[1];
parameterTypes[0] = String[].class;
//the getMethod only returns the public method
//Method m= clazz.getMethod("newInstance", parameterTypes);
Method m = clazz.getDeclaredMethod("newInstance", String.class);
m.setAccessible(true);
m.invoke(clazz.newInstance(),clazz.getCanonicalName());
}
catch(Exception e) {
e.printStackTrace();
//if not setted ,it will be null
//System.out.println(e.getMessage());
}
}
//user-defined classloader must override the loadClass to change the load rules.
public class MyClassLoader extends URLClassLoader{
public MyClassLoader(URL[] urls) {
super(urls);
}
public void addURL(URL[] urls) {
for(int i=0;i<urls.length;i++) {
addURL(urls[i]);
}
}
public void addURL(URL url) {
super.addURL(url);
}
public URL[] getURL() {
return super.getURLs();
}
// ordinary the method need not to be overrided,
// it just will be called by yourself classloader
/**
@Override
public Class<?> findClass(String clazz) throws ClassNotFoundException{
Class<?> aClass = findLoadedClass(clazz);
System.out.println("the clazz name="+clazz);
if(aClass!=null) {
System.out.println(clazz+"is already loaded by " + aClass.getClassLoader());
return aClass;
}
if(!clazz.startsWith("org.apache")) {
System.out.println(clazz+"is loaded by parent loader ");
return super.loadClass(clazz);
}
//find and load the class
InputStream is = this.getResourceAsStream(clazz);
if(is==null) {
System.out.println("is = null");
throw new ClassNotFoundException(clazz);
}
try {
byte[] b = new byte[is.available()];
is.read(b);
defineClass(clazz, b, 0, b.length);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} **/
}
}
|
UTF-8
|
Java
| 5,881 |
java
|
testXml.java
|
Java
|
[] | null |
[] |
package com.java.utils.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class testXml {
@Test
public void main() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream in = new FileInputStream("D:/ws/PA18Shopauto1.42.0/src/config/config-dmz/web/web-context-payment.xml");
InputSource is = new InputSource(in);
Document doc=builder.parse(is);
Element root=doc.getDocumentElement();
List<Element> nodes=testXml.getElement(root, "bean");
for(int i=0;i<nodes.size(); i++) {
Element bean=nodes.get(i);
String beanid = bean.getAttribute("name");
if(beanid==null) {
beanid = bean.getAttribute("id");
}
System.out.println(beanid);
List<Element> properties =testXml.getElement(bean, "property");
for(int j=0;j<properties.size();j++) {
Element property = properties.get(j);
List<Element> refs = testXml.getElement(property, "ref");
if(refs.size()==0) {
continue;
}
String attr = refs.get(0).getAttribute("bean");
System.out.println("++"+attr);
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List<Element> getElement(Element root,String elementName) {
List<Element> elements = new ArrayList<Element>();
NodeList nodes = root.getChildNodes();
for(int i=0;i<nodes.getLength();i++) {
Node node = nodes.item(i);
if(node instanceof Element) {
Element e = (Element)node;
if(e.getNodeName().equals(elementName)) {
elements.add(e);
}
}
}
return elements;
}
@Test
public void testLoaderLog4j() {
try {
URL[] urls= {
new File("D:/ws/PA18Shopauto1.42.0/dist/weblogic/pa18shopauto/APP-INF/lib/log4j-1.2.15.jar").toURI().toURL(),
new File("D:/ws/PA18Shopauto1.42.0/dist/weblogic/pa18shopauto/APP-INF/lib/commons-logging.jar").toURI().toURL()};
//and if set the classloader in contextclassloader,
//if the class was loaded by
//如果是junit 测试 ,会自动将 lib下的commons-logging.jar 添加到默认的 classpath下。
//启动 junit 测试时,这些类将会被 System AppClassLoader 加载 。 fuck。
MyClassLoader loader = new MyClassLoader(urls);
//first delegate to parent classloader to load this class ,if loaded ,then return ;
//if all parent classloader loaded failed ,finally invoke the
//user-defined calssloader's method findClass(String clazz) to find and load it .
//
Class clazz=loader.loadClass("org.apache.commons.logging.impl.LogFactoryImpl");
Thread.currentThread().setContextClassLoader(loader);
System.out.println(clazz.getClassLoader()+";;classpath="+clazz.getClassLoader().getResource(""));
Class[] parameterTypes = new Class[1];
parameterTypes[0] = String[].class;
//the getMethod only returns the public method
//Method m= clazz.getMethod("newInstance", parameterTypes);
Method m = clazz.getDeclaredMethod("newInstance", String.class);
m.setAccessible(true);
m.invoke(clazz.newInstance(),clazz.getCanonicalName());
}
catch(Exception e) {
e.printStackTrace();
//if not setted ,it will be null
//System.out.println(e.getMessage());
}
}
//user-defined classloader must override the loadClass to change the load rules.
public class MyClassLoader extends URLClassLoader{
public MyClassLoader(URL[] urls) {
super(urls);
}
public void addURL(URL[] urls) {
for(int i=0;i<urls.length;i++) {
addURL(urls[i]);
}
}
public void addURL(URL url) {
super.addURL(url);
}
public URL[] getURL() {
return super.getURLs();
}
// ordinary the method need not to be overrided,
// it just will be called by yourself classloader
/**
@Override
public Class<?> findClass(String clazz) throws ClassNotFoundException{
Class<?> aClass = findLoadedClass(clazz);
System.out.println("the clazz name="+clazz);
if(aClass!=null) {
System.out.println(clazz+"is already loaded by " + aClass.getClassLoader());
return aClass;
}
if(!clazz.startsWith("org.apache")) {
System.out.println(clazz+"is loaded by parent loader ");
return super.loadClass(clazz);
}
//find and load the class
InputStream is = this.getResourceAsStream(clazz);
if(is==null) {
System.out.println("is = null");
throw new ClassNotFoundException(clazz);
}
try {
byte[] b = new byte[is.available()];
is.read(b);
defineClass(clazz, b, 0, b.length);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} **/
}
}
| 5,881 | 0.653297 | 0.646239 | 197 | 27.48731 | 24.558147 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.197969 | false | false |
5
|
1f8adbfcd85311ba66e82162567b4509bcdd2dd3
| 146,028,921,696 |
863cf0bbd25a11556b458934c404d917d536c77e
|
/game-data/src/main/java/com/cool/wendao/admin/dao/BaseUserDao.java
|
3dfbb8c59b0a7bbca7a198594a609c293a5000a7
|
[] |
no_license
|
xsxz01/wendaoshouyou
|
https://github.com/xsxz01/wendaoshouyou
|
2eeaa7f820fa54c9c15d6b1e5a7d3fada688e678
|
abdadf8885e9b553ab5fdf005efc195e07eab7d8
|
refs/heads/master
| 2021-05-19T05:48:52.097000 | 2020-01-17T07:16:31 | 2020-01-17T07:16:31 | 251,553,820 | 1 | 2 | null | true | 2020-03-31T09:13:17 | 2020-03-31T09:13:16 | 2020-01-17T07:16:54 | 2020-01-17T07:16:52 | 59,225 | 0 | 0 | 0 | null | false | false |
package com.cool.wendao.admin.dao;
import com.cool.wendao.admin.core.MgtPageBean;
import com.cool.wendao.admin.params.SysJob;
import com.cool.wendao.admin.params.SysUser;
import com.cool.wendao.admin.params.SysUser2Job;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BaseUserDao {
/**
* 系统用户登录
*
* @param loginName
* @return SysUser
*/
SysUser doLogin(@Param("loginName") String loginName, @Param("pt") Integer pt);
/**
* 根据机构id获取系统用户总数
*
* @param pageBean
* @return
*/
int getSysUsersCount(MgtPageBean<SysUser> pageBean);
/**
* 分页查询系统用户
*
* @param pageBean
* @return
*/
List<SysUser> getSysUsersByPage(MgtPageBean<SysUser> pageBean);
/**
* 根据userId查询系统用户信息
*
* @param userId
* @return
*/
SysUser getSysUserById(String userId);
/**
* 批量添加系统用户对应岗位
*
* @param sysUser2JobList
*/
void addSysUser2Jobs(List<SysUser2Job> sysUser2JobList);
/**
* 新增系统用户
*
* @param sysUser
*/
void addSysUser(SysUser sysUser);
/**
* 修改系统用户
*
* @param sysUser
*/
void updateSysUser(SysUser sysUser);
/**
* 检查登录名是否存在
*
* @param loginName
* @return
*/
int checkLoginName(@Param("loginName") String loginName, @Param("pt") Integer pt);
/**
* 根据id删除系统用户
*
* @param userId
*/
void delSysUserById(String userId);
/**
* 修改系统用户启用状态
*
* @param params
*/
void updateSysUserEnabled(Map<String, Object> params);
/**
* 根据系统用户id查询对应的岗位id集合
*
* @param userId
* @return
*/
List<String> getJobIdsByUserId(String userId);
/**
* 根据系统用户id查询对应的岗位集合
*
* @param userId
* @return
*/
List<SysJob> getJobByUserId(String userId);
/**
* 根据岗位id查询对应的用户集合
*
* @param jobId
* @return
*/
List<String> getUserIdsByJobId(String jobId);
/**
* 根据系统用户id删除系统用户对应岗位信息
*
* @param userId
*/
void delSysUser2JobsByUserId(String userId);
/**
* 修改系统用户密码
*
* @param sysUser
*/
void updatePwd(SysUser sysUser);
/**
* 修改系统用户密码
*
* @param sysUser
*/
int updateUserPwd(SysUser sysUser);
/**
* 查询所有商户账号
*
* @return
*/
List<SysUser> findAllSellerUser();
/**
* 新增修改个人信息的接口
*/
int updateSysUserNew(SysUser sysUser);
}
|
UTF-8
|
Java
| 2,921 |
java
|
BaseUserDao.java
|
Java
|
[] | null |
[] |
package com.cool.wendao.admin.dao;
import com.cool.wendao.admin.core.MgtPageBean;
import com.cool.wendao.admin.params.SysJob;
import com.cool.wendao.admin.params.SysUser;
import com.cool.wendao.admin.params.SysUser2Job;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface BaseUserDao {
/**
* 系统用户登录
*
* @param loginName
* @return SysUser
*/
SysUser doLogin(@Param("loginName") String loginName, @Param("pt") Integer pt);
/**
* 根据机构id获取系统用户总数
*
* @param pageBean
* @return
*/
int getSysUsersCount(MgtPageBean<SysUser> pageBean);
/**
* 分页查询系统用户
*
* @param pageBean
* @return
*/
List<SysUser> getSysUsersByPage(MgtPageBean<SysUser> pageBean);
/**
* 根据userId查询系统用户信息
*
* @param userId
* @return
*/
SysUser getSysUserById(String userId);
/**
* 批量添加系统用户对应岗位
*
* @param sysUser2JobList
*/
void addSysUser2Jobs(List<SysUser2Job> sysUser2JobList);
/**
* 新增系统用户
*
* @param sysUser
*/
void addSysUser(SysUser sysUser);
/**
* 修改系统用户
*
* @param sysUser
*/
void updateSysUser(SysUser sysUser);
/**
* 检查登录名是否存在
*
* @param loginName
* @return
*/
int checkLoginName(@Param("loginName") String loginName, @Param("pt") Integer pt);
/**
* 根据id删除系统用户
*
* @param userId
*/
void delSysUserById(String userId);
/**
* 修改系统用户启用状态
*
* @param params
*/
void updateSysUserEnabled(Map<String, Object> params);
/**
* 根据系统用户id查询对应的岗位id集合
*
* @param userId
* @return
*/
List<String> getJobIdsByUserId(String userId);
/**
* 根据系统用户id查询对应的岗位集合
*
* @param userId
* @return
*/
List<SysJob> getJobByUserId(String userId);
/**
* 根据岗位id查询对应的用户集合
*
* @param jobId
* @return
*/
List<String> getUserIdsByJobId(String jobId);
/**
* 根据系统用户id删除系统用户对应岗位信息
*
* @param userId
*/
void delSysUser2JobsByUserId(String userId);
/**
* 修改系统用户密码
*
* @param sysUser
*/
void updatePwd(SysUser sysUser);
/**
* 修改系统用户密码
*
* @param sysUser
*/
int updateUserPwd(SysUser sysUser);
/**
* 查询所有商户账号
*
* @return
*/
List<SysUser> findAllSellerUser();
/**
* 新增修改个人信息的接口
*/
int updateSysUserNew(SysUser sysUser);
}
| 2,921 | 0.566341 | 0.563992 | 147 | 16.380953 | 16.971098 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.197279 | false | false |
5
|
0873fe7a8bd4e8b6668e000cc3a838b9521a1efa
| 146,028,921,243 |
52b482a57b75df52238bb1c30df4b534f4ba321a
|
/src/main/java/dev/gurung/services/InventoryService.java
|
7b29e872cc48994764ea037f44ea64895fbb3c79
|
[] |
no_license
|
210823-java-msa-wvu/yungdrung_gurung_p0
|
https://github.com/210823-java-msa-wvu/yungdrung_gurung_p0
|
e17d2642b7f1aa4dafd38709e13756299c4e65c5
|
ae86dc8af1b09881908c46b914762c1ce1b4cd30
|
refs/heads/main
| 2023-08-19T00:23:14.902000 | 2021-09-15T04:28:16 | 2021-09-15T04:28:16 | 403,138,939 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dev.gurung.services;
import dev.gurung.models.Inventory;
import dev.gurung.models.User;
import dev.gurung.repositories.InventoryRepo;
import java.util.List;
public class InventoryService {
private static InventoryRepo inventoryRepo = new InventoryRepo();
public List<Inventory> getAllInventories(){
return inventoryRepo.getAll();
}
public Boolean addProduct( String productName, int quantity, Double price, User user){
Inventory i = inventoryRepo.add( new Inventory(productName, quantity, price, user));
if(i != null){
return true;
}
return false;
}
public boolean updateProduct(Integer id, int quantity, Double price){
Inventory inventory = inventoryRepo.getById(id);
if(inventory.getId() == id){
inventory.setId(id);
inventory.setQuantity(quantity);
inventory.setPrice(price);
inventoryRepo.update(inventory);
return true;
}
return false;
}
public boolean deleteProduct(Integer id){
Inventory inventory = inventoryRepo.getById(id);
if(inventory.getId() == id){
inventoryRepo.delete(id);
return true;
}
return false;
}
}
|
UTF-8
|
Java
| 1,283 |
java
|
InventoryService.java
|
Java
|
[] | null |
[] |
package dev.gurung.services;
import dev.gurung.models.Inventory;
import dev.gurung.models.User;
import dev.gurung.repositories.InventoryRepo;
import java.util.List;
public class InventoryService {
private static InventoryRepo inventoryRepo = new InventoryRepo();
public List<Inventory> getAllInventories(){
return inventoryRepo.getAll();
}
public Boolean addProduct( String productName, int quantity, Double price, User user){
Inventory i = inventoryRepo.add( new Inventory(productName, quantity, price, user));
if(i != null){
return true;
}
return false;
}
public boolean updateProduct(Integer id, int quantity, Double price){
Inventory inventory = inventoryRepo.getById(id);
if(inventory.getId() == id){
inventory.setId(id);
inventory.setQuantity(quantity);
inventory.setPrice(price);
inventoryRepo.update(inventory);
return true;
}
return false;
}
public boolean deleteProduct(Integer id){
Inventory inventory = inventoryRepo.getById(id);
if(inventory.getId() == id){
inventoryRepo.delete(id);
return true;
}
return false;
}
}
| 1,283 | 0.630553 | 0.630553 | 53 | 23.207546 | 24.052113 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54717 | false | false |
5
|
a0618f850be230c41c1ce5159112adcb496de572
| 29,480,655,542,219 |
a6a198cee9b54d162ea851ab4b5c7496a67aa7ed
|
/app/src/main/java/com/example/myapplication/models/Post.java
|
6435ca704c47ba2af9a5f0460a7afbe0899bc23d
|
[] |
no_license
|
tjgusdn07/SupportApp
|
https://github.com/tjgusdn07/SupportApp
|
80efeb21dfa8ec53c46db62d5770c23398685a2c
|
4c1e8d898f3f3418fc03d45aeba142efc0547907
|
refs/heads/master
| 2023-08-29T01:38:47.843000 | 2021-10-27T13:09:32 | 2021-10-27T13:09:32 | 354,273,752 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.myapplication.models;
public class Post {
public String imgName;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getView_cnt() {
return view_cnt;
}
public void setView_cnt(int view_cnt) {
this.view_cnt = view_cnt;
}
public String type;
public String title;
public String username;
public String date;
public int view_cnt;
public String contents;
public String img;
public String key;
public String target;
public String t_uid;
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
|
UTF-8
|
Java
| 1,325 |
java
|
Post.java
|
Java
|
[
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getDate() {\n ret",
"end": 506,
"score": 0.8820626139640808,
"start": 498,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.example.myapplication.models;
public class Post {
public String imgName;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getView_cnt() {
return view_cnt;
}
public void setView_cnt(int view_cnt) {
this.view_cnt = view_cnt;
}
public String type;
public String title;
public String username;
public String date;
public int view_cnt;
public String contents;
public String img;
public String key;
public String target;
public String t_uid;
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
| 1,325 | 0.584906 | 0.584906 | 77 | 16.207792 | 14.456686 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.337662 | false | false |
5
|
aa79361c7fad3bf3b730f6f2f692aae24169bbf2
| 38,714,835,248,571 |
00b2b31b70a9a1e3213541b78357ef0d7d164662
|
/src/main/java/com/devjr/taco/cloud/controllers/HomeController.java
|
c6c2b221f25db5438b9872a3357b079ec4ab2e55
|
[] |
no_license
|
JacintoRR396/spring-boot-taco-cloud
|
https://github.com/JacintoRR396/spring-boot-taco-cloud
|
dbf1652790b79bd14fa4ce2e360709c5d2e91166
|
472e32c55b99764250a1f55158bcfc1c21b75a4d
|
refs/heads/master
| 2020-06-29T12:36:01.188000 | 2019-08-08T10:02:52 | 2019-08-08T10:02:52 | 200,538,525 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.devjr.taco.cloud.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.devjr.taco.cloud.tools.UtilityConfig;
@Controller
public class HomeController{
@GetMapping(UtilityConfig.S_PATH_HOME)
public String home(){
return UtilityConfig.S_VIEW_HOME;
}
}
|
UTF-8
|
Java
| 364 |
java
|
HomeController.java
|
Java
|
[] | null |
[] |
package com.devjr.taco.cloud.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.devjr.taco.cloud.tools.UtilityConfig;
@Controller
public class HomeController{
@GetMapping(UtilityConfig.S_PATH_HOME)
public String home(){
return UtilityConfig.S_VIEW_HOME;
}
}
| 364 | 0.774725 | 0.774725 | 16 | 21.8125 | 21.122318 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false |
5
|
3e09d8294b372f232eab24df5b6e6e3ff023b4d3
| 38,422,777,444,887 |
6f672fb72caedccb841ee23f53e32aceeaf1895e
|
/GooglePlay_source/src/com/google/android/gms/common/internal/PermissionCheckPreProcessor.java
|
6fba9906cf2c77f1d3f44acd2bcc9aaeeca730d0
|
[] |
no_license
|
cha63506/CompSecurity
|
https://github.com/cha63506/CompSecurity
|
5c69743f660b9899146ed3cf21eceabe3d5f4280
|
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
|
refs/heads/master
| 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.common.internal;
import android.content.Context;
import android.os.RemoteException;
import com.google.android.gms.common.permission.PermissionUtils;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
// Referenced classes of package com.google.android.gms.common.internal:
// GetServicePreProcessor, GetServiceRequest, IGmsCallbacks
public final class PermissionCheckPreProcessor extends GetServicePreProcessor
{
private PermissionUtils mPermUtils;
private Set mRequiredPermGroups;
public PermissionCheckPreProcessor(Context context, Set set)
{
this(context, set, PermissionUtils.getInstance());
}
private PermissionCheckPreProcessor(Context context, Set set, PermissionUtils permissionutils)
{
super(context);
mRequiredPermGroups = set;
mPermUtils = permissionutils;
}
public final boolean process(IGmsCallbacks igmscallbacks, GetServiceRequest getservicerequest)
throws RemoteException
{
if (!"com.google.android.gms".equals(getservicerequest.callingPackage))
{
Object obj = mPermUtils;
Set set = mRequiredPermGroups;
if (set == null)
{
obj = Collections.emptySet();
} else
{
obj = new HashSet(((PermissionUtils) (obj)).getMissingPermissionGroups());
((Set) (obj)).retainAll(set);
}
if (!((Set) (obj)).isEmpty())
{
logAndCallback(igmscallbacks, getservicerequest, 19, PermissionUtils.getRecoverPermissionIntent(mContext.getApplicationContext(), mRequiredPermGroups));
return false;
}
}
return true;
}
}
|
UTF-8
|
Java
| 1,972 |
java
|
PermissionCheckPreProcessor.java
|
Java
|
[
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.999648928642273,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null |
[] |
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.common.internal;
import android.content.Context;
import android.os.RemoteException;
import com.google.android.gms.common.permission.PermissionUtils;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
// Referenced classes of package com.google.android.gms.common.internal:
// GetServicePreProcessor, GetServiceRequest, IGmsCallbacks
public final class PermissionCheckPreProcessor extends GetServicePreProcessor
{
private PermissionUtils mPermUtils;
private Set mRequiredPermGroups;
public PermissionCheckPreProcessor(Context context, Set set)
{
this(context, set, PermissionUtils.getInstance());
}
private PermissionCheckPreProcessor(Context context, Set set, PermissionUtils permissionutils)
{
super(context);
mRequiredPermGroups = set;
mPermUtils = permissionutils;
}
public final boolean process(IGmsCallbacks igmscallbacks, GetServiceRequest getservicerequest)
throws RemoteException
{
if (!"com.google.android.gms".equals(getservicerequest.callingPackage))
{
Object obj = mPermUtils;
Set set = mRequiredPermGroups;
if (set == null)
{
obj = Collections.emptySet();
} else
{
obj = new HashSet(((PermissionUtils) (obj)).getMissingPermissionGroups());
((Set) (obj)).retainAll(set);
}
if (!((Set) (obj)).isEmpty())
{
logAndCallback(igmscallbacks, getservicerequest, 19, PermissionUtils.getRecoverPermissionIntent(mContext.getApplicationContext(), mRequiredPermGroups));
return false;
}
}
return true;
}
}
| 1,962 | 0.66785 | 0.663286 | 58 | 33 | 32.504642 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568965 | false | false |
5
|
633648ff66648934097802126f065d6840361ea9
| 38,414,187,511,183 |
5b210c51539e5378c95d82f2dcb74c1ad5714fed
|
/app/src/main/java/net/hb/day0628/Work01jumin.java
|
84f7f21ca94cd5ed26ca6629fa6ed5a46d3b81a3
|
[] |
no_license
|
HHwanseung/Day0628
|
https://github.com/HHwanseung/Day0628
|
b7fbb7a0a3ee630661f0c2339508f3d83ed8eb91
|
8eb3e7a1208aa1bc1d6453978f90b74bae018fd9
|
refs/heads/main
| 2023-06-25T11:34:04.921000 | 2021-07-27T01:50:32 | 2021-07-27T01:50:32 | 381,344,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.hb.day0628;
public class Work01jumin {
public static void main(String[] args) {
String min = "871024-1541965"; //키보드입력 대신 초기값
String min1 = "871024";
String min2 = "1541965";
//문제1 총자릿수 6 - 7 13자릿수, 14자릿수
int len = min.length();
System.out.println("총자릿수 = " + len);
//문제2 ******-1541965
String data = min.substring(min.indexOf("-")+1);
System.out.println("******-"+data);
//문제3 1/3남자 2/4여자
char gender = min.charAt(7);
switch (gender) {
case'1' :
case'3' :
System.out.println("남자입니다.");
case'2' :
case'4' :
System.out.println("여자입니다.");
break;
default :
System.out.println("잘못된 성별입니다.");
break;
}
//length(),substring(),indexOF(),charAt()
}//end
}//class END
|
UTF-8
|
Java
| 867 |
java
|
Work01jumin.java
|
Java
|
[] | null |
[] |
package net.hb.day0628;
public class Work01jumin {
public static void main(String[] args) {
String min = "871024-1541965"; //키보드입력 대신 초기값
String min1 = "871024";
String min2 = "1541965";
//문제1 총자릿수 6 - 7 13자릿수, 14자릿수
int len = min.length();
System.out.println("총자릿수 = " + len);
//문제2 ******-1541965
String data = min.substring(min.indexOf("-")+1);
System.out.println("******-"+data);
//문제3 1/3남자 2/4여자
char gender = min.charAt(7);
switch (gender) {
case'1' :
case'3' :
System.out.println("남자입니다.");
case'2' :
case'4' :
System.out.println("여자입니다.");
break;
default :
System.out.println("잘못된 성별입니다.");
break;
}
//length(),substring(),indexOF(),charAt()
}//end
}//class END
| 867 | 0.577982 | 0.499345 | 41 | 17.609756 | 15.039587 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.170732 | false | false |
5
|
829a2442b87f2076bae407c90793d4a1a6f7f048
| 10,505,490,056,993 |
60ca3e0584a7df6dc6b6e4e627fbe4cbb0c747d9
|
/bariwala/src/main/java/com/bariwala/bariwala/authentication/Authentication.java
|
7b1d9c9fcaaaa1188322d4a1b774c1c0623d1963
|
[] |
no_license
|
DigitizeioBangladesh/barioyalaAPI
|
https://github.com/DigitizeioBangladesh/barioyalaAPI
|
81b8339bb36eb60c595f2f01c44d83543dfc1c47
|
88d77d660a8745b021ddacbf4e74f4bc10c04532
|
refs/heads/master
| 2023-08-20T07:47:14.079000 | 2021-10-18T19:46:41 | 2021-10-18T19:46:41 | 418,640,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bariwala.bariwala.authentication;
import com.bariwala.bariwala.repositories.OracleDBConnectionPool;
import com.bariwala.bariwala.utilities.APIConfiguration;
import org.apache.log4j.Logger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Authentication {
static final Logger errorLog = Logger.getLogger("errorLogger");
static final Logger reportsLog = Logger.getLogger("reportsLog");
;
private APIConfiguration configuration;
private static OracleDBConnectionPool oracleDBConnectionPool;
public Authentication() {
configuration = APIConfiguration.getInstance();
oracleDBConnectionPool = OracleDBConnectionPool.getInstance();
}
private Connection getAPIDBConnection() throws SQLException {
return oracleDBConnectionPool.getApiDBConnection();
}
public boolean passwordValidator(String userName, String password,String function_name,String ip)
{
if ((userName == null) && (password == null)) {
return false;
}
if (isAuthorized(userName, getMD5EncryptedValue(password), function_name, ip).equals("000")) {
return true;
}
return false;
}
public String getMD5EncryptedValue(String password) {
final byte[] defaultBytes = password.getBytes();
try {
final MessageDigest md5MsgDigest = MessageDigest.getInstance("MD5");
md5MsgDigest.reset();
md5MsgDigest.update(defaultBytes);
final byte messageDigest[] = md5MsgDigest.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : messageDigest) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
password = hexString + "";
} catch (final NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
return password;
}
public String isAuthorized(String username, String password, String function_name,String ip) {
Connection connection = null;
Statement myStatement = null;
try {
connection = getAPIDBConnection();
myStatement = connection.createStatement();
} catch (SQLException ex) {
errorLog.error("Connection Error");
}
String response="";
try
{
CallableStatement stmt = null;
stmt = connection.prepareCall("call ER_USR.MID_PKG.isAuthorized (?,?,?,?,?)");
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, function_name);
stmt.setString(4, ip);
stmt.registerOutParameter(5, oracle.jdbc.OracleTypes.VARCHAR);
stmt.execute();
response = stmt.getString(5);
} catch (SQLException e) {
// logDAO.insertMessageLog(
// new MessageLog("SQLException", "Error", e.getMessage(), "isAuthorized", new Date()));
//logger.error(e.getMessage(), e);
} finally {
if (connection != null)
try {
if (!connection.isClosed())
connection.close();
} catch (Exception ex) {
errorLog.error("Connection Error");
}
}
return response;
}
}
|
UTF-8
|
Java
| 3,678 |
java
|
Authentication.java
|
Java
|
[] | null |
[] |
package com.bariwala.bariwala.authentication;
import com.bariwala.bariwala.repositories.OracleDBConnectionPool;
import com.bariwala.bariwala.utilities.APIConfiguration;
import org.apache.log4j.Logger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Authentication {
static final Logger errorLog = Logger.getLogger("errorLogger");
static final Logger reportsLog = Logger.getLogger("reportsLog");
;
private APIConfiguration configuration;
private static OracleDBConnectionPool oracleDBConnectionPool;
public Authentication() {
configuration = APIConfiguration.getInstance();
oracleDBConnectionPool = OracleDBConnectionPool.getInstance();
}
private Connection getAPIDBConnection() throws SQLException {
return oracleDBConnectionPool.getApiDBConnection();
}
public boolean passwordValidator(String userName, String password,String function_name,String ip)
{
if ((userName == null) && (password == null)) {
return false;
}
if (isAuthorized(userName, getMD5EncryptedValue(password), function_name, ip).equals("000")) {
return true;
}
return false;
}
public String getMD5EncryptedValue(String password) {
final byte[] defaultBytes = password.getBytes();
try {
final MessageDigest md5MsgDigest = MessageDigest.getInstance("MD5");
md5MsgDigest.reset();
md5MsgDigest.update(defaultBytes);
final byte messageDigest[] = md5MsgDigest.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : messageDigest) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
password = hexString + "";
} catch (final NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
return password;
}
public String isAuthorized(String username, String password, String function_name,String ip) {
Connection connection = null;
Statement myStatement = null;
try {
connection = getAPIDBConnection();
myStatement = connection.createStatement();
} catch (SQLException ex) {
errorLog.error("Connection Error");
}
String response="";
try
{
CallableStatement stmt = null;
stmt = connection.prepareCall("call ER_USR.MID_PKG.isAuthorized (?,?,?,?,?)");
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, function_name);
stmt.setString(4, ip);
stmt.registerOutParameter(5, oracle.jdbc.OracleTypes.VARCHAR);
stmt.execute();
response = stmt.getString(5);
} catch (SQLException e) {
// logDAO.insertMessageLog(
// new MessageLog("SQLException", "Error", e.getMessage(), "isAuthorized", new Date()));
//logger.error(e.getMessage(), e);
} finally {
if (connection != null)
try {
if (!connection.isClosed())
connection.close();
} catch (Exception ex) {
errorLog.error("Connection Error");
}
}
return response;
}
}
| 3,678 | 0.60522 | 0.599782 | 109 | 32.743118 | 26.613924 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.697248 | false | false |
5
|
06a6873d9e5d1d1be27bac83ed37be49ecbd26c0
| 34,840,774,730,461 |
f1bcdee29a3775164cf5c1c3ed070944a4b70f4f
|
/src/main/java/com/diploma/Backend/rest/controller/ReportController.java
|
65a006c972c39b2248cface8bb2c332c443e192c
|
[] |
no_license
|
WeWillLose/NewBackend
|
https://github.com/WeWillLose/NewBackend
|
cac031bf16fa30ca1b34ee53f3b2d21c70c08bd8
|
987316516d64f9a0697f420bfe92f2a08df311f0
|
refs/heads/master
| 2023-04-23T02:08:46.733000 | 2021-05-08T19:14:37 | 2021-05-08T19:14:37 | 358,354,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.diploma.Backend.rest.controller;
import com.diploma.Backend.model.Report;
import com.diploma.Backend.model.User;
import com.diploma.Backend.rest.dto.InputStreamResourceDTO;
import com.diploma.Backend.rest.dto.ReportDTO;
import com.diploma.Backend.rest.dto.ReportStatusDTO;
import com.diploma.Backend.rest.service.mapper.IReportMapper;
import com.diploma.Backend.service.report.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("api/v1/report")
@RequiredArgsConstructor
@Slf4j
public class ReportController {
private final ReportService reportService;
private final IReportMapper reportMapperService;
@PostMapping("")
public ResponseEntity<?> saveReport(@RequestBody ReportDTO report, @AuthenticationPrincipal User user){
return ResponseEntity.ok(reportService.saveReport(reportMapperService.reportDTOToReport(report),user.getId()));
}
@GetMapping("docx/{id:\\d+}")
public ResponseEntity<?> getReportDocx(@PathVariable Long id){
InputStreamResourceDTO inputStreamResource = reportService.generateReportDocx(id);
HttpHeaders headers = new HttpHeaders();
String format = String.format("attachment; filename=%s", inputStreamResource.getFileName());
headers.add(HttpHeaders.CONTENT_DISPOSITION,format);
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(inputStreamResource.getInputStreamResource());
}
@GetMapping("author/current")
public ResponseEntity<?> getReportByCurrentUser(@AuthenticationPrincipal User user){
List<ReportDTO> reportDTOS = reportMapperService.reportToReportDTOsWithoutData(reportService.findAllByAuthorId(user.getId()));
return ResponseEntity.ok().body(reportDTOS);
}
@GetMapping("followers/{id}")
public ResponseEntity<?> getReportByChairmanId(@PathVariable(name = "id") Long chairmanID){
List<ReportDTO> followersReports = reportMapperService.reportToReportDTOsWithoutData(reportService.findFollowersReports(chairmanID));
return ResponseEntity.ok().body(followersReports);
}
@GetMapping("followers/current")
public ResponseEntity<?> getReportByChairmanId(@AuthenticationPrincipal User user){
List<ReportDTO> followersReports = reportMapperService.reportToReportDTOsWithoutData(reportService.findFollowersReports(user.getId()));
return ResponseEntity.ok().body(followersReports);
}
@DeleteMapping("{id}")
public ResponseEntity<?> deleteReportById(@PathVariable Long id){
reportService.deleteReport(id);
return ResponseEntity.ok().body(null);
}
@GetMapping("author/{id}")
public ResponseEntity<List<ReportDTO>> getReportByAuthor(@PathVariable Long id){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTOs(reportService.findAllByAuthorId(id)));
}
@GetMapping("{id}")
public ResponseEntity<?> getReportByReportId(@PathVariable(name = "id") Long reportId){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.findByReportId(reportId).orElse(null)));
}
@GetMapping("withoutdata/{id}")
public ResponseEntity<?> getReportByReportIdWithoutData(@PathVariable(name = "id") Long reportId){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTOWithoutData(reportService.findByReportId(reportId).orElse(null)));
}
@PutMapping("data/{id}")
public ResponseEntity<?> updateReportData(@PathVariable(name="id") Long reportId, @RequestBody ReportDTO reportDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReportData(reportId,
reportMapperService.reportDTOToReport(reportDTO))));
}
@PutMapping("{id}")
@PreAuthorize("hasAnyRole('ADMIN','CHAIRMAN')")
public ResponseEntity<?> updateReport(@PathVariable(name="id") Long reportId, @RequestBody ReportDTO reportDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReport(reportId,
reportMapperService.reportDTOToReport(reportDTO))));
}
@PutMapping("status/{id}")
@PreAuthorize("hasAnyRole('ADMIN','CHAIRMAN')")
public ResponseEntity<?> updateReportStatus(@PathVariable(name="id") Long reportId, @Valid @RequestBody ReportStatusDTO reportStatusDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReportStatus(reportId,reportStatusDTO.getStatus())));
}
}
|
UTF-8
|
Java
| 5,087 |
java
|
ReportController.java
|
Java
|
[] | null |
[] |
package com.diploma.Backend.rest.controller;
import com.diploma.Backend.model.Report;
import com.diploma.Backend.model.User;
import com.diploma.Backend.rest.dto.InputStreamResourceDTO;
import com.diploma.Backend.rest.dto.ReportDTO;
import com.diploma.Backend.rest.dto.ReportStatusDTO;
import com.diploma.Backend.rest.service.mapper.IReportMapper;
import com.diploma.Backend.service.report.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("api/v1/report")
@RequiredArgsConstructor
@Slf4j
public class ReportController {
private final ReportService reportService;
private final IReportMapper reportMapperService;
@PostMapping("")
public ResponseEntity<?> saveReport(@RequestBody ReportDTO report, @AuthenticationPrincipal User user){
return ResponseEntity.ok(reportService.saveReport(reportMapperService.reportDTOToReport(report),user.getId()));
}
@GetMapping("docx/{id:\\d+}")
public ResponseEntity<?> getReportDocx(@PathVariable Long id){
InputStreamResourceDTO inputStreamResource = reportService.generateReportDocx(id);
HttpHeaders headers = new HttpHeaders();
String format = String.format("attachment; filename=%s", inputStreamResource.getFileName());
headers.add(HttpHeaders.CONTENT_DISPOSITION,format);
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(inputStreamResource.getInputStreamResource());
}
@GetMapping("author/current")
public ResponseEntity<?> getReportByCurrentUser(@AuthenticationPrincipal User user){
List<ReportDTO> reportDTOS = reportMapperService.reportToReportDTOsWithoutData(reportService.findAllByAuthorId(user.getId()));
return ResponseEntity.ok().body(reportDTOS);
}
@GetMapping("followers/{id}")
public ResponseEntity<?> getReportByChairmanId(@PathVariable(name = "id") Long chairmanID){
List<ReportDTO> followersReports = reportMapperService.reportToReportDTOsWithoutData(reportService.findFollowersReports(chairmanID));
return ResponseEntity.ok().body(followersReports);
}
@GetMapping("followers/current")
public ResponseEntity<?> getReportByChairmanId(@AuthenticationPrincipal User user){
List<ReportDTO> followersReports = reportMapperService.reportToReportDTOsWithoutData(reportService.findFollowersReports(user.getId()));
return ResponseEntity.ok().body(followersReports);
}
@DeleteMapping("{id}")
public ResponseEntity<?> deleteReportById(@PathVariable Long id){
reportService.deleteReport(id);
return ResponseEntity.ok().body(null);
}
@GetMapping("author/{id}")
public ResponseEntity<List<ReportDTO>> getReportByAuthor(@PathVariable Long id){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTOs(reportService.findAllByAuthorId(id)));
}
@GetMapping("{id}")
public ResponseEntity<?> getReportByReportId(@PathVariable(name = "id") Long reportId){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.findByReportId(reportId).orElse(null)));
}
@GetMapping("withoutdata/{id}")
public ResponseEntity<?> getReportByReportIdWithoutData(@PathVariable(name = "id") Long reportId){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTOWithoutData(reportService.findByReportId(reportId).orElse(null)));
}
@PutMapping("data/{id}")
public ResponseEntity<?> updateReportData(@PathVariable(name="id") Long reportId, @RequestBody ReportDTO reportDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReportData(reportId,
reportMapperService.reportDTOToReport(reportDTO))));
}
@PutMapping("{id}")
@PreAuthorize("hasAnyRole('ADMIN','CHAIRMAN')")
public ResponseEntity<?> updateReport(@PathVariable(name="id") Long reportId, @RequestBody ReportDTO reportDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReport(reportId,
reportMapperService.reportDTOToReport(reportDTO))));
}
@PutMapping("status/{id}")
@PreAuthorize("hasAnyRole('ADMIN','CHAIRMAN')")
public ResponseEntity<?> updateReportStatus(@PathVariable(name="id") Long reportId, @Valid @RequestBody ReportStatusDTO reportStatusDTO){
return ResponseEntity.ok().body(reportMapperService.reportToReportDTO(reportService.updateReportStatus(reportId,reportStatusDTO.getStatus())));
}
}
| 5,087 | 0.750344 | 0.749558 | 105 | 47.44762 | 42.425282 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.504762 | false | false |
5
|
33076717d32b04f4a9b0edea74714842b0862da7
| 37,632,503,454,571 |
0adf9a6d0de1cce3c3da189584a1ed21fc9664ee
|
/NovaCore-GameEngine/src/net/zeeraa/novacore/spigot/gameengine/module/modules/game/map/mapmodules/fireresistance/FireReistanceMapModule.java
|
0e74c3418f590e2d9e3580e3f7e2816f807422d1
|
[
"MIT"
] |
permissive
|
AntonUden/NovaCore
|
https://github.com/AntonUden/NovaCore
|
af6ce9f2002d15e2d1a6ca00e06358c08054201b
|
f347f86cbe7d3e6836ed79fdb68c05c4c932d1a8
|
refs/heads/master
| 2023-07-18T23:34:15.359000 | 2023-07-15T15:31:45 | 2023-07-15T15:31:45 | 279,360,767 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.zeeraa.novacore.spigot.gameengine.module.modules.game.map.mapmodules.fireresistance;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.json.JSONObject;
import net.zeeraa.novacore.commons.tasks.Task;
import net.zeeraa.novacore.spigot.gameengine.module.modules.game.Game;
import net.zeeraa.novacore.spigot.gameengine.module.modules.game.map.mapmodule.MapModule;
import net.zeeraa.novacore.spigot.tasks.SimpleTask;
public class FireReistanceMapModule extends MapModule implements Listener {
private boolean extinguish;
private Task task;
public FireReistanceMapModule(JSONObject json) {
super(json);
extinguish = json.optBoolean("extinguish", false);
task = null;
}
@Override
public void onGameStart(Game game) {
Bukkit.getServer().getPluginManager().registerEvents(this, game.getPlugin());
if (extinguish) {
task = new SimpleTask(game.getPlugin(), () -> Bukkit.getServer().getOnlinePlayers().forEach(player -> player.setFireTicks(0)), 1L);
Task.tryStartTask(task);
}
}
@Override
public void onGameEnd(Game game) {
HandlerList.unregisterAll(this);
Task.tryStopTask(task);
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent e) {
if (e.getEntity() instanceof Player) {
if (e.getCause() == DamageCause.LAVA || e.getCause() == DamageCause.FIRE || e.getCause() == DamageCause.FIRE_TICK) {
e.setCancelled(true);
}
}
}
@Override
public String getSummaryString() {
return ChatColor.GOLD + "Extinguish: " + ChatColor.AQUA + extinguish;
}
}
|
UTF-8
|
Java
| 1,878 |
java
|
FireReistanceMapModule.java
|
Java
|
[] | null |
[] |
package net.zeeraa.novacore.spigot.gameengine.module.modules.game.map.mapmodules.fireresistance;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.json.JSONObject;
import net.zeeraa.novacore.commons.tasks.Task;
import net.zeeraa.novacore.spigot.gameengine.module.modules.game.Game;
import net.zeeraa.novacore.spigot.gameengine.module.modules.game.map.mapmodule.MapModule;
import net.zeeraa.novacore.spigot.tasks.SimpleTask;
public class FireReistanceMapModule extends MapModule implements Listener {
private boolean extinguish;
private Task task;
public FireReistanceMapModule(JSONObject json) {
super(json);
extinguish = json.optBoolean("extinguish", false);
task = null;
}
@Override
public void onGameStart(Game game) {
Bukkit.getServer().getPluginManager().registerEvents(this, game.getPlugin());
if (extinguish) {
task = new SimpleTask(game.getPlugin(), () -> Bukkit.getServer().getOnlinePlayers().forEach(player -> player.setFireTicks(0)), 1L);
Task.tryStartTask(task);
}
}
@Override
public void onGameEnd(Game game) {
HandlerList.unregisterAll(this);
Task.tryStopTask(task);
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent e) {
if (e.getEntity() instanceof Player) {
if (e.getCause() == DamageCause.LAVA || e.getCause() == DamageCause.FIRE || e.getCause() == DamageCause.FIRE_TICK) {
e.setCancelled(true);
}
}
}
@Override
public String getSummaryString() {
return ChatColor.GOLD + "Extinguish: " + ChatColor.AQUA + extinguish;
}
}
| 1,878 | 0.768371 | 0.767306 | 58 | 31.396551 | 31.222197 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.551724 | false | false |
5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.