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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3156e3f0caea2e4b5d90b473bc4c1eff0e4cc692
| 29,721,173,742,793 |
e12b01968e03be1f4df28d7415d48225089c0f58
|
/crypto/support/hashes/argon2/src/main/java/org/apache/shiro/crypto/support/hashes/argon2/Argon2HashProvider.java
|
2a8fdee40b6b8fa0dcff4f697e29f6eb6ed419d1
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown"
] |
permissive
|
apache/shiro
|
https://github.com/apache/shiro
|
331ace9cd8cd71adbf661ff8e89e8b4eeba7f8d6
|
26989066e3581884a188a306abda48d7159d0726
|
refs/heads/main
| 2023-08-28T01:48:02.760000 | 2023-08-27T06:31:04 | 2023-08-27T06:31:04 | 291,570 | 4,614 | 2,825 |
Apache-2.0
| false | 2023-09-14T18:04:57 | 2009-08-29T08:00:17 | 2023-09-14T05:45:57 | 2023-09-14T18:04:55 | 28,100 | 4,165 | 2,337 | 14 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shiro.crypto.support.hashes.argon2;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.HashSpi;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.lang.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Locale;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
/**
* A HashProvider for the Argon2 hash algorithm.
*
* <p>This class is intended to be used by the {@code HashProvider} class from Shiro. However,
* this class can also be used to created instances of the Argon2 hash manually.</p>
*
* <p>Furthermore, there is a nested {@link Parameters} class which provides names for the
* keys used in the parameters map of the {@link HashRequest} class.</p>
*
* @since 2.0
*/
public class Argon2HashProvider implements HashSpi {
private static final Logger LOG = LoggerFactory.getLogger(Argon2HashProvider.class);
@Override
public Set<String> getImplementedAlgorithms() {
return Argon2Hash.getAlgorithmsArgon2();
}
@Override
public Argon2Hash fromString(String format) {
return Argon2Hash.fromString(format);
}
@Override
public HashFactory newHashFactory(Random random) {
return new Argon2HashFactory(random);
}
static class Argon2HashFactory implements HashSpi.HashFactory {
private final SecureRandom random;
public Argon2HashFactory(Random random) {
if (!(random instanceof SecureRandom)) {
throw new IllegalArgumentException("Only SecureRandom instances are supported at the moment!");
}
this.random = (SecureRandom) random;
}
@Override
public Argon2Hash generate(HashRequest hashRequest) {
final String algorithmName = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ALGORITHM_NAME))
.map(algo -> (String) algo)
.orElse(Parameters.DEFAULT_ALGORITHM_NAME);
final int version = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ALGORITHM_VERSION))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_ALGORITHM_VERSION))
.orElse(Parameters.DEFAULT_ALGORITHM_VERSION);
final ByteSource salt = parseSalt(hashRequest);
final int iterations = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ITERATIONS))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_ITERATIONS))
.orElse(Parameters.DEFAULT_ITERATIONS);
final int memoryKib = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_MEMORY_KIB))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_MEMORY_KIB))
.orElse(Parameters.DEFAULT_MEMORY_KIB);
final int parallelism = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_PARALLELISM))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_PARALLELISM))
.orElse(Parameters.DEFAULT_PARALLELISM);
final int outputLengthBits = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_OUTPUT_LENGTH_BITS))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_OUTPUT_LENGTH_BITS))
.orElse(Parameters.DEFAULT_OUTPUT_LENGTH_BITS);
return Argon2Hash.generate(
algorithmName,
version,
hashRequest.getSource(),
salt,
iterations,
memoryKib,
parallelism,
outputLengthBits
);
}
private ByteSource parseSalt(HashRequest hashRequest) {
return Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_SALT))
.map(saltParm -> Base64.getDecoder().decode((String) saltParm))
.map(SimpleByteSource::new)
.flatMap(this::lengthValidOrEmpty)
.orElseGet(() -> Argon2Hash.createSalt(random));
}
private Optional<ByteSource> lengthValidOrEmpty(ByteSource bytes) {
if (bytes.getBytes().length != 16) {
return Optional.empty();
}
return Optional.of(bytes);
}
private Optional<Integer> intOrEmpty(Object maybeInt, String parameterName) {
try {
return Optional.of(Integer.parseInt((String) maybeInt, 10));
} catch (NumberFormatException numberFormatException) {
String message = String.format(
Locale.ENGLISH,
"Expected Integer for parameter %s, but %s is not parsable.",
parameterName, maybeInt
);
LOG.warn(message, numberFormatException);
return Optional.empty();
}
}
}
/**
* Parameters for the {@link Argon2Hash} class.
*
* <p>This class contains public constants only. The constants starting with {@code PARAMETER_} are
* the parameter names recognized by the
* {@link org.apache.shiro.crypto.hash.HashSpi.HashFactory#generate(HashRequest)} method.</p>
*
* <p>The constants starting with {@code DEFAULT_} are their respective default values.</p>
*/
public static final class Parameters {
public static final String DEFAULT_ALGORITHM_NAME = Argon2Hash.DEFAULT_ALGORITHM_NAME;
public static final int DEFAULT_ALGORITHM_VERSION = Argon2Hash.DEFAULT_ALGORITHM_VERSION;
public static final int DEFAULT_ITERATIONS = Argon2Hash.DEFAULT_ITERATIONS;
public static final int DEFAULT_MEMORY_KIB = Argon2Hash.DEFAULT_MEMORY_KIB;
public static final int DEFAULT_PARALLELISM = Argon2Hash.DEFAULT_PARALLELISM;
public static final int DEFAULT_OUTPUT_LENGTH_BITS = Argon2Hash.DEFAULT_OUTPUT_LENGTH_BITS;
/**
* Parameter for modifying the internal algorithm used by Argon2.
*
* <p>Valid values are {@code argon2i} (optimized to resist side-channel attacks),
* {@code argon2d} (maximizes resistance to GPU cracking attacks)
* and {@code argon2id} (a hybrid version).</p>
*
* <p>The default value is {@value DEFAULT_ALGORITHM_NAME} when this parameter is not specified.</p>
*/
public static final String PARAMETER_ALGORITHM_NAME = "Argon2.algorithmName";
public static final String PARAMETER_ALGORITHM_VERSION = "Argon2.version";
/**
* The salt to use.
*
* <p>The value for this parameter accepts a Base64-encoded 16byte (128bit) salt.</p>
*
* <p>As for any KDF, do not use a static salt value for multiple passwords.</p>
*
* <p>The default value is a new random 128bit-salt, if this parameter is not specified.</p>
*/
public static final String PARAMETER_SALT = "Argon2.salt";
public static final String PARAMETER_ITERATIONS = "Argon2.iterations";
public static final String PARAMETER_MEMORY_KIB = "Argon2.memoryKib";
public static final String PARAMETER_PARALLELISM = "Argon2.parallelism";
/**
* The output length (in bits) of the resulting data section.
*
* <p>Argon2 allows to modify the length of the generated output.</p>
*
* <p>The default value is {@value DEFAULT_OUTPUT_LENGTH_BITS} when this parameter is not specified.</p>
*/
public static final String PARAMETER_OUTPUT_LENGTH_BITS = "Argon2.outputLength";
private Parameters() {
// utility class
}
}
}
|
UTF-8
|
Java
| 8,808 |
java
|
Argon2HashProvider.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shiro.crypto.support.hashes.argon2;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.HashSpi;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.lang.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Locale;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
/**
* A HashProvider for the Argon2 hash algorithm.
*
* <p>This class is intended to be used by the {@code HashProvider} class from Shiro. However,
* this class can also be used to created instances of the Argon2 hash manually.</p>
*
* <p>Furthermore, there is a nested {@link Parameters} class which provides names for the
* keys used in the parameters map of the {@link HashRequest} class.</p>
*
* @since 2.0
*/
public class Argon2HashProvider implements HashSpi {
private static final Logger LOG = LoggerFactory.getLogger(Argon2HashProvider.class);
@Override
public Set<String> getImplementedAlgorithms() {
return Argon2Hash.getAlgorithmsArgon2();
}
@Override
public Argon2Hash fromString(String format) {
return Argon2Hash.fromString(format);
}
@Override
public HashFactory newHashFactory(Random random) {
return new Argon2HashFactory(random);
}
static class Argon2HashFactory implements HashSpi.HashFactory {
private final SecureRandom random;
public Argon2HashFactory(Random random) {
if (!(random instanceof SecureRandom)) {
throw new IllegalArgumentException("Only SecureRandom instances are supported at the moment!");
}
this.random = (SecureRandom) random;
}
@Override
public Argon2Hash generate(HashRequest hashRequest) {
final String algorithmName = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ALGORITHM_NAME))
.map(algo -> (String) algo)
.orElse(Parameters.DEFAULT_ALGORITHM_NAME);
final int version = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ALGORITHM_VERSION))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_ALGORITHM_VERSION))
.orElse(Parameters.DEFAULT_ALGORITHM_VERSION);
final ByteSource salt = parseSalt(hashRequest);
final int iterations = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_ITERATIONS))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_ITERATIONS))
.orElse(Parameters.DEFAULT_ITERATIONS);
final int memoryKib = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_MEMORY_KIB))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_MEMORY_KIB))
.orElse(Parameters.DEFAULT_MEMORY_KIB);
final int parallelism = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_PARALLELISM))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_PARALLELISM))
.orElse(Parameters.DEFAULT_PARALLELISM);
final int outputLengthBits = Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_OUTPUT_LENGTH_BITS))
.flatMap(algoV -> intOrEmpty(algoV, Parameters.PARAMETER_OUTPUT_LENGTH_BITS))
.orElse(Parameters.DEFAULT_OUTPUT_LENGTH_BITS);
return Argon2Hash.generate(
algorithmName,
version,
hashRequest.getSource(),
salt,
iterations,
memoryKib,
parallelism,
outputLengthBits
);
}
private ByteSource parseSalt(HashRequest hashRequest) {
return Optional.ofNullable(hashRequest.getParameters().get(Parameters.PARAMETER_SALT))
.map(saltParm -> Base64.getDecoder().decode((String) saltParm))
.map(SimpleByteSource::new)
.flatMap(this::lengthValidOrEmpty)
.orElseGet(() -> Argon2Hash.createSalt(random));
}
private Optional<ByteSource> lengthValidOrEmpty(ByteSource bytes) {
if (bytes.getBytes().length != 16) {
return Optional.empty();
}
return Optional.of(bytes);
}
private Optional<Integer> intOrEmpty(Object maybeInt, String parameterName) {
try {
return Optional.of(Integer.parseInt((String) maybeInt, 10));
} catch (NumberFormatException numberFormatException) {
String message = String.format(
Locale.ENGLISH,
"Expected Integer for parameter %s, but %s is not parsable.",
parameterName, maybeInt
);
LOG.warn(message, numberFormatException);
return Optional.empty();
}
}
}
/**
* Parameters for the {@link Argon2Hash} class.
*
* <p>This class contains public constants only. The constants starting with {@code PARAMETER_} are
* the parameter names recognized by the
* {@link org.apache.shiro.crypto.hash.HashSpi.HashFactory#generate(HashRequest)} method.</p>
*
* <p>The constants starting with {@code DEFAULT_} are their respective default values.</p>
*/
public static final class Parameters {
public static final String DEFAULT_ALGORITHM_NAME = Argon2Hash.DEFAULT_ALGORITHM_NAME;
public static final int DEFAULT_ALGORITHM_VERSION = Argon2Hash.DEFAULT_ALGORITHM_VERSION;
public static final int DEFAULT_ITERATIONS = Argon2Hash.DEFAULT_ITERATIONS;
public static final int DEFAULT_MEMORY_KIB = Argon2Hash.DEFAULT_MEMORY_KIB;
public static final int DEFAULT_PARALLELISM = Argon2Hash.DEFAULT_PARALLELISM;
public static final int DEFAULT_OUTPUT_LENGTH_BITS = Argon2Hash.DEFAULT_OUTPUT_LENGTH_BITS;
/**
* Parameter for modifying the internal algorithm used by Argon2.
*
* <p>Valid values are {@code argon2i} (optimized to resist side-channel attacks),
* {@code argon2d} (maximizes resistance to GPU cracking attacks)
* and {@code argon2id} (a hybrid version).</p>
*
* <p>The default value is {@value DEFAULT_ALGORITHM_NAME} when this parameter is not specified.</p>
*/
public static final String PARAMETER_ALGORITHM_NAME = "Argon2.algorithmName";
public static final String PARAMETER_ALGORITHM_VERSION = "Argon2.version";
/**
* The salt to use.
*
* <p>The value for this parameter accepts a Base64-encoded 16byte (128bit) salt.</p>
*
* <p>As for any KDF, do not use a static salt value for multiple passwords.</p>
*
* <p>The default value is a new random 128bit-salt, if this parameter is not specified.</p>
*/
public static final String PARAMETER_SALT = "Argon2.salt";
public static final String PARAMETER_ITERATIONS = "Argon2.iterations";
public static final String PARAMETER_MEMORY_KIB = "Argon2.memoryKib";
public static final String PARAMETER_PARALLELISM = "Argon2.parallelism";
/**
* The output length (in bits) of the resulting data section.
*
* <p>Argon2 allows to modify the length of the generated output.</p>
*
* <p>The default value is {@value DEFAULT_OUTPUT_LENGTH_BITS} when this parameter is not specified.</p>
*/
public static final String PARAMETER_OUTPUT_LENGTH_BITS = "Argon2.outputLength";
private Parameters() {
// utility class
}
}
}
| 8,808 | 0.650204 | 0.643392 | 207 | 41.550724 | 35.59306 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371981 | false | false |
10
|
41556acd4f10addfc4a24d18b3e36c7f143c8d1d
| 26,877,905,377,382 |
9e263c179d2b4b7861cb2bcbd6c971afe5f4272e
|
/src/com/li/java/FinallyAndReturn.java
|
1f4298f174e28da98a74e33dcbe3d03703e6253c
|
[] |
no_license
|
fjl121029xx/Arithmetic
|
https://github.com/fjl121029xx/Arithmetic
|
13981a2d0c465f6e78818224244be465eb4784db
|
12ff21c07998debcf5de4c1ad0b5455bd3d34e1d
|
refs/heads/master
| 2021-01-25T11:56:47.484000 | 2019-07-24T09:02:19 | 2019-07-24T09:02:19 | 123,446,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.li.java;
/**
* http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
*/
public class FinallyAndReturn {
public static void main(String[] args) {
System.out.println(test2());
}
public static String test11() {
try {
System.out.println("try block");
return test12();
} finally {
System.out.println("finally block");
}
}
public static String test12() {
System.out.println("return statement");
return "after return";
}
public static int test2() {
int b = 20;
try {
System.out.println("try block");
return b += 80;
} catch (Exception e) {
System.out.println("catch block");
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
return 200;
}
// return b;
}
public static int test3() {
int b = 20;
try {
System.out.println("try block");
return b += 80;
} catch (Exception e) {
System.out.println("catch block");
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
b = 150;
}
return 2000;
}
}
|
UTF-8
|
Java
| 1,441 |
java
|
FinallyAndReturn.java
|
Java
|
[
{
"context": "ckage com.li.java;\n\n/**\n * http://www.cnblogs.com/lanxuezaipiao/p/3440471.html\n */\npublic class FinallyAndReturn ",
"end": 65,
"score": 0.9997242093086243,
"start": 52,
"tag": "USERNAME",
"value": "lanxuezaipiao"
}
] | null |
[] |
package com.li.java;
/**
* http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
*/
public class FinallyAndReturn {
public static void main(String[] args) {
System.out.println(test2());
}
public static String test11() {
try {
System.out.println("try block");
return test12();
} finally {
System.out.println("finally block");
}
}
public static String test12() {
System.out.println("return statement");
return "after return";
}
public static int test2() {
int b = 20;
try {
System.out.println("try block");
return b += 80;
} catch (Exception e) {
System.out.println("catch block");
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
return 200;
}
// return b;
}
public static int test3() {
int b = 20;
try {
System.out.println("try block");
return b += 80;
} catch (Exception e) {
System.out.println("catch block");
} finally {
System.out.println("finally block");
if (b > 25) {
System.out.println("b>25, b = " + b);
}
b = 150;
}
return 2000;
}
}
| 1,441 | 0.460791 | 0.431645 | 77 | 17.714285 | 17.498688 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324675 | false | false |
10
|
dc8a4229fcc5e2073a78ca4f0fcffdf872003950
| 13,700,945,711,576 |
5f6bb5b7dc4a2039b831bb1be5207c1b861bc69c
|
/src/main/java/com/example/j2eeapp/services/CoursesService.java
|
718441d25b29c6026aaba15a10de3fe71115ab50
|
[] |
no_license
|
J2EEDEV-IMRAN/JAVAEE_digital_syllabus
|
https://github.com/J2EEDEV-IMRAN/JAVAEE_digital_syllabus
|
63b82976a001e9d3bd80fa7d8c0220979c08b092
|
d009d22c322e8f8fbe959b5eedf56242536fcc33
|
refs/heads/master
| 2021-06-16T08:18:41.569000 | 2017-04-28T09:42:07 | 2017-04-28T09:42:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.j2eeapp.services;
import java.util.List;
import javax.faces.model.SelectItem;
import com.example.j2eeapp.domain.CoursesEntity;
public interface CoursesService {
boolean createCourse(CoursesEntity coursesEntity,String name);
List<SelectItem> loadCredits();
List<SelectItem> loadcourseTypes();
List<SelectItem> loadCourseCreditHours();
List<SelectItem> loadCourseYear();
List<SelectItem> loadCourseTerm();
List<CoursesEntity> loadAllCourses();
boolean updateCourse(CoursesEntity coursesEntity);
void delteCourse(CoursesEntity entity);
List<CoursesEntity> loadFirstFCourses();
List<CoursesEntity> loadFirstSCourses();
List<CoursesEntity> loadSecondFCourses();
List<CoursesEntity> loadSecondSCourses();
List<CoursesEntity> loadThirdFCourses();
List<CoursesEntity> loadThirdSCourses();
List<CoursesEntity> loadFourthFCourses();
List<CoursesEntity> loadFourthSCourses();
List<CoursesEntity> loadLectureByCourse();
List<CoursesEntity> loadLabExamplesByCourse();
}
|
UTF-8
|
Java
| 1,010 |
java
|
CoursesService.java
|
Java
|
[] | null |
[] |
package com.example.j2eeapp.services;
import java.util.List;
import javax.faces.model.SelectItem;
import com.example.j2eeapp.domain.CoursesEntity;
public interface CoursesService {
boolean createCourse(CoursesEntity coursesEntity,String name);
List<SelectItem> loadCredits();
List<SelectItem> loadcourseTypes();
List<SelectItem> loadCourseCreditHours();
List<SelectItem> loadCourseYear();
List<SelectItem> loadCourseTerm();
List<CoursesEntity> loadAllCourses();
boolean updateCourse(CoursesEntity coursesEntity);
void delteCourse(CoursesEntity entity);
List<CoursesEntity> loadFirstFCourses();
List<CoursesEntity> loadFirstSCourses();
List<CoursesEntity> loadSecondFCourses();
List<CoursesEntity> loadSecondSCourses();
List<CoursesEntity> loadThirdFCourses();
List<CoursesEntity> loadThirdSCourses();
List<CoursesEntity> loadFourthFCourses();
List<CoursesEntity> loadFourthSCourses();
List<CoursesEntity> loadLectureByCourse();
List<CoursesEntity> loadLabExamplesByCourse();
}
| 1,010 | 0.805941 | 0.80396 | 34 | 28.705883 | 19.187204 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.411765 | false | false |
10
|
0f58d46822c9916ae8aab00173d4c63fbdbcb353
| 28,132,035,833,897 |
6461b1ce8cdb94ae0ccb53181adcc8997c5ec40f
|
/workspace/sources/library/programmertests/org/jwaresoftware/mwf4j/bal/SequenceActionTest.java
|
7834562f2d4b30888ef7be954edbb0c4592eb507
|
[] |
no_license
|
pvdung/mwf4j
|
https://github.com/pvdung/mwf4j
|
fc09bea2241765b2a625878216af73474ceeea1d
|
c4a4f3a9a3117909805b931d697dfa2fc80c8338
|
refs/heads/master
| 2021-01-23T12:25:28.128000 | 2011-05-22T02:56:40 | 2011-05-22T02:56:40 | 33,824,170 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* $Id$
@JAVA_SOURCE_HEADER@
**/
package org.jwaresoftware.mwf4j.bal;
import java.util.Deque;
import java.util.concurrent.Callable;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import org.jwaresoftware.gestalt.helpers.Pair;
import org.jwaresoftware.mwf4j.Action;
import org.jwaresoftware.mwf4j.Harness;
import org.jwaresoftware.mwf4j.MWf4JException;
import org.jwaresoftware.mwf4j.Sequence;
import org.jwaresoftware.mwf4j.scope.EnterLeaveScopeAction;
import org.jwaresoftware.mwf4j.starters.EpicFail;
import org.jwaresoftware.mwf4j.starters.FinishLaterAction;
import org.jwaresoftware.mwf4j.starters.TestStatement;
import org.jwaresoftware.mwf4j.starters.TouchAction;
import org.jwaresoftware.mwf4j.starters.UnknownAction;
/**
* Test suite for {@linkplain SequenceAction} and its associated statements.
* <p/>
* Note other statements+actions should always include a "as part of a sequence"
* and "as part of a heavily nested sequence" test case in their own suites.
* This suite (being at top o' pile) relies on simple echo and touch actions only.
* <p/>
* Note that we test the rewindablility of sequence thoroughly in the
* {@linkplain RewindAction rewind action} test suite to avoid the dependency
* on that action and others here.
*
* @since JWare/MWf4J 1.0.0
* @author ssmc, ©2010-2011 <a href="@Module_WEBSITE@">SSMC</a>
* @version @Module_VERSION@
* @.safety single
* @.group impl,test
**/
@Test(groups= {"mwf4j","baseline","bal"})
public final class SequenceActionTest extends ActionTestSkeleton
{
// ---------------------------------------------------------------------------------------
// Harness preparation methods
// ---------------------------------------------------------------------------------------
private SequenceAction newOUT(String id)
{
SequenceAction out = id==null ? new SequenceAction() : new SequenceAction(id);
out.setQuiet(false);
return out;
}
private SequenceAction newOUT()
{
return newOUT(null);
}
// ---------------------------------------------------------------------------------------
// The test cases (1 per method)
// ---------------------------------------------------------------------------------------
public void testEmptySequence_1_0_0()
{
Sequence out = newOUT();
assertTrue(out.isEmpty(),"isempty");
assertEquals(out.size(),0,"size");
assertNull(out.lastAdded(),"lastAdded");
newHARNESS(out).run();
}
public void testEmptySequenceCopyMode_1_0_0()
{
SequenceAction out = newOUT("empty");
out.setMode(SequenceAction.Mode.MULTIPLE);
newHARNESS(out).run();
assertTrue(out.isEmpty(),"isempty");
}
public void testSimpleSequenceOfEmptyStatements_1_0_0()
{
iniStatementCount();
Sequence out = newOUT();
out.add(new UnknownAction("1st",TestStatement.class));
out.add(new EmptyAction("2nd"));
assertTrue(out.lastAdded() instanceof EmptyAction,"lastAdded=empty");
out.add(new EmptyAction("3rd"));
out.add(new TouchAction("4th"));
assertTrue(out.lastAdded() instanceof TouchAction,"lastAdded=touch");
runTASK(out);
assertEquals(getStatementCount(),2,"calls to test statements");
assertTrue(wasPerformed("1st"),"1st performed");
assertTrue(wasPerformed("4th"),"4th performed");
}
/**
* Verify following ordering:<pre>
* i=[
* i.1,
* i.2=[ *EMPTY*
* ],
* i.3,
* i.4=[ *EMPTY*
* ],
* i.5,
* ]
* </pre>
*/
public void test1NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(touch("i.1"))
.add(newOUT("i.2"))
.add(touch("i.3"))
.add(newOUT("i.4"))
.add(touch("i.5"));
runTASK(out);
assertEquals(getStatementCount(),3,"calls to test statements");
assertTrue(werePerformedInOrder("i.1|i.3|i.5"),"ordering");
}
/**
* Verify following ordering:<pre>
* i=[
* i.1=[
* i.1.1
* ],
* i.2=[
* i.2.1
* ],
* i.3=[
* i.3.1
* ],
* i.4=[
* i.4.1
* ],
* i.5=[
* i.5.1
* ],
* ]
* </pre>
*/
public void test2NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(newOUT("i.1").add(touch("i.1.1")))
.add(newOUT("i.2").add(touch("i.2.1")))
.add(newOUT("i.3").add(touch("i.3.1")))
.add(newOUT("i.4").add(touch("i.4.1")))
.add(newOUT("i.5").add(touch("i.5.1")));
runTASK(out);
assertEquals(getStatementCount(),5,"calls to test statements");
assertTrue(werePerformedInOrder("i.1.1|i.2.1|i.3.1|i.4.1|i.5.1"),"ordering");
}
/**
* Verify following ordering: <pre>
* i=[
* i.1,
* i.2,
* i.3=[
* i.3.1
* ],
* i.4=[
* i.4.1,
* i.4.2,
* i.4.3=[
* i.4.3.1
* ],
* i.5,
* i.6=[
* i.6.1,
* i.6.2=[
* i.6.2.1,
* i.6.2.2=[
* i.6.2.2.1,
* i.6.2.2.2=[ *EMPTY*
* ]
* ],
* ],
* i.6.3
* ],
* i.7
* ]
* </pre>
*/
public void test3NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(touch("i.1"))
.add(touch("i.2"))
.add(newOUT("i.3").add(touch("i.3.1")))
.add(newOUT("i.4").add(touch("i.4.1")).add(touch("i.4.2")).add(newOUT("i.4.3").add(touch("i.4.3.1"))))
.add(touch("i.5"))
.add(newOUT("i.6").add(touch("i.6.1")).add(newOUT("i.6.2").add(touch("i.6.2.1")).add(newOUT("i.6.2.2").add(touch("i.6.2.2.1")).add(newOUT("i.6.2.2.2")))).add(touch("i.6.3")))
.add(touch("i.7"));
runTASK(out);
assertEquals(getStatementCount(),12,"calls to test statements");
assertTrue(werePerformedInOrder("i.1|i.2|i.3.1|i.4.1|i.4.2|i.4.3.1|i.5|i.6.1|i.6.2.1|i.6.2.2.1|i.6.3|i.7"),"ordering");
}
public void testMultiplePassesForSameAction_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("multipass");
out.setMode(SequenceAction.Mode.MULTIPLE);
out.add(new TouchAction("1st"));
newHARNESS(out).run();
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("1st"));
newHARNESS(out).run();
assertEquals(getStatementCount(),2,"calls to test statement");
assertTrue(wasPerformed("1st",2));
}
public void testTryEachHappyPath_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.setTryEach(true);
out.add(touch("touch")).add(new EmptyAction()).add(touch("touch"));
newHARNESS(out).run();
assertEquals(getStatementCount(),2,"calls to test statement");
assertTrue(wasPerformed("touch",2),"touch x2");
}
public void testTryEachAndNoHaltIfError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("tryall-nobarf");
out.setTryEach(true);
out.setHaltIfError(false);
out.add(new ThrowAction()).add(new TouchAction("after"));
runTASK(out);
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
}
@Test (expectedExceptions= {MWf4JException.class})
public void testTryEachButHaltIfError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("tryall-dobarf");
out.setTryEach(true);
out.add(new ThrowAction()).add(new TouchAction("after"));
try {
runTASK(out);
} finally {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
}
}
public void testContinueOnErrorHappyPath_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.setHaltIfError(false);
out.add(new EmptyAction()).add(new EmptyAction()).add(touch("end"));
runTASK(out);
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("end"),"end called");
}
public void testContinueOnError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("continu");
out.setHaltIfError(false);
out.add(new ThrowAction()).add(new EpicFail()).add(touch("after"));
runTASK(out);
assertEquals(getStatementCount(),0,"calls to test statement");
}
/**
* Verify following with try+halt flags setup: <pre>
* m=[(halt=Y)
* m.1,
* m.2=[ (halt=N,tryeach=N)
* m.2.1,
* m.2.2-*THROW*,
* *FAIL*
* ],
* m.3,
* m.4,
* m.5=[ (halt=N,tryeach=Y)
* m.5.1,
* m.5.2-*THROW*,
* m.5.3-*THROW*,
* m.5.4,
* m.5.5=[ (halt=Y)
* m.5.5.1-*THROW*,
* *FAIL*
* ],
* ],
* m.6,
* m.7
* ]
* </pre>
*/
public void testContinueOnError1NestedLevel_1_0_0()
{
iniStatementCount();
SequenceAction m2 = newOUT("m.2");
m2.setHaltIfError(false);
m2.add(touch("m.2.1")).add(new ThrowAction("m.2.2-ERR")).add(new EpicFail());
SequenceAction m5 = newOUT("m.5");
m5.setTryEach(true);
m5.setHaltIfError(false);
m5.add(touch("m.5.1")).add(error("m.5.2-ERR")).add(error("m.5.3-ERR")).add(touch("m.5.4"));
m5.add(newOUT("m.5.5").add(error("m.5.5.1-ERR")).add(new EpicFail()));
SequenceAction out = newOUT("m");
out.add(touch("m.1"));
out.add(m2);
out.add(touch("m.3"));
out.add(new EmptyAction("m.4"));
out.add(m5);
out.add(new FinishLaterAction("m.6"));
out.add(touch("m.7"));
runTASK(out);
assertEquals(getStatementCount(),6,"calls to test statement");
assertTrue(werePerformedInOrder("m.1|m.2.1|m.3|m.5.1|m.5.4|m.6|m.7"),"ordering");
}
@Test (expectedExceptions= {MWf4JException.class})
public void testUnwindPlainSequence_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.add(touch("before")).add(new ThrowAction("b-ERR")).add(new EpicFail());
try {
runTASK(out);
fail("Should not get past throw action");
} catch(MWf4JException Xpected) {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("before"),"touch before throw");
throw Xpected;
}
}
@Test (expectedExceptions= {RunFailedException.class})
public void testUnwindTryEachSequence_1_0_0()
{
iniStatementCount();
ThrowAction throWacka = new ThrowAction("a-ERR");
throWacka.setCause(new IllegalStateException("WhackaWhackoWhooWhoo"));
ThrowAction throPeeep = new ThrowAction("c-ERR");
throPeeep.setCause(new NumberFormatException("NoNoNoPeeeping"));
SequenceAction out = newOUT();
out.setTryEach(true);
out.setUseHaltContinuation(false);
out.add(throWacka).add(touch("after")).add(throPeeep);
try {
runTASK(out);
fail("Should not get past throw action");
} catch(RunFailedException Xpected) {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
Throwable firstX = Xpected.getCause();
assertTrue(firstX.getMessage().indexOf("WhooWhoo")>0,"right exception");
Deque<Throwable> thrown = Xpected.copyOfCauses();
assertEquals(thrown.size(),2,"num.causes");
assertSame(thrown.pop(),throWacka.getCause(),"1st = wacka");
assertSame(thrown.pop(),throPeeep.getCause(),"2nd = peeep");
throw Xpected;
}
}
/**
* Verify a set of nested sequence from multiple independent threads to
* ensure sequence scoping works as expected.<pre>
* !=[
* aaa
* {=bbb
* chk.aaa
* $=[
* %=[
* ccc
* $=[
* ddd
* chk.ddd
* ddd
* chk.ddd(2)
* ]
* chk.ccc
* chk.aaa
* ]
* bbb
* ccc
* chk.ccc(2)
* chk.bbb
* ]
* }
* chk.ddd
* chk.ccc
* chk.bbb
* ]
* </pre>
*/
public void testMultithreadedNestedScopes_1_0_0() throws Exception
{
//Just make some nested sequences that should work per-thread
Sequence ddd = newOUT("$").add(touch("ddd")).add(checkdone("ddd",1)).add(touch("ddd")).add(checkdone("ddd",2));
Sequence ccc = newOUT("%").add(touch("ccc")).add(ddd).add(checkdone("ccc")).add(checkdone("aaa"));
Sequence bbb = newOUT("$").add(ccc).add(touch("bbb")).add(touch("ccc")).add(checkdone("ccc",2)).add(checkdone("bbb"));
Pair<Action,Action> enterleave= EnterLeaveScopeAction.newPair("xxx");
final Sequence out = block("!").add(touch("aaa")).add(enterleave.get1()).add(checkdone("aaa"))
.add(bbb).add(enterleave.get2()).add(checkdone("ddd")).add(checkdone("ccc"))
.add(checkdone("bbb"));
Callable<Harness> harnessFactory = new Callable<Harness>() {
public Harness call() {
String tn = Thread.currentThread().getName();
return newHARNESS("main."+tn,out);
}
};
runTASK(harnessFactory,3L);
}
}
/* end-of-SequenceActionTest.java */
|
UTF-8
|
Java
| 14,231 |
java
|
SequenceActionTest.java
|
Java
|
[
{
"context": ".\n *\n * @since JWare/MWf4J 1.0.0\n * @author ssmc, ©2010-2011 <a href=\"@Module_WEBSITE@\">SSMC<",
"end": 1351,
"score": 0.9982272982597351,
"start": 1347,
"tag": "USERNAME",
"value": "ssmc"
}
] | null |
[] |
/**
* $Id$
@JAVA_SOURCE_HEADER@
**/
package org.jwaresoftware.mwf4j.bal;
import java.util.Deque;
import java.util.concurrent.Callable;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import org.jwaresoftware.gestalt.helpers.Pair;
import org.jwaresoftware.mwf4j.Action;
import org.jwaresoftware.mwf4j.Harness;
import org.jwaresoftware.mwf4j.MWf4JException;
import org.jwaresoftware.mwf4j.Sequence;
import org.jwaresoftware.mwf4j.scope.EnterLeaveScopeAction;
import org.jwaresoftware.mwf4j.starters.EpicFail;
import org.jwaresoftware.mwf4j.starters.FinishLaterAction;
import org.jwaresoftware.mwf4j.starters.TestStatement;
import org.jwaresoftware.mwf4j.starters.TouchAction;
import org.jwaresoftware.mwf4j.starters.UnknownAction;
/**
* Test suite for {@linkplain SequenceAction} and its associated statements.
* <p/>
* Note other statements+actions should always include a "as part of a sequence"
* and "as part of a heavily nested sequence" test case in their own suites.
* This suite (being at top o' pile) relies on simple echo and touch actions only.
* <p/>
* Note that we test the rewindablility of sequence thoroughly in the
* {@linkplain RewindAction rewind action} test suite to avoid the dependency
* on that action and others here.
*
* @since JWare/MWf4J 1.0.0
* @author ssmc, ©2010-2011 <a href="@Module_WEBSITE@">SSMC</a>
* @version @Module_VERSION@
* @.safety single
* @.group impl,test
**/
@Test(groups= {"mwf4j","baseline","bal"})
public final class SequenceActionTest extends ActionTestSkeleton
{
// ---------------------------------------------------------------------------------------
// Harness preparation methods
// ---------------------------------------------------------------------------------------
private SequenceAction newOUT(String id)
{
SequenceAction out = id==null ? new SequenceAction() : new SequenceAction(id);
out.setQuiet(false);
return out;
}
private SequenceAction newOUT()
{
return newOUT(null);
}
// ---------------------------------------------------------------------------------------
// The test cases (1 per method)
// ---------------------------------------------------------------------------------------
public void testEmptySequence_1_0_0()
{
Sequence out = newOUT();
assertTrue(out.isEmpty(),"isempty");
assertEquals(out.size(),0,"size");
assertNull(out.lastAdded(),"lastAdded");
newHARNESS(out).run();
}
public void testEmptySequenceCopyMode_1_0_0()
{
SequenceAction out = newOUT("empty");
out.setMode(SequenceAction.Mode.MULTIPLE);
newHARNESS(out).run();
assertTrue(out.isEmpty(),"isempty");
}
public void testSimpleSequenceOfEmptyStatements_1_0_0()
{
iniStatementCount();
Sequence out = newOUT();
out.add(new UnknownAction("1st",TestStatement.class));
out.add(new EmptyAction("2nd"));
assertTrue(out.lastAdded() instanceof EmptyAction,"lastAdded=empty");
out.add(new EmptyAction("3rd"));
out.add(new TouchAction("4th"));
assertTrue(out.lastAdded() instanceof TouchAction,"lastAdded=touch");
runTASK(out);
assertEquals(getStatementCount(),2,"calls to test statements");
assertTrue(wasPerformed("1st"),"1st performed");
assertTrue(wasPerformed("4th"),"4th performed");
}
/**
* Verify following ordering:<pre>
* i=[
* i.1,
* i.2=[ *EMPTY*
* ],
* i.3,
* i.4=[ *EMPTY*
* ],
* i.5,
* ]
* </pre>
*/
public void test1NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(touch("i.1"))
.add(newOUT("i.2"))
.add(touch("i.3"))
.add(newOUT("i.4"))
.add(touch("i.5"));
runTASK(out);
assertEquals(getStatementCount(),3,"calls to test statements");
assertTrue(werePerformedInOrder("i.1|i.3|i.5"),"ordering");
}
/**
* Verify following ordering:<pre>
* i=[
* i.1=[
* i.1.1
* ],
* i.2=[
* i.2.1
* ],
* i.3=[
* i.3.1
* ],
* i.4=[
* i.4.1
* ],
* i.5=[
* i.5.1
* ],
* ]
* </pre>
*/
public void test2NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(newOUT("i.1").add(touch("i.1.1")))
.add(newOUT("i.2").add(touch("i.2.1")))
.add(newOUT("i.3").add(touch("i.3.1")))
.add(newOUT("i.4").add(touch("i.4.1")))
.add(newOUT("i.5").add(touch("i.5.1")));
runTASK(out);
assertEquals(getStatementCount(),5,"calls to test statements");
assertTrue(werePerformedInOrder("i.1.1|i.2.1|i.3.1|i.4.1|i.5.1"),"ordering");
}
/**
* Verify following ordering: <pre>
* i=[
* i.1,
* i.2,
* i.3=[
* i.3.1
* ],
* i.4=[
* i.4.1,
* i.4.2,
* i.4.3=[
* i.4.3.1
* ],
* i.5,
* i.6=[
* i.6.1,
* i.6.2=[
* i.6.2.1,
* i.6.2.2=[
* i.6.2.2.1,
* i.6.2.2.2=[ *EMPTY*
* ]
* ],
* ],
* i.6.3
* ],
* i.7
* ]
* </pre>
*/
public void test3NestedLevel_1_0_0()
{
iniStatementCount();
Sequence out= newOUT("i");
out.add(touch("i.1"))
.add(touch("i.2"))
.add(newOUT("i.3").add(touch("i.3.1")))
.add(newOUT("i.4").add(touch("i.4.1")).add(touch("i.4.2")).add(newOUT("i.4.3").add(touch("i.4.3.1"))))
.add(touch("i.5"))
.add(newOUT("i.6").add(touch("i.6.1")).add(newOUT("i.6.2").add(touch("i.6.2.1")).add(newOUT("i.6.2.2").add(touch("i.6.2.2.1")).add(newOUT("i.6.2.2.2")))).add(touch("i.6.3")))
.add(touch("i.7"));
runTASK(out);
assertEquals(getStatementCount(),12,"calls to test statements");
assertTrue(werePerformedInOrder("i.1|i.2|i.3.1|i.4.1|i.4.2|i.4.3.1|i.5|i.6.1|i.6.2.1|i.6.2.2.1|i.6.3|i.7"),"ordering");
}
public void testMultiplePassesForSameAction_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("multipass");
out.setMode(SequenceAction.Mode.MULTIPLE);
out.add(new TouchAction("1st"));
newHARNESS(out).run();
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("1st"));
newHARNESS(out).run();
assertEquals(getStatementCount(),2,"calls to test statement");
assertTrue(wasPerformed("1st",2));
}
public void testTryEachHappyPath_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.setTryEach(true);
out.add(touch("touch")).add(new EmptyAction()).add(touch("touch"));
newHARNESS(out).run();
assertEquals(getStatementCount(),2,"calls to test statement");
assertTrue(wasPerformed("touch",2),"touch x2");
}
public void testTryEachAndNoHaltIfError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("tryall-nobarf");
out.setTryEach(true);
out.setHaltIfError(false);
out.add(new ThrowAction()).add(new TouchAction("after"));
runTASK(out);
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
}
@Test (expectedExceptions= {MWf4JException.class})
public void testTryEachButHaltIfError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("tryall-dobarf");
out.setTryEach(true);
out.add(new ThrowAction()).add(new TouchAction("after"));
try {
runTASK(out);
} finally {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
}
}
public void testContinueOnErrorHappyPath_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.setHaltIfError(false);
out.add(new EmptyAction()).add(new EmptyAction()).add(touch("end"));
runTASK(out);
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("end"),"end called");
}
public void testContinueOnError_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT("continu");
out.setHaltIfError(false);
out.add(new ThrowAction()).add(new EpicFail()).add(touch("after"));
runTASK(out);
assertEquals(getStatementCount(),0,"calls to test statement");
}
/**
* Verify following with try+halt flags setup: <pre>
* m=[(halt=Y)
* m.1,
* m.2=[ (halt=N,tryeach=N)
* m.2.1,
* m.2.2-*THROW*,
* *FAIL*
* ],
* m.3,
* m.4,
* m.5=[ (halt=N,tryeach=Y)
* m.5.1,
* m.5.2-*THROW*,
* m.5.3-*THROW*,
* m.5.4,
* m.5.5=[ (halt=Y)
* m.5.5.1-*THROW*,
* *FAIL*
* ],
* ],
* m.6,
* m.7
* ]
* </pre>
*/
public void testContinueOnError1NestedLevel_1_0_0()
{
iniStatementCount();
SequenceAction m2 = newOUT("m.2");
m2.setHaltIfError(false);
m2.add(touch("m.2.1")).add(new ThrowAction("m.2.2-ERR")).add(new EpicFail());
SequenceAction m5 = newOUT("m.5");
m5.setTryEach(true);
m5.setHaltIfError(false);
m5.add(touch("m.5.1")).add(error("m.5.2-ERR")).add(error("m.5.3-ERR")).add(touch("m.5.4"));
m5.add(newOUT("m.5.5").add(error("m.5.5.1-ERR")).add(new EpicFail()));
SequenceAction out = newOUT("m");
out.add(touch("m.1"));
out.add(m2);
out.add(touch("m.3"));
out.add(new EmptyAction("m.4"));
out.add(m5);
out.add(new FinishLaterAction("m.6"));
out.add(touch("m.7"));
runTASK(out);
assertEquals(getStatementCount(),6,"calls to test statement");
assertTrue(werePerformedInOrder("m.1|m.2.1|m.3|m.5.1|m.5.4|m.6|m.7"),"ordering");
}
@Test (expectedExceptions= {MWf4JException.class})
public void testUnwindPlainSequence_1_0_0()
{
iniStatementCount();
SequenceAction out = newOUT();
out.add(touch("before")).add(new ThrowAction("b-ERR")).add(new EpicFail());
try {
runTASK(out);
fail("Should not get past throw action");
} catch(MWf4JException Xpected) {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("before"),"touch before throw");
throw Xpected;
}
}
@Test (expectedExceptions= {RunFailedException.class})
public void testUnwindTryEachSequence_1_0_0()
{
iniStatementCount();
ThrowAction throWacka = new ThrowAction("a-ERR");
throWacka.setCause(new IllegalStateException("WhackaWhackoWhooWhoo"));
ThrowAction throPeeep = new ThrowAction("c-ERR");
throPeeep.setCause(new NumberFormatException("NoNoNoPeeeping"));
SequenceAction out = newOUT();
out.setTryEach(true);
out.setUseHaltContinuation(false);
out.add(throWacka).add(touch("after")).add(throPeeep);
try {
runTASK(out);
fail("Should not get past throw action");
} catch(RunFailedException Xpected) {
assertEquals(getStatementCount(),1,"calls to test statement");
assertTrue(wasPerformed("after"),"touch after throw");
Throwable firstX = Xpected.getCause();
assertTrue(firstX.getMessage().indexOf("WhooWhoo")>0,"right exception");
Deque<Throwable> thrown = Xpected.copyOfCauses();
assertEquals(thrown.size(),2,"num.causes");
assertSame(thrown.pop(),throWacka.getCause(),"1st = wacka");
assertSame(thrown.pop(),throPeeep.getCause(),"2nd = peeep");
throw Xpected;
}
}
/**
* Verify a set of nested sequence from multiple independent threads to
* ensure sequence scoping works as expected.<pre>
* !=[
* aaa
* {=bbb
* chk.aaa
* $=[
* %=[
* ccc
* $=[
* ddd
* chk.ddd
* ddd
* chk.ddd(2)
* ]
* chk.ccc
* chk.aaa
* ]
* bbb
* ccc
* chk.ccc(2)
* chk.bbb
* ]
* }
* chk.ddd
* chk.ccc
* chk.bbb
* ]
* </pre>
*/
public void testMultithreadedNestedScopes_1_0_0() throws Exception
{
//Just make some nested sequences that should work per-thread
Sequence ddd = newOUT("$").add(touch("ddd")).add(checkdone("ddd",1)).add(touch("ddd")).add(checkdone("ddd",2));
Sequence ccc = newOUT("%").add(touch("ccc")).add(ddd).add(checkdone("ccc")).add(checkdone("aaa"));
Sequence bbb = newOUT("$").add(ccc).add(touch("bbb")).add(touch("ccc")).add(checkdone("ccc",2)).add(checkdone("bbb"));
Pair<Action,Action> enterleave= EnterLeaveScopeAction.newPair("xxx");
final Sequence out = block("!").add(touch("aaa")).add(enterleave.get1()).add(checkdone("aaa"))
.add(bbb).add(enterleave.get2()).add(checkdone("ddd")).add(checkdone("ccc"))
.add(checkdone("bbb"));
Callable<Harness> harnessFactory = new Callable<Harness>() {
public Harness call() {
String tn = Thread.currentThread().getName();
return newHARNESS("main."+tn,out);
}
};
runTASK(harnessFactory,3L);
}
}
/* end-of-SequenceActionTest.java */
| 14,231 | 0.535451 | 0.511278 | 463 | 29.736502 | 27.082781 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62851 | false | false |
10
|
b1a940660eac7f5042de1141319b1891211569c8
| 28,132,035,836,893 |
66324fa715dca2414b65e3f26c295d513cd0be9c
|
/src/com/maria/dama2014/controller/TicketController.java
|
03d7694f5fe41da6dbadda2a2951b4cfd3a1d767
|
[] |
no_license
|
marikiya88/Dama2013
|
https://github.com/marikiya88/Dama2013
|
09a58d4d6441e9b8accecd44172282c93a934b89
|
f3d2039d82b9bf09ed5e2ed373e7b0de48c16554
|
refs/heads/master
| 2020-06-05T05:30:17.619000 | 2014-11-16T01:15:45 | 2014-11-16T01:15:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.maria.dama2014.controller;
import com.maria.dama2014.TicketEvents;
import com.maria.dama2014.TicketOptions;
import com.maria.dama2014.model.TicketModel;
import com.maria.dama2014.view.TicketView;
import java.awt.event.ActionEvent;
/**
*
* @author Maria
*/
public class TicketController {
public TicketController(TicketView ticketV, TicketModel ticketM) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void actionPerformed(ActionEvent actionEvent) {
// ver tipo de evento
if (actionEvent.getID() == TicketEvents.CHOICE.ordinal()) {
actionSelected(actionEvent.getActionCommand());
}
}
private void actionSelected(String actionCommand) {
if (actionCommand.equals(TicketOptions.ACEPTAR.toString())) {
System.out.println("Acepto ticket");
//aceptarTicket();
} else if (actionCommand.equals(TicketOptions.APARCAR.toString())) {
System.out.println("Aparco ticket");
//aparcarTicket()
} else if (actionCommand.equals(TicketOptions.BUSCAR_REF)) {
System.out.println("Voy a consultar el almacen");
//buscarRef()
} else if (actionCommand.equals(TicketOptions.BORRAR_LINEA)) {
//borrarLinea()
} else if (actionCommand.equals(TicketOptions.VALE)) {
//pagar con vale
} else if (actionCommand.equals(TicketOptions.CANCELAR)) {
//cancelarTicket();
}
}
}
|
UTF-8
|
Java
| 1,669 |
java
|
TicketController.java
|
Java
|
[
{
"context": "java.awt.event.ActionEvent;\r\n\r\n/**\r\n *\r\n * @author Maria\r\n */\r\npublic class TicketController {\r\n\r\n public",
"end": 382,
"score": 0.9284326434135437,
"start": 377,
"tag": "NAME",
"value": "Maria"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.maria.dama2014.controller;
import com.maria.dama2014.TicketEvents;
import com.maria.dama2014.TicketOptions;
import com.maria.dama2014.model.TicketModel;
import com.maria.dama2014.view.TicketView;
import java.awt.event.ActionEvent;
/**
*
* @author Maria
*/
public class TicketController {
public TicketController(TicketView ticketV, TicketModel ticketM) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void actionPerformed(ActionEvent actionEvent) {
// ver tipo de evento
if (actionEvent.getID() == TicketEvents.CHOICE.ordinal()) {
actionSelected(actionEvent.getActionCommand());
}
}
private void actionSelected(String actionCommand) {
if (actionCommand.equals(TicketOptions.ACEPTAR.toString())) {
System.out.println("Acepto ticket");
//aceptarTicket();
} else if (actionCommand.equals(TicketOptions.APARCAR.toString())) {
System.out.println("Aparco ticket");
//aparcarTicket()
} else if (actionCommand.equals(TicketOptions.BUSCAR_REF)) {
System.out.println("Voy a consultar el almacen");
//buscarRef()
} else if (actionCommand.equals(TicketOptions.BORRAR_LINEA)) {
//borrarLinea()
} else if (actionCommand.equals(TicketOptions.VALE)) {
//pagar con vale
} else if (actionCommand.equals(TicketOptions.CANCELAR)) {
//cancelarTicket();
}
}
}
| 1,669 | 0.638107 | 0.626123 | 50 | 31.379999 | 25.484026 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false |
10
|
2cc9d5b09b444356b225ee6e769fdc5a4f70a1f8
| 30,846,455,188,620 |
645b3bdc2e37f282c3e8c631a458b94901742b8d
|
/job-tracker-core/src/main/java/org/limbo/flowjob/tracker/core/storage/JobInstanceStorage.java
|
cdb5a1880f3e03e7ac29ee962a6d5bb116b759d6
|
[
"Apache-2.0"
] |
permissive
|
ExtremeYu/flow-job
|
https://github.com/ExtremeYu/flow-job
|
6beef48f499eedfc77f7410777dd1b04b2f247d3
|
2706b3dc3ea6e5b4442b6309ca326fcc03adc2a1
|
refs/heads/master
| 2023-07-15T15:49:53.469000 | 2021-08-30T11:10:50 | 2021-08-30T11:10:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.limbo.flowjob.tracker.core.storage;
import org.limbo.flowjob.tracker.core.job.context.JobInstance;
/**
* 作业贮藏所
*
* 1. 内存阻塞队列(磁盘) 起一个线程 监听 有任务就消费
* 2. redis 生产消费
* 3. DB 存 db后 消费者定时从DB获取
*
*
* 延迟是必然的,你没办法做到 比如 3:00:00 的任务 在3:00:00下发到worker执行
* 正常的操作来说,如果任务执行和时间有关的话,那应该是 将时间段作为参数传递过去,比如绩效的时候,我算哪天的
* 每秒一次的任务,也是如此。有两种方式:
* 1. 传递时间参数,比如 3:00:00 处理这一秒的数据
* 2. worker 获取当前时间来执行任务(这种就可能会有重复执行的情况,比如任务堆积或者任务排序后导致同时下发,那两个worker获取时间相同)
*
* @author Devil
* @since 2021/7/24
*/
public interface JobInstanceStorage {
/**
* 存储一个 job 实例
* @param instance 实例
*/
void store(JobInstance instance);
/**
* 取走一个 job 实例
* @return 实例
*/
JobInstance take();
}
|
UTF-8
|
Java
| 1,175 |
java
|
JobInstanceStorage.java
|
Java
|
[
{
"context": "比如任务堆积或者任务排序后导致同时下发,那两个worker获取时间相同)\n *\n * @author Devil\n * @since 2021/7/24\n */\npublic interface JobInsta",
"end": 473,
"score": 0.9944958090782166,
"start": 468,
"tag": "NAME",
"value": "Devil"
}
] | null |
[] |
package org.limbo.flowjob.tracker.core.storage;
import org.limbo.flowjob.tracker.core.job.context.JobInstance;
/**
* 作业贮藏所
*
* 1. 内存阻塞队列(磁盘) 起一个线程 监听 有任务就消费
* 2. redis 生产消费
* 3. DB 存 db后 消费者定时从DB获取
*
*
* 延迟是必然的,你没办法做到 比如 3:00:00 的任务 在3:00:00下发到worker执行
* 正常的操作来说,如果任务执行和时间有关的话,那应该是 将时间段作为参数传递过去,比如绩效的时候,我算哪天的
* 每秒一次的任务,也是如此。有两种方式:
* 1. 传递时间参数,比如 3:00:00 处理这一秒的数据
* 2. worker 获取当前时间来执行任务(这种就可能会有重复执行的情况,比如任务堆积或者任务排序后导致同时下发,那两个worker获取时间相同)
*
* @author Devil
* @since 2021/7/24
*/
public interface JobInstanceStorage {
/**
* 存储一个 job 实例
* @param instance 实例
*/
void store(JobInstance instance);
/**
* 取走一个 job 实例
* @return 实例
*/
JobInstance take();
}
| 1,175 | 0.666667 | 0.62901 | 36 | 18.916666 | 19.651653 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | false | false |
10
|
3257078e002d6824434476ee537e333a031ce9e8
| 16,569,983,858,252 |
a3f5f19df4ad5373b5d9edaf88a002ea26381f38
|
/api/src/test/java/com/budgeteer/api/controller/UserControllerTest.java
|
11f176e02711760c932f8e59654d90b36d906d18
|
[] |
no_license
|
EdotJ/crappybudget
|
https://github.com/EdotJ/crappybudget
|
c31432ad83e35c020e6115ef9b681ce15da541ab
|
efca0d81d8626651c583fc19b09427e2505825a0
|
refs/heads/main
| 2023-04-23T10:25:58.789000 | 2021-05-25T18:16:42 | 2021-05-25T18:16:42 | 335,727,967 | 1 | 0 | null | false | 2021-05-25T18:16:43 | 2021-02-03T19:09:55 | 2021-05-16T11:42:43 | 2021-05-25T18:16:43 | 1,128 | 0 | 0 | 0 |
Java
| false | false |
package com.budgeteer.api.controller;
import com.budgeteer.api.base.AuthenticationExtension;
import com.budgeteer.api.base.DatabaseCleanupExtension;
import com.budgeteer.api.base.TestUtils;
import com.budgeteer.api.dto.ErrorResponse;
import com.budgeteer.api.dto.user.SingleUserDto;
import com.budgeteer.api.dto.user.UserListDto;
import com.budgeteer.api.model.User;
import com.budgeteer.api.repository.UserRepository;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@MicronautTest
@ExtendWith(DatabaseCleanupExtension.class)
@Tag("Integration")
public class UserControllerTest {
@RegisterExtension
public AuthenticationExtension authExtension = new AuthenticationExtension();
@Inject
@Client(value = "/${api.base-path}", errorType = ErrorResponse.class)
private RxHttpClient client;
@Inject
private UserRepository repository;
private User testUser;
private User secondUser;
@BeforeEach
public void beforeEach() {
testUser = repository.save(TestUtils.createSecureTestUser());
secondUser = repository.save(TestUtils.createAdditionalTestUser());
}
@Test
public void shouldReturnListOfTwoUsers() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users").headers(authExtension.getAuthHeader());
HttpResponse<UserListDto> response = client.toBlocking().exchange(request, UserListDto.class);
assertEquals(HttpStatus.OK, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals(2, response.getBody().get().getCount());
}
@Test
public void shouldReturnSingleUser() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users/" + testUser.getId())
.headers(authExtension.getAuthHeader());
HttpResponse<SingleUserDto> response = client.toBlocking().exchange(request, SingleUserDto.class);
assertEquals(HttpStatus.OK, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals(TestUtils.TEST_USER_EMAIL, response.getBody().get().getEmail());
}
@Test
public void shouldCreateNewUser() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username2");
dto.setEmail("email2@gmail.com");
dto.setPassword("unsecurepassword");
HttpResponse<SingleUserDto> response = client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), SingleUserDto.class);
assertEquals(HttpStatus.CREATED, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
Optional<User> newUser = repository.findById(response.getBody().get().getId());
assertTrue(newUser.isPresent());
assertEquals(dto.getEmail(), newUser.get().getEmail());
assertEquals(dto.getUsername(), newUser.get().getUsername());
}
@Test
public void shouldUpdateUser() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("testuser");
dto.setEmail("email@gmail.com");
MutableHttpRequest<SingleUserDto> request = HttpRequest.PUT("/users/" + testUser.getId(), dto)
.headers(authExtension.getAuthHeader());
HttpResponse<SingleUserDto> response = client.toBlocking()
.exchange(request, SingleUserDto.class);
assertEquals(HttpStatus.OK, response.status());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals("username", response.getBody().get().getUsername());
assertEquals("email@gmail.com", response.getBody().get().getEmail());
}
@Test
public void shouldDeleteTestUser() {
MutableHttpRequest<Object> request = HttpRequest.DELETE("/users/" + testUser.getId())
.headers(authExtension.getAuthHeader());
HttpResponse<Object> response = client.toBlocking().exchange(request, Object.class);
assertEquals(HttpStatus.NO_CONTENT, response.getStatus());
List<User> users = repository.findAll();
assertEquals(1, users.size());
}
@Test
public void shouldFailEmailVerificationWithInvalidFormat() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("email@g");
dto.setPassword("unsecurepassword");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("format"));
assertTrue(errorResponse.getDetail().contains("Invalid email format"));
}
@Test
public void shouldFailEmailVerificationWithEmptyEmail() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("");
dto.setPassword("unsecurepassword");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getDetail().contains("empty"));
}
@Test
public void shouldFailPasswordVerification() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("email@gmail.com");
dto.setPassword("");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("PASSWORD_VALIDATION", errorResponse.getCode());
}
@Test
public void shouldFailUsernameVerification() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("");
dto.setEmail("email@go.com");
dto.setPassword("unsecurepassword");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_USERNAME", errorResponse.getCode());
assertTrue(errorResponse.getDetail().contains("empty"));
}
@Test
public void shouldFailWhenNotUniqueEmail() {
SingleUserDto dto = new SingleUserDto(TestUtils.createTestUser());
dto.setPassword("unsecuredpassword");
dto.setUsername("testytesterson");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class)
);
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("use"));
}
@Test
public void shouldFailWhenNotUniqueUsername() {
SingleUserDto dto = new SingleUserDto(TestUtils.createTestUser());
dto.setPassword("unsecuredpassword");
dto.setEmail("testytesterson@testy.com");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class)
);
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_USERNAME", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("use"));
}
@Test
public void shouldFailFetchingOtherUserInfo() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users/" + secondUser.getId())
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
@Test
public void shouldFailUpdatingOtherUserInfo() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("testuser");
dto.setEmail("email@gmail.com");
MutableHttpRequest<SingleUserDto> request = HttpRequest.PUT("/users/" + secondUser.getId(), dto)
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
@Test
public void shouldFailDeletingOtherUserInfo() {
MutableHttpRequest<Object> request = HttpRequest.DELETE("/users/" + secondUser.getId())
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
}
|
UTF-8
|
Java
| 11,406 |
java
|
UserControllerTest.java
|
Java
|
[
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"username2\");\n dto.setEmail(\"email2@gmail.com\");\n ",
"end": 2993,
"score": 0.9994326829910278,
"start": 2984,
"tag": "USERNAME",
"value": "username2"
},
{
"context": "o.setUsername(\"username2\");\n dto.setEmail(\"email2@gmail.com\");\n dto.setPassword(\"unsecurepassword\");\n ",
"end": 3035,
"score": 0.9999246597290039,
"start": 3019,
"tag": "EMAIL",
"value": "email2@gmail.com"
},
{
"context": "ail(\"email2@gmail.com\");\n dto.setPassword(\"unsecurepassword\");\n HttpResponse<SingleUserDto> response =",
"end": 3080,
"score": 0.9991695880889893,
"start": 3064,
"tag": "PASSWORD",
"value": "unsecurepassword"
},
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"testuser\");\n dto.setEmail(\"email@gmail.com\");\n ",
"end": 3787,
"score": 0.9995383024215698,
"start": 3779,
"tag": "USERNAME",
"value": "testuser"
},
{
"context": "to.setUsername(\"testuser\");\n dto.setEmail(\"email@gmail.com\");\n MutableHttpRequest<SingleUserDto> requ",
"end": 3828,
"score": 0.9999203681945801,
"start": 3813,
"tag": "EMAIL",
"value": "email@gmail.com"
},
{
"context": "nse.getBody().isPresent());\n assertEquals(\"username\", response.getBody().get().getUsername());\n ",
"end": 4294,
"score": 0.9005206227302551,
"start": 4286,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ody().get().getUsername());\n assertEquals(\"email@gmail.com\", response.getBody().get().getEmail());\n }\n\n ",
"end": 4375,
"score": 0.9999221563339233,
"start": 4360,
"tag": "EMAIL",
"value": "email@gmail.com"
},
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"username\");\n dto.setEmail(\"email@g\");\n dto.s",
"end": 5037,
"score": 0.9995915293693542,
"start": 5029,
"tag": "USERNAME",
"value": "username"
},
{
"context": "dto.setEmail(\"email@g\");\n dto.setPassword(\"unsecurepassword\");\n HttpClientResponseException e = assert",
"end": 5115,
"score": 0.999333381652832,
"start": 5099,
"tag": "PASSWORD",
"value": "unsecurepassword"
},
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"username\");\n dto.setEmail(\"\");\n dto.setPassw",
"end": 5955,
"score": 0.9995909333229065,
"start": 5947,
"tag": "USERNAME",
"value": "username"
},
{
"context": " dto.setEmail(\"\");\n dto.setPassword(\"unsecurepassword\");\n HttpClientResponseException e = assert",
"end": 6026,
"score": 0.9993411898612976,
"start": 6010,
"tag": "PASSWORD",
"value": "unsecurepassword"
},
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"username\");\n dto.setEmail(\"email@gmail.com\");\n ",
"end": 6772,
"score": 0.999546468257904,
"start": 6764,
"tag": "USERNAME",
"value": "username"
},
{
"context": "to.setUsername(\"username\");\n dto.setEmail(\"email@gmail.com\");\n dto.setPassword(\"\");\n HttpClien",
"end": 6813,
"score": 0.9999213218688965,
"start": 6798,
"tag": "EMAIL",
"value": "email@gmail.com"
},
{
"context": " dto.setUsername(\"\");\n dto.setEmail(\"email@go.com\");\n dto.setPassword(\"unsecurepassword\");\n ",
"end": 7564,
"score": 0.9999195337295532,
"start": 7552,
"tag": "EMAIL",
"value": "email@go.com"
},
{
"context": "etEmail(\"email@go.com\");\n dto.setPassword(\"unsecurepassword\");\n HttpClientResponseException e = assert",
"end": 7609,
"score": 0.9992987513542175,
"start": 7593,
"tag": "PASSWORD",
"value": "unsecurepassword"
},
{
"context": "Utils.createTestUser());\n dto.setPassword(\"unsecuredpassword\");\n dto.setUsername(\"testytesterson\");\n ",
"end": 8392,
"score": 0.9993366003036499,
"start": 8375,
"tag": "PASSWORD",
"value": "unsecuredpassword"
},
{
"context": "rd(\"unsecuredpassword\");\n dto.setUsername(\"testytesterson\");\n HttpClientResponseException e = assert",
"end": 8435,
"score": 0.9996578097343445,
"start": 8421,
"tag": "USERNAME",
"value": "testytesterson"
},
{
"context": "Utils.createTestUser());\n dto.setPassword(\"unsecuredpassword\");\n dto.setEmail(\"testytesterson@testy.com",
"end": 9225,
"score": 0.9993348121643066,
"start": 9208,
"tag": "PASSWORD",
"value": "unsecuredpassword"
},
{
"context": "sword(\"unsecuredpassword\");\n dto.setEmail(\"testytesterson@testy.com\");\n HttpClientResponseException e = assert",
"end": 9275,
"score": 0.9999307990074158,
"start": 9251,
"tag": "EMAIL",
"value": "testytesterson@testy.com"
},
{
"context": "o = new SingleUserDto();\n dto.setUsername(\"testuser\");\n dto.setEmail(\"email@gmail.com\");\n ",
"end": 10491,
"score": 0.9995743036270142,
"start": 10483,
"tag": "USERNAME",
"value": "testuser"
},
{
"context": "to.setUsername(\"testuser\");\n dto.setEmail(\"email@gmail.com\");\n MutableHttpRequest<SingleUserDto> requ",
"end": 10532,
"score": 0.999917209148407,
"start": 10517,
"tag": "EMAIL",
"value": "email@gmail.com"
}
] | null |
[] |
package com.budgeteer.api.controller;
import com.budgeteer.api.base.AuthenticationExtension;
import com.budgeteer.api.base.DatabaseCleanupExtension;
import com.budgeteer.api.base.TestUtils;
import com.budgeteer.api.dto.ErrorResponse;
import com.budgeteer.api.dto.user.SingleUserDto;
import com.budgeteer.api.dto.user.UserListDto;
import com.budgeteer.api.model.User;
import com.budgeteer.api.repository.UserRepository;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
@MicronautTest
@ExtendWith(DatabaseCleanupExtension.class)
@Tag("Integration")
public class UserControllerTest {
@RegisterExtension
public AuthenticationExtension authExtension = new AuthenticationExtension();
@Inject
@Client(value = "/${api.base-path}", errorType = ErrorResponse.class)
private RxHttpClient client;
@Inject
private UserRepository repository;
private User testUser;
private User secondUser;
@BeforeEach
public void beforeEach() {
testUser = repository.save(TestUtils.createSecureTestUser());
secondUser = repository.save(TestUtils.createAdditionalTestUser());
}
@Test
public void shouldReturnListOfTwoUsers() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users").headers(authExtension.getAuthHeader());
HttpResponse<UserListDto> response = client.toBlocking().exchange(request, UserListDto.class);
assertEquals(HttpStatus.OK, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals(2, response.getBody().get().getCount());
}
@Test
public void shouldReturnSingleUser() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users/" + testUser.getId())
.headers(authExtension.getAuthHeader());
HttpResponse<SingleUserDto> response = client.toBlocking().exchange(request, SingleUserDto.class);
assertEquals(HttpStatus.OK, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals(TestUtils.TEST_USER_EMAIL, response.getBody().get().getEmail());
}
@Test
public void shouldCreateNewUser() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username2");
dto.setEmail("<EMAIL>");
dto.setPassword("<PASSWORD>");
HttpResponse<SingleUserDto> response = client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), SingleUserDto.class);
assertEquals(HttpStatus.CREATED, response.getStatus());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
Optional<User> newUser = repository.findById(response.getBody().get().getId());
assertTrue(newUser.isPresent());
assertEquals(dto.getEmail(), newUser.get().getEmail());
assertEquals(dto.getUsername(), newUser.get().getUsername());
}
@Test
public void shouldUpdateUser() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("testuser");
dto.setEmail("<EMAIL>");
MutableHttpRequest<SingleUserDto> request = HttpRequest.PUT("/users/" + testUser.getId(), dto)
.headers(authExtension.getAuthHeader());
HttpResponse<SingleUserDto> response = client.toBlocking()
.exchange(request, SingleUserDto.class);
assertEquals(HttpStatus.OK, response.status());
assertNotNull(response.body());
assertTrue(response.getBody().isPresent());
assertEquals("username", response.getBody().get().getUsername());
assertEquals("<EMAIL>", response.getBody().get().getEmail());
}
@Test
public void shouldDeleteTestUser() {
MutableHttpRequest<Object> request = HttpRequest.DELETE("/users/" + testUser.getId())
.headers(authExtension.getAuthHeader());
HttpResponse<Object> response = client.toBlocking().exchange(request, Object.class);
assertEquals(HttpStatus.NO_CONTENT, response.getStatus());
List<User> users = repository.findAll();
assertEquals(1, users.size());
}
@Test
public void shouldFailEmailVerificationWithInvalidFormat() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("email@g");
dto.setPassword("<PASSWORD>");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("format"));
assertTrue(errorResponse.getDetail().contains("Invalid email format"));
}
@Test
public void shouldFailEmailVerificationWithEmptyEmail() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("");
dto.setPassword("<PASSWORD>");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getDetail().contains("empty"));
}
@Test
public void shouldFailPasswordVerification() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("username");
dto.setEmail("<EMAIL>");
dto.setPassword("");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("PASSWORD_VALIDATION", errorResponse.getCode());
}
@Test
public void shouldFailUsernameVerification() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("");
dto.setEmail("<EMAIL>");
dto.setPassword("<PASSWORD>");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () -> client.toBlocking()
.exchange(HttpRequest.POST("/users", dto), ErrorResponse.class));
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_USERNAME", errorResponse.getCode());
assertTrue(errorResponse.getDetail().contains("empty"));
}
@Test
public void shouldFailWhenNotUniqueEmail() {
SingleUserDto dto = new SingleUserDto(TestUtils.createTestUser());
dto.setPassword("<PASSWORD>");
dto.setUsername("testytesterson");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class)
);
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_EMAIL", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("use"));
}
@Test
public void shouldFailWhenNotUniqueUsername() {
SingleUserDto dto = new SingleUserDto(TestUtils.createTestUser());
dto.setPassword("<PASSWORD>");
dto.setEmail("<EMAIL>");
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(HttpRequest.POST("/users", dto), ErrorResponse.class)
);
assertEquals(HttpStatus.BAD_REQUEST, e.getResponse().status());
Optional<ErrorResponse> optionalError = e.getResponse().getBody(ErrorResponse.class);
assertTrue(optionalError.isPresent());
ErrorResponse errorResponse = optionalError.get();
assertEquals("BAD_USERNAME", errorResponse.getCode());
assertTrue(errorResponse.getMessage().contains("use"));
}
@Test
public void shouldFailFetchingOtherUserInfo() {
MutableHttpRequest<Object> request = HttpRequest.GET("/users/" + secondUser.getId())
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
@Test
public void shouldFailUpdatingOtherUserInfo() {
SingleUserDto dto = new SingleUserDto();
dto.setUsername("testuser");
dto.setEmail("<EMAIL>");
MutableHttpRequest<SingleUserDto> request = HttpRequest.PUT("/users/" + secondUser.getId(), dto)
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
@Test
public void shouldFailDeletingOtherUserInfo() {
MutableHttpRequest<Object> request = HttpRequest.DELETE("/users/" + secondUser.getId())
.headers(authExtension.getAuthHeader());
HttpClientResponseException e = assertThrows(HttpClientResponseException.class, () ->
client.toBlocking().exchange(request, ErrorResponse.class)
);
assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
}
}
| 11,305 | 0.694985 | 0.694547 | 248 | 44.991936 | 30.047407 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.83871 | false | false |
10
|
05a94a0c2d94a9613b3d42387e6914b9a58fd2e3
| 27,522,150,451,051 |
4e07d27227723880e7c74dc57624fa1f4ec9a0d1
|
/data/src/main/java/mx/gob/economia/inadem/entity/seguridad/Rol.java
|
a5d46d95281cde9694c6d55e213786af961b3f24
|
[] |
no_license
|
iamedu/oracle-vagrant
|
https://github.com/iamedu/oracle-vagrant
|
a565efb02401478ed9c64e32eb7ff2d94c64cd9b
|
9c1477135fb9ea4c56e53f90ae845dffec7832f7
|
refs/heads/master
| 2021-01-01T16:34:15.147000 | 2013-03-08T22:53:55 | 2013-03-08T22:53:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mx.gob.economia.inadem.entity.seguridad;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import mx.gob.economia.inadem.entity.catalogo.Catalogo;
@Entity
@Table(name="ROL")
public class Rol extends Catalogo {
private static final long serialVersionUID = 1L;
@ManyToMany(mappedBy="roles")
private List<Usuario> usuarios;
public List<Usuario> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
}
|
UTF-8
|
Java
| 589 |
java
|
Rol.java
|
Java
|
[] | null |
[] |
package mx.gob.economia.inadem.entity.seguridad;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import mx.gob.economia.inadem.entity.catalogo.Catalogo;
@Entity
@Table(name="ROL")
public class Rol extends Catalogo {
private static final long serialVersionUID = 1L;
@ManyToMany(mappedBy="roles")
private List<Usuario> usuarios;
public List<Usuario> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
}
| 589 | 0.731749 | 0.730051 | 28 | 19.035715 | 18.711117 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false |
10
|
3d53d6a69da40e4f855c332f7c3a06418d34369d
| 32,040,456,067,295 |
142dec7710969747cd31785a5afadf51a52964d6
|
/information-manager-system-web/src/main/java/com/xingkaichun/information/controller/HttpController.java
|
1c771243dcefb642a6cafec7c7d8dbe9cc5a40d8
|
[] |
no_license
|
wxtouot546/information-manager-system
|
https://github.com/wxtouot546/information-manager-system
|
8032a86d56043558c62d7067b5bbcf65915738d4
|
994ceb051e7b887b0758a0cd7ac5bb050af83013
|
refs/heads/master
| 2022-11-25T07:17:31.181000 | 2020-07-22T15:11:54 | 2020-07-22T15:11:54 | 281,709,682 | 0 | 0 | null | true | 2020-07-22T15:07:51 | 2020-07-22T15:07:50 | 2020-07-01T11:41:56 | 2020-06-29T14:23:10 | 22,247 | 0 | 0 | 0 | null | false | false |
package com.xingkaichun.information.controller;
import com.alibaba.fastjson.JSONObject;
import com.xingkaichun.common.dto.base.FreshServiceResult;
import com.xingkaichun.common.dto.base.ServiceResult;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
@Api(value="HttpController",tags={"请求转发"})
@Controller
@RequestMapping(value = "/Http")
public class HttpController {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpController.class);
@ResponseBody
@PostMapping("/POST")
public ServiceResult<JSONObject> Get2(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody JSONObject requestBody) {
try {
String body1 = requestBody.toString();
String forwardRequestUrl = httpServletRequest.getHeader("forwardRequestUrl");
String forwardRequestMethod = httpServletRequest.getHeader("forwardRequestMethod");
OutputStreamWriter out = null;
InputStream is = null;
try {
URL url = new URL(forwardRequestUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(forwardRequestMethod); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(body1);
out.flush();
out.close();
// 读取响应
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String contentType = connection.getHeaderField("content-type");
String result = new String(data, "UTF-8"); // utf-8编码
JSONObject resultJsonObject = JSONObject.parseObject(result);
return ServiceResult.createSuccessServiceResult("成功",resultJsonObject);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
return FreshServiceResult.createFailFreshServiceResult("失败");
}
return FreshServiceResult.createFailFreshServiceResult("失败");
}
}
|
UTF-8
|
Java
| 4,146 |
java
|
HttpController.java
|
Java
|
[] | null |
[] |
package com.xingkaichun.information.controller;
import com.alibaba.fastjson.JSONObject;
import com.xingkaichun.common.dto.base.FreshServiceResult;
import com.xingkaichun.common.dto.base.ServiceResult;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
@Api(value="HttpController",tags={"请求转发"})
@Controller
@RequestMapping(value = "/Http")
public class HttpController {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpController.class);
@ResponseBody
@PostMapping("/POST")
public ServiceResult<JSONObject> Get2(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody JSONObject requestBody) {
try {
String body1 = requestBody.toString();
String forwardRequestUrl = httpServletRequest.getHeader("forwardRequestUrl");
String forwardRequestMethod = httpServletRequest.getHeader("forwardRequestMethod");
OutputStreamWriter out = null;
InputStream is = null;
try {
URL url = new URL(forwardRequestUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(forwardRequestMethod); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
out.append(body1);
out.flush();
out.close();
// 读取响应
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String contentType = connection.getHeaderField("content-type");
String result = new String(data, "UTF-8"); // utf-8编码
JSONObject resultJsonObject = JSONObject.parseObject(result);
return ServiceResult.createSuccessServiceResult("成功",resultJsonObject);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
return FreshServiceResult.createFailFreshServiceResult("失败");
}
return FreshServiceResult.createFailFreshServiceResult("失败");
}
}
| 4,146 | 0.608255 | 0.603312 | 94 | 42.042553 | 28.258652 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.755319 | false | false |
10
|
24eb4e09650deec193b694470c79c127ae28ab0f
| 29,317,446,793,420 |
a8623b67dc4197eaac403eb2383aa3587ddd1175
|
/tensorflow-framework/src/main/java/org/tensorflow/framework/metrics/CategoricalCrossentropy.java
|
0390660de1b138f6afdcd20f1d75f0d35e8e4076
|
[
"Apache-2.0"
] |
permissive
|
saudet/tensorflow-java
|
https://github.com/saudet/tensorflow-java
|
eb2c1005fb2a75b40d5c3e95b7da30021a9750d4
|
825e5014eeb4aaac2a0097e2cb1fa4f5914f6e02
|
refs/heads/master
| 2022-06-03T15:01:12.124000 | 2022-03-29T13:33:26 | 2022-03-29T13:33:41 | 210,991,539 | 6 | 2 |
Apache-2.0
| true | 2020-04-28T03:44:29 | 2019-09-26T03:27:37 | 2020-04-16T07:01:12 | 2020-04-28T03:44:28 | 7,916 | 0 | 0 | 0 |
Java
| false | false |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.framework.metrics;
import static org.tensorflow.framework.utils.CastHelper.cast;
import org.tensorflow.Graph;
import org.tensorflow.Operand;
import org.tensorflow.framework.losses.Losses;
import org.tensorflow.framework.metrics.impl.LossMetric;
import org.tensorflow.framework.metrics.impl.MeanBaseMetricWrapper;
import org.tensorflow.op.Ops;
import org.tensorflow.types.family.TNumber;
/**
* A Metric that computes the categorical cross-entropy loss between true labels and predicted
* labels.
*
* <p>This is the crossentropy metric class to be used when there are multiple label classes (2 or
* more). The labels should be given as a one_hot representation. eg., When labels values are {@code
* [2, 0, 1]}, the labels Operand contains = {@code [[0, 0, 1], [1, 0, 0], [0, 1, 0]] }.
*
* @param <T> The data type for the metric result
*/
public class CategoricalCrossentropy<T extends TNumber> extends MeanBaseMetricWrapper<T>
implements LossMetric {
private final boolean fromLogits;
private final float labelSmoothing;
private final int axis;
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions using {@link Class#getSimpleName()} for the metric name
*
* <p>Uses a {@link Losses#CHANNELS_LAST} for the channel axis.
*
* @param fromLogits Whether to interpret predictions as a tensor of logit values oras opposed to
* a probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
boolean fromLogits, float labelSmoothing, long seed, Class<T> type) {
this(null, fromLogits, labelSmoothing, Losses.CHANNELS_LAST, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions using {@link Class#getSimpleName()} for the metric name.
*
* @param fromLogits Whether to interpret predictions as a tensor of logit values as opposed to a
* probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param axis Int specifying the channels axis. {@code axis={@link Losses#CHANNELS_LAST}}
* corresponds to data format {@code channels_last}, and {@code axis={@link
* Losses#CHANNELS_FIRST}} corresponds to data format {@code channels_first}.
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
boolean fromLogits, float labelSmoothing, int axis, long seed, Class<T> type) {
this(null, fromLogits, labelSmoothing, axis, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions.
*
* <p>Uses a {@link Losses#CHANNELS_LAST} for the channel axis.
*
* @param name the name of this metric, if null then metric name is {@link Class#getSimpleName()}.
* @param fromLogits Whether to interpret predictions as a tensor of logit values oras opposed to
* a probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
String name, boolean fromLogits, float labelSmoothing, long seed, Class<T> type) {
this(name, fromLogits, labelSmoothing, Losses.CHANNELS_LAST, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions.
*
* @param name the name of this metric, if null then metric name is {@link Class#getSimpleName()}.
* @param fromLogits Whether to interpret predictions as a tensor of logit values as opposed to a
* probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param axis Int specifying the channels axis. {@code axis={@link Losses#CHANNELS_LAST}}
* corresponds to data format {@code channels_last}, and {@code axis={@link
* Losses#CHANNELS_FIRST}} corresponds to data format {@code channels_first}.
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
String name, boolean fromLogits, float labelSmoothing, int axis, long seed, Class<T> type) {
super(name, seed, type);
setLoss(this);
this.fromLogits = fromLogits;
this.labelSmoothing = labelSmoothing;
this.axis = axis;
}
/**
* Computes the crossentropy loss between the labels and predictions.
*
* @param tf the TensorFlow Ops encapsulating a {@link Graph} environment.
* @param labels the truth values or labels, of one-hot true targets, same shape as predictions
* @param predictions the predictions
* @throws IllegalArgumentException if the TensorFlow Ops scope does not encapsulate a Graph
* environment.
* @return Categorical crossentropy loss value.
*/
@Override
public <U extends TNumber> Operand<U> call(
Ops tf,
Operand<? extends TNumber> labels,
Operand<? extends TNumber> predictions,
Class<U> resultType) {
init(tf);
Operand<U> tLabels = cast(tf, labels, resultType);
Operand<U> tPredictions = cast(tf, predictions, resultType);
return Losses.categoricalCrossentropy(
tf, tLabels, tPredictions, fromLogits, labelSmoothing, axis);
}
}
|
UTF-8
|
Java
| 7,807 |
java
|
CategoricalCrossentropy.java
|
Java
|
[] | null |
[] |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.framework.metrics;
import static org.tensorflow.framework.utils.CastHelper.cast;
import org.tensorflow.Graph;
import org.tensorflow.Operand;
import org.tensorflow.framework.losses.Losses;
import org.tensorflow.framework.metrics.impl.LossMetric;
import org.tensorflow.framework.metrics.impl.MeanBaseMetricWrapper;
import org.tensorflow.op.Ops;
import org.tensorflow.types.family.TNumber;
/**
* A Metric that computes the categorical cross-entropy loss between true labels and predicted
* labels.
*
* <p>This is the crossentropy metric class to be used when there are multiple label classes (2 or
* more). The labels should be given as a one_hot representation. eg., When labels values are {@code
* [2, 0, 1]}, the labels Operand contains = {@code [[0, 0, 1], [1, 0, 0], [0, 1, 0]] }.
*
* @param <T> The data type for the metric result
*/
public class CategoricalCrossentropy<T extends TNumber> extends MeanBaseMetricWrapper<T>
implements LossMetric {
private final boolean fromLogits;
private final float labelSmoothing;
private final int axis;
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions using {@link Class#getSimpleName()} for the metric name
*
* <p>Uses a {@link Losses#CHANNELS_LAST} for the channel axis.
*
* @param fromLogits Whether to interpret predictions as a tensor of logit values oras opposed to
* a probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
boolean fromLogits, float labelSmoothing, long seed, Class<T> type) {
this(null, fromLogits, labelSmoothing, Losses.CHANNELS_LAST, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions using {@link Class#getSimpleName()} for the metric name.
*
* @param fromLogits Whether to interpret predictions as a tensor of logit values as opposed to a
* probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param axis Int specifying the channels axis. {@code axis={@link Losses#CHANNELS_LAST}}
* corresponds to data format {@code channels_last}, and {@code axis={@link
* Losses#CHANNELS_FIRST}} corresponds to data format {@code channels_first}.
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
boolean fromLogits, float labelSmoothing, int axis, long seed, Class<T> type) {
this(null, fromLogits, labelSmoothing, axis, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions.
*
* <p>Uses a {@link Losses#CHANNELS_LAST} for the channel axis.
*
* @param name the name of this metric, if null then metric name is {@link Class#getSimpleName()}.
* @param fromLogits Whether to interpret predictions as a tensor of logit values oras opposed to
* a probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
String name, boolean fromLogits, float labelSmoothing, long seed, Class<T> type) {
this(name, fromLogits, labelSmoothing, Losses.CHANNELS_LAST, seed, type);
}
/**
* Creates a CategoricalCrossentropy metric that computes the crossentropy metric between the
* labels and predictions.
*
* @param name the name of this metric, if null then metric name is {@link Class#getSimpleName()}.
* @param fromLogits Whether to interpret predictions as a tensor of logit values as opposed to a
* probability distribution.
* @param labelSmoothing value used to smooth labels, When > 0, label values are smoothed,
* meaning the confidence on label values are relaxed. e.g. {@code labelSmoothing=0.2} means
* that we will use a value of {@code 0.1} for label {@code 0} and {@code 0.9 } for label
* {@code 1}
* @param axis Int specifying the channels axis. {@code axis={@link Losses#CHANNELS_LAST}}
* corresponds to data format {@code channels_last}, and {@code axis={@link
* Losses#CHANNELS_FIRST}} corresponds to data format {@code channels_first}.
* @param seed the seed for random number generation. An initializer created with a given seed
* will always produce the same random tensor for a given shape and data type.
* @param type the type for the variables and result
*/
public CategoricalCrossentropy(
String name, boolean fromLogits, float labelSmoothing, int axis, long seed, Class<T> type) {
super(name, seed, type);
setLoss(this);
this.fromLogits = fromLogits;
this.labelSmoothing = labelSmoothing;
this.axis = axis;
}
/**
* Computes the crossentropy loss between the labels and predictions.
*
* @param tf the TensorFlow Ops encapsulating a {@link Graph} environment.
* @param labels the truth values or labels, of one-hot true targets, same shape as predictions
* @param predictions the predictions
* @throws IllegalArgumentException if the TensorFlow Ops scope does not encapsulate a Graph
* environment.
* @return Categorical crossentropy loss value.
*/
@Override
public <U extends TNumber> Operand<U> call(
Ops tf,
Operand<? extends TNumber> labels,
Operand<? extends TNumber> predictions,
Class<U> resultType) {
init(tf);
Operand<U> tLabels = cast(tf, labels, resultType);
Operand<U> tPredictions = cast(tf, predictions, resultType);
return Losses.categoricalCrossentropy(
tf, tLabels, tPredictions, fromLogits, labelSmoothing, axis);
}
}
| 7,807 | 0.71295 | 0.705649 | 157 | 48.726116 | 35.932102 | 100 | false | false | 0 | 0 | 0 | 0 | 72 | 0.009222 | 0.687898 | false | false |
10
|
73adba7a811abfa54e4972c5d48c67d5baf33ad9
| 19,988,777,849,722 |
32b4c6cfe6d4c5c86e867ea7ec04138ce39605cf
|
/Task9/test/com/epam/Roman_Riznyk/controller/RegistrationServletTest.java
|
22a8fe626ccb4f9a9595dd647d21d10c2f13e4db
|
[] |
no_license
|
rromank/EPAM
|
https://github.com/rromank/EPAM
|
d3cea4352b7b431e7f71c99ad32ee13ec6999046
|
929b1c0f1b7ee490a32a5071c5fe825050bf095c
|
refs/heads/master
| 2016-08-08T14:13:36.086000 | 2014-12-22T07:43:09 | 2014-12-22T07:43:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.epam.Roman_Riznyk.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.epam.Roman_Riznyk.avatar.AvatarService;
import com.epam.Roman_Riznyk.captcha.Captcha;
import com.epam.Roman_Riznyk.captcha.exception.CaptchaStoreException;
import com.epam.Roman_Riznyk.captcha.service.CaptchaProvider;
import com.epam.Roman_Riznyk.db.exception.ElementAlreadyExistsException;
import com.epam.Roman_Riznyk.db.exception.PersistException;
import com.epam.Roman_Riznyk.model.User;
import com.epam.Roman_Riznyk.service.UserService;
@SuppressWarnings({ "unchecked", "rawtypes" })
@RunWith(MockitoJUnitRunner.class)
public class RegistrationServletTest {
@InjectMocks
private RegistrationServlet servlet;
@Mock
private CaptchaProvider captchaProvider;
@Mock
private UserService userService;
@Mock
private AvatarService avatarService;
private ServletConfig servletConfig;
private HttpServletRequest request;
private HttpServletResponse response;
private Captcha captcha;
private static final String EMAIL = "email@mail.ru";
private static final String CAPTCHA_STRING = "123456";
@Before
public void setUp() throws ServletException, IOException,
CaptchaStoreException {
MockitoAnnotations.initMocks(this);
avatarService = getMockedAvatarService();
servletConfig = getMocketServletConfig();
request = getMockedRequest();
response = getMockedResponse();
captcha = getMockedCaptcha();
mockUserService();
mockCaptchaProvider();
}
private AvatarService getMockedAvatarService() {
AvatarService avatarService = mock(AvatarService.class);
return avatarService;
}
private ServletConfig getMocketServletConfig() {
ServletConfig servletConfig = mock(ServletConfig.class);
ServletContext appContext = mock(ServletContext.class);
when(servletConfig.getServletContext()).thenReturn(appContext);
when(appContext.getAttribute(Mockito.eq(Parameter.USER_SERVICE)))
.thenReturn(userService);
when(appContext.getAttribute(Mockito.eq(Parameter.CAPTCHA_PROVIDER)))
.thenReturn(captchaProvider);
when(appContext.getAttribute(Mockito.eq(Parameter.AVATAR_SERVICE)))
.thenReturn(avatarService);
return servletConfig;
}
private HttpServletRequest getMockedRequest() throws ServletException,
IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
RequestDispatcher requestDispatcher = mock(RequestDispatcher.class);
when(request.getParameter("captcha")).thenReturn(CAPTCHA_STRING);
when(request.getRequestDispatcher(anyString())).thenReturn(
requestDispatcher);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return null;
}
}).when(requestDispatcher).forward(request, response);
Part part = mock(Part.class);
when(part.getSize()).thenReturn(100L);
when(request.getPart(anyString())).thenReturn(part);
return request;
}
private HttpServletResponse getMockedResponse() {
HttpServletResponse response = mock(HttpServletResponse.class);
return response;
}
private Captcha getMockedCaptcha() {
Captcha capcha = mock(Captcha.class);
when(capcha.isCorrect(Mockito.eq(CAPTCHA_STRING))).thenReturn(true);
return capcha;
}
private void mockCaptchaProvider() throws CaptchaStoreException {
when(captchaProvider.getCaptcha(request)).thenReturn(captcha);
}
private void mockUserService() {
when(userService.isUserAlreadyRegistered(EMAIL)).thenReturn(true);
}
private void initNewUserBean() {
when(request.getParameter("first_name")).thenReturn("userFirstName");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn("new@mail.ru");
when(request.getParameter("password")).thenReturn("somePassword");
when(request.getParameter("password_confirmation")).thenReturn(
"somePassword");
}
private void initValidFormBean() {
when(request.getParameter("first_name")).thenReturn("userFirstName");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn(EMAIL);
when(request.getParameter("password")).thenReturn("somePassword");
when(request.getParameter("password_confirmation")).thenReturn(
"somePassword");
}
private void initInvalidUserNameFormBean() {
when(request.getParameter("first_name")).thenReturn("us");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn(EMAIL);
when(request.getParameter("password")).thenReturn("somePassword");
when(request.getParameter("password_confirmation")).thenReturn(
"somePassword");
}
@Test
public void testCaptchaProviderDeletesExpired() throws ServletException,
IOException {
servlet.doGet(request, response);
Mockito.verify(captchaProvider).deleteExpired(request);
}
@Test
public void testIncorrectUserName() throws ServletException, IOException {
initInvalidUserNameFormBean();
servlet.doPost(request, response);
ArgumentCaptor<Map> argument = ArgumentCaptor.forClass(Map.class);
Mockito.verify(request).setAttribute(Mockito.eq("validation"),
argument.capture());
Map<String, String> map = (Map<String, String>) argument.getValue();
String key = "firstName";
assertTrue(map.containsKey(key));
}
@Test
public void testUserAlreadyRegistered() throws ServletException,
IOException {
initValidFormBean();
servlet.doPost(request, response);
ArgumentCaptor<Boolean> argument = ArgumentCaptor
.forClass(Boolean.class);
Mockito.verify(request).setAttribute(Mockito.eq("alreadyRegistered"),
argument.capture());
boolean isRegistered = argument.getValue();
boolean expected = true;
assertEquals(expected, isRegistered);
}
@Test
public void testCaptchaIncorrect() throws ServletException, IOException {
initValidFormBean();
when(request.getParameter("captcha")).thenReturn("wrong");
servlet.doPost(request, response);
ArgumentCaptor<Boolean> argument = ArgumentCaptor
.forClass(Boolean.class);
Mockito.verify(request).setAttribute(Mockito.eq("invalidCaptcha"),
argument.capture());
boolean invalidCaptcha = argument.getValue();
boolean expected = true;
assertEquals(expected, invalidCaptcha);
}
@Test
public void testSuccessRegisterUser() throws IllegalAccessException,
ServletException, IOException, ElementAlreadyExistsException,
PersistException {
initValidFormBean();
when(request.getParameter("email")).thenReturn("new@mail.ru");
servlet.doPost(request, response);
Mockito.verify(userService).addUser(any(User.class));
}
@Test
public void testAvatarStored() throws ServletException, IOException {
initNewUserBean();
servlet.init(servletConfig);
servlet.doPost(request, response);
Mockito.verify(avatarService).store(any(Part.class), anyString());
}
@Test
public void testAvatarDeletedIfError() throws ServletException, IOException {
initNewUserBean();
Mockito.doThrow(ElementAlreadyExistsException.class).when(userService)
.addUser(any(User.class));
servlet.init(servletConfig);
servlet.doPost(request, response);
Mockito.verify(avatarService).remove(anyString());
}
}
|
UTF-8
|
Java
| 8,135 |
java
|
RegistrationServletTest.java
|
Java
|
[
{
"context": "a captcha;\n\n\tprivate static final String EMAIL = \"email@mail.ru\";\n\tprivate static final String CAPTCHA_STRING = \"",
"end": 1998,
"score": 0.9999200105667114,
"start": 1985,
"tag": "EMAIL",
"value": "email@mail.ru"
},
{
"context": "\t\twhen(request.getParameter(\"email\")).thenReturn(\"new@mail.ru\");\n\t\twhen(request.getParameter(\"password\")).thenR",
"end": 4650,
"score": 0.9999157190322876,
"start": 4639,
"tag": "EMAIL",
"value": "new@mail.ru"
},
{
"context": "hen(request.getParameter(\"password\")).thenReturn(\"somePassword\");\n\t\twhen(request.getParameter(\"password_confirma",
"end": 4719,
"score": 0.9994034171104431,
"start": 4707,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "ameter(\"password_confirmation\")).thenReturn(\n\t\t\t\t\"somePassword\");\n\t}\n\n\tprivate void initValidFormBean() {\n\t\twhen",
"end": 4806,
"score": 0.9993450045585632,
"start": 4794,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "hen(request.getParameter(\"password\")).thenReturn(\"somePassword\");\n\t\twhen(request.getParameter(\"password_confirma",
"end": 5114,
"score": 0.9994205236434937,
"start": 5102,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "ameter(\"password_confirmation\")).thenReturn(\n\t\t\t\t\"somePassword\");\n\t}\n\n\tprivate void initInvalidUserNameFormBean(",
"end": 5201,
"score": 0.9992903470993042,
"start": 5189,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "hen(request.getParameter(\"password\")).thenReturn(\"somePassword\");\n\t\twhen(request.getParameter(\"password_confirma",
"end": 5508,
"score": 0.9994323253631592,
"start": 5496,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "ameter(\"password_confirmation\")).thenReturn(\n\t\t\t\t\"somePassword\");\n\t}\n\n\t@Test\n\tpublic void testCaptchaProviderDel",
"end": 5595,
"score": 0.9992944002151489,
"start": 5583,
"tag": "PASSWORD",
"value": "somePassword"
},
{
"context": "g, String>) argument.getValue();\n\n\t\tString key = \"firstName\";\n\t\tassertTrue(map.containsKey(key));\n\t}\n\n\t@Test\n",
"end": 6210,
"score": 0.9924665093421936,
"start": 6201,
"tag": "KEY",
"value": "firstName"
},
{
"context": "\t\twhen(request.getParameter(\"email\")).thenReturn(\"new@mail.ru\");\n\t\tservlet.doPost(request, response);\n\n\t\tMockit",
"end": 7451,
"score": 0.9999154806137085,
"start": 7440,
"tag": "EMAIL",
"value": "new@mail.ru"
}
] | null |
[] |
package com.epam.Roman_Riznyk.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.epam.Roman_Riznyk.avatar.AvatarService;
import com.epam.Roman_Riznyk.captcha.Captcha;
import com.epam.Roman_Riznyk.captcha.exception.CaptchaStoreException;
import com.epam.Roman_Riznyk.captcha.service.CaptchaProvider;
import com.epam.Roman_Riznyk.db.exception.ElementAlreadyExistsException;
import com.epam.Roman_Riznyk.db.exception.PersistException;
import com.epam.Roman_Riznyk.model.User;
import com.epam.Roman_Riznyk.service.UserService;
@SuppressWarnings({ "unchecked", "rawtypes" })
@RunWith(MockitoJUnitRunner.class)
public class RegistrationServletTest {
@InjectMocks
private RegistrationServlet servlet;
@Mock
private CaptchaProvider captchaProvider;
@Mock
private UserService userService;
@Mock
private AvatarService avatarService;
private ServletConfig servletConfig;
private HttpServletRequest request;
private HttpServletResponse response;
private Captcha captcha;
private static final String EMAIL = "<EMAIL>";
private static final String CAPTCHA_STRING = "123456";
@Before
public void setUp() throws ServletException, IOException,
CaptchaStoreException {
MockitoAnnotations.initMocks(this);
avatarService = getMockedAvatarService();
servletConfig = getMocketServletConfig();
request = getMockedRequest();
response = getMockedResponse();
captcha = getMockedCaptcha();
mockUserService();
mockCaptchaProvider();
}
private AvatarService getMockedAvatarService() {
AvatarService avatarService = mock(AvatarService.class);
return avatarService;
}
private ServletConfig getMocketServletConfig() {
ServletConfig servletConfig = mock(ServletConfig.class);
ServletContext appContext = mock(ServletContext.class);
when(servletConfig.getServletContext()).thenReturn(appContext);
when(appContext.getAttribute(Mockito.eq(Parameter.USER_SERVICE)))
.thenReturn(userService);
when(appContext.getAttribute(Mockito.eq(Parameter.CAPTCHA_PROVIDER)))
.thenReturn(captchaProvider);
when(appContext.getAttribute(Mockito.eq(Parameter.AVATAR_SERVICE)))
.thenReturn(avatarService);
return servletConfig;
}
private HttpServletRequest getMockedRequest() throws ServletException,
IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
RequestDispatcher requestDispatcher = mock(RequestDispatcher.class);
when(request.getParameter("captcha")).thenReturn(CAPTCHA_STRING);
when(request.getRequestDispatcher(anyString())).thenReturn(
requestDispatcher);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return null;
}
}).when(requestDispatcher).forward(request, response);
Part part = mock(Part.class);
when(part.getSize()).thenReturn(100L);
when(request.getPart(anyString())).thenReturn(part);
return request;
}
private HttpServletResponse getMockedResponse() {
HttpServletResponse response = mock(HttpServletResponse.class);
return response;
}
private Captcha getMockedCaptcha() {
Captcha capcha = mock(Captcha.class);
when(capcha.isCorrect(Mockito.eq(CAPTCHA_STRING))).thenReturn(true);
return capcha;
}
private void mockCaptchaProvider() throws CaptchaStoreException {
when(captchaProvider.getCaptcha(request)).thenReturn(captcha);
}
private void mockUserService() {
when(userService.isUserAlreadyRegistered(EMAIL)).thenReturn(true);
}
private void initNewUserBean() {
when(request.getParameter("first_name")).thenReturn("userFirstName");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn("<EMAIL>");
when(request.getParameter("password")).thenReturn("<PASSWORD>");
when(request.getParameter("password_confirmation")).thenReturn(
"<PASSWORD>");
}
private void initValidFormBean() {
when(request.getParameter("first_name")).thenReturn("userFirstName");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn(EMAIL);
when(request.getParameter("password")).thenReturn("<PASSWORD>");
when(request.getParameter("password_confirmation")).thenReturn(
"<PASSWORD>");
}
private void initInvalidUserNameFormBean() {
when(request.getParameter("first_name")).thenReturn("us");
when(request.getParameter("last_name")).thenReturn("userLastName");
when(request.getParameter("email")).thenReturn(EMAIL);
when(request.getParameter("password")).thenReturn("<PASSWORD>");
when(request.getParameter("password_confirmation")).thenReturn(
"<PASSWORD>");
}
@Test
public void testCaptchaProviderDeletesExpired() throws ServletException,
IOException {
servlet.doGet(request, response);
Mockito.verify(captchaProvider).deleteExpired(request);
}
@Test
public void testIncorrectUserName() throws ServletException, IOException {
initInvalidUserNameFormBean();
servlet.doPost(request, response);
ArgumentCaptor<Map> argument = ArgumentCaptor.forClass(Map.class);
Mockito.verify(request).setAttribute(Mockito.eq("validation"),
argument.capture());
Map<String, String> map = (Map<String, String>) argument.getValue();
String key = "firstName";
assertTrue(map.containsKey(key));
}
@Test
public void testUserAlreadyRegistered() throws ServletException,
IOException {
initValidFormBean();
servlet.doPost(request, response);
ArgumentCaptor<Boolean> argument = ArgumentCaptor
.forClass(Boolean.class);
Mockito.verify(request).setAttribute(Mockito.eq("alreadyRegistered"),
argument.capture());
boolean isRegistered = argument.getValue();
boolean expected = true;
assertEquals(expected, isRegistered);
}
@Test
public void testCaptchaIncorrect() throws ServletException, IOException {
initValidFormBean();
when(request.getParameter("captcha")).thenReturn("wrong");
servlet.doPost(request, response);
ArgumentCaptor<Boolean> argument = ArgumentCaptor
.forClass(Boolean.class);
Mockito.verify(request).setAttribute(Mockito.eq("invalidCaptcha"),
argument.capture());
boolean invalidCaptcha = argument.getValue();
boolean expected = true;
assertEquals(expected, invalidCaptcha);
}
@Test
public void testSuccessRegisterUser() throws IllegalAccessException,
ServletException, IOException, ElementAlreadyExistsException,
PersistException {
initValidFormBean();
when(request.getParameter("email")).thenReturn("<EMAIL>");
servlet.doPost(request, response);
Mockito.verify(userService).addUser(any(User.class));
}
@Test
public void testAvatarStored() throws ServletException, IOException {
initNewUserBean();
servlet.init(servletConfig);
servlet.doPost(request, response);
Mockito.verify(avatarService).store(any(Part.class), anyString());
}
@Test
public void testAvatarDeletedIfError() throws ServletException, IOException {
initNewUserBean();
Mockito.doThrow(ElementAlreadyExistsException.class).when(userService)
.addUser(any(User.class));
servlet.init(servletConfig);
servlet.doPost(request, response);
Mockito.verify(avatarService).remove(anyString());
}
}
| 8,109 | 0.781561 | 0.780455 | 248 | 31.806452 | 24.429186 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.927419 | false | false |
10
|
383f1fd51e9fbd4a08b0620e6f575c1a1b11d23f
| 21,698,174,810,886 |
155d7e5c1543f6d102479de8e54527f4b77a1b38
|
/server-core/src/main/java/io/onedev/server/event/DefaultListenerRegistry.java
|
aa92a0450b17f9e6561815f3f923da205bda410c
|
[
"MIT"
] |
permissive
|
theonedev/onedev
|
https://github.com/theonedev/onedev
|
0945cbe8c2ebeeee781ab88ea11363217bf1d0b7
|
1ec9918988611d5eb284a21d7e94e071c7b48aa7
|
refs/heads/main
| 2023-08-22T22:37:29.554000 | 2023-08-22T14:52:13 | 2023-08-22T14:52:13 | 156,317,154 | 12,162 | 880 |
MIT
| false | 2023-08-07T02:33:21 | 2018-11-06T02:57:01 | 2023-08-07T01:39:22 | 2023-08-07T02:15:24 | 205,120 | 11,450 | 773 | 0 |
Java
| false | false |
package io.onedev.server.event;
import io.onedev.commons.loader.AppLoader;
import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.LockUtils;
import io.onedev.server.cluster.ClusterManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.event.project.ProjectDeleted;
import io.onedev.server.event.project.ProjectEvent;
import io.onedev.server.event.project.ActiveServerChanged;
import io.onedev.server.persistence.SessionManager;
import io.onedev.server.persistence.TransactionManager;
import io.onedev.server.persistence.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Singleton
public class DefaultListenerRegistry implements ListenerRegistry, Serializable {
private static final Logger logger = LoggerFactory.getLogger(DefaultListenerRegistry.class);
private final ProjectManager projectManager;
private final TransactionManager transactionManager;
private final SessionManager sessionManager;
private final ClusterManager clusterManager;
private volatile Map<Object, Collection<Method>> listenerMethods;
private final Map<Class<?>, Collection<Listener>> listeners = new ConcurrentHashMap<>();
@Inject
public DefaultListenerRegistry(ProjectManager projectManager, ClusterManager clusterManager,
TransactionManager transactionManager, SessionManager sessionManager) {
this.projectManager = projectManager;
this.transactionManager = transactionManager;
this.clusterManager = clusterManager;
this.sessionManager = sessionManager;
}
public Object writeReplace() throws ObjectStreamException {
return new ManagedSerializedForm(ListenerRegistry.class);
}
private Map<Object, Collection<Method>> getListenerMethods() {
if (this.listenerMethods == null) {
Map<Object, Collection<Method>> listenersBySingleton = new HashMap<>();
for (Object singleton: AppLoader.getSingletons()) {
Collection<Method> listeners = new ArrayList<>();
Class<?> current = singleton.getClass();
Set<Class<?>> encounteredEventTypes = new HashSet<>();
while (current != Object.class) {
for (Method method: current.getDeclaredMethods()) {
if (method.isAnnotationPresent(Listen.class)) {
if (method.getParameterTypes().length != 1) {
throw new RuntimeException("Listener method " + method + " should have only one parameter");
}
Class<?> eventType = method.getParameterTypes()[0];
if (!encounteredEventTypes.contains(eventType)) {
listeners.add(method);
encounteredEventTypes.add(eventType);
}
}
}
current = current.getSuperclass();
}
listenersBySingleton.put(singleton, listeners);
}
this.listenerMethods = listenersBySingleton;
}
return this.listenerMethods;
}
protected Collection<Listener> getListeners(Class<?> eventType) {
Collection<Listener> listeners = this.listeners.get(eventType);
if (listeners == null) {
listeners = new ArrayList<>();
for (Map.Entry<Object, Collection<Method>> entry: getListenerMethods().entrySet()) {
for (Method method: entry.getValue()) {
Class<?> paramType = method.getParameterTypes()[0];
if (paramType.isAssignableFrom(eventType))
listeners.add(new Listener(entry.getKey(), method));
}
}
this.listeners.put(eventType, listeners);
}
return listeners;
}
@Override
public void invokeListeners(Object event) {
for (Listener listener: getListeners(event.getClass()))
listener.notify(event);
}
@Transactional
@Override
public void post(Object event) {
if (event instanceof ProjectEvent) {
ProjectEvent projectEvent = (ProjectEvent) event;
Long projectId = projectEvent.getProject().getId();
transactionManager.runAfterCommit(() -> projectManager.submitToActiveServer(projectId, () -> {
try {
String lockName = projectEvent.getLockName();
if (lockName != null) {
LockUtils.call(lockName, true, () -> {
sessionManager.run(() -> invokeListeners(event));
return null;
});
} else {
sessionManager.run(() -> invokeListeners(event));
}
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
} else if (event instanceof ProjectDeleted) {
ProjectDeleted projectDeleted = (ProjectDeleted) event;
Long projectId = projectDeleted.getProjectId();
String activeServer = projectManager.getActiveServer(projectId, false);
if (activeServer != null) {
transactionManager.runAfterCommit(() -> clusterManager.submitToServer(activeServer, () -> {
try {
sessionManager.run(() -> invokeListeners(event));
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
}
} else if (event instanceof ActiveServerChanged) {
ActiveServerChanged activeServerChanged = (ActiveServerChanged) event;
transactionManager.runAfterCommit(() -> clusterManager.submitToServer(activeServerChanged.getActiveServer(), () -> {
try {
sessionManager.run(() -> invokeListeners(event));
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
} else {
invokeListeners(event);
}
}
}
|
UTF-8
|
Java
| 5,489 |
java
|
DefaultListenerRegistry.java
|
Java
|
[] | null |
[] |
package io.onedev.server.event;
import io.onedev.commons.loader.AppLoader;
import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.LockUtils;
import io.onedev.server.cluster.ClusterManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.event.project.ProjectDeleted;
import io.onedev.server.event.project.ProjectEvent;
import io.onedev.server.event.project.ActiveServerChanged;
import io.onedev.server.persistence.SessionManager;
import io.onedev.server.persistence.TransactionManager;
import io.onedev.server.persistence.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Singleton
public class DefaultListenerRegistry implements ListenerRegistry, Serializable {
private static final Logger logger = LoggerFactory.getLogger(DefaultListenerRegistry.class);
private final ProjectManager projectManager;
private final TransactionManager transactionManager;
private final SessionManager sessionManager;
private final ClusterManager clusterManager;
private volatile Map<Object, Collection<Method>> listenerMethods;
private final Map<Class<?>, Collection<Listener>> listeners = new ConcurrentHashMap<>();
@Inject
public DefaultListenerRegistry(ProjectManager projectManager, ClusterManager clusterManager,
TransactionManager transactionManager, SessionManager sessionManager) {
this.projectManager = projectManager;
this.transactionManager = transactionManager;
this.clusterManager = clusterManager;
this.sessionManager = sessionManager;
}
public Object writeReplace() throws ObjectStreamException {
return new ManagedSerializedForm(ListenerRegistry.class);
}
private Map<Object, Collection<Method>> getListenerMethods() {
if (this.listenerMethods == null) {
Map<Object, Collection<Method>> listenersBySingleton = new HashMap<>();
for (Object singleton: AppLoader.getSingletons()) {
Collection<Method> listeners = new ArrayList<>();
Class<?> current = singleton.getClass();
Set<Class<?>> encounteredEventTypes = new HashSet<>();
while (current != Object.class) {
for (Method method: current.getDeclaredMethods()) {
if (method.isAnnotationPresent(Listen.class)) {
if (method.getParameterTypes().length != 1) {
throw new RuntimeException("Listener method " + method + " should have only one parameter");
}
Class<?> eventType = method.getParameterTypes()[0];
if (!encounteredEventTypes.contains(eventType)) {
listeners.add(method);
encounteredEventTypes.add(eventType);
}
}
}
current = current.getSuperclass();
}
listenersBySingleton.put(singleton, listeners);
}
this.listenerMethods = listenersBySingleton;
}
return this.listenerMethods;
}
protected Collection<Listener> getListeners(Class<?> eventType) {
Collection<Listener> listeners = this.listeners.get(eventType);
if (listeners == null) {
listeners = new ArrayList<>();
for (Map.Entry<Object, Collection<Method>> entry: getListenerMethods().entrySet()) {
for (Method method: entry.getValue()) {
Class<?> paramType = method.getParameterTypes()[0];
if (paramType.isAssignableFrom(eventType))
listeners.add(new Listener(entry.getKey(), method));
}
}
this.listeners.put(eventType, listeners);
}
return listeners;
}
@Override
public void invokeListeners(Object event) {
for (Listener listener: getListeners(event.getClass()))
listener.notify(event);
}
@Transactional
@Override
public void post(Object event) {
if (event instanceof ProjectEvent) {
ProjectEvent projectEvent = (ProjectEvent) event;
Long projectId = projectEvent.getProject().getId();
transactionManager.runAfterCommit(() -> projectManager.submitToActiveServer(projectId, () -> {
try {
String lockName = projectEvent.getLockName();
if (lockName != null) {
LockUtils.call(lockName, true, () -> {
sessionManager.run(() -> invokeListeners(event));
return null;
});
} else {
sessionManager.run(() -> invokeListeners(event));
}
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
} else if (event instanceof ProjectDeleted) {
ProjectDeleted projectDeleted = (ProjectDeleted) event;
Long projectId = projectDeleted.getProjectId();
String activeServer = projectManager.getActiveServer(projectId, false);
if (activeServer != null) {
transactionManager.runAfterCommit(() -> clusterManager.submitToServer(activeServer, () -> {
try {
sessionManager.run(() -> invokeListeners(event));
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
}
} else if (event instanceof ActiveServerChanged) {
ActiveServerChanged activeServerChanged = (ActiveServerChanged) event;
transactionManager.runAfterCommit(() -> clusterManager.submitToServer(activeServerChanged.getActiveServer(), () -> {
try {
sessionManager.run(() -> invokeListeners(event));
} catch (Exception e) {
logger.error("Error invoking listeners", e);
}
return null;
}));
} else {
invokeListeners(event);
}
}
}
| 5,489 | 0.726908 | 0.725997 | 157 | 33.961784 | 26.790503 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.261147 | false | false |
10
|
18c426e245b461a741ccfbc10054a42f39207f0c
| 2,156,073,597,948 |
5b331ea7c03e53e09f082e2df20470323c63e8dd
|
/core/src/com/mygdx/game/MyGdxGame.java
|
54e13fa8f0d1751bc0d699f71ffbccfae4eb6df1
|
[] |
no_license
|
Pamico/libGdxTest
|
https://github.com/Pamico/libGdxTest
|
25856082940fffb5179f7fbce53b7ca6d4adbd78
|
266ff374a0cc25926b84597b044ade485e019db8
|
refs/heads/master
| 2016-08-06T15:46:10.852000 | 2015-09-20T18:41:06 | 2015-09-20T18:41:06 | 42,824,476 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.screen.GameScreen;
public class MyGdxGame extends Game {
public static int width;
public static int height;
public MyGdxGame(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void create () {
setScreen(new GameScreen(this));
}
}
|
UTF-8
|
Java
| 521 |
java
|
MyGdxGame.java
|
Java
|
[] | null |
[] |
package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.screen.GameScreen;
public class MyGdxGame extends Game {
public static int width;
public static int height;
public MyGdxGame(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void create () {
setScreen(new GameScreen(this));
}
}
| 521 | 0.754319 | 0.74856 | 24 | 20.708334 | 16.118 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
10
|
239c1636f5aa725b71c46edcd1d18e1ea61d12a4
| 30,434,138,317,424 |
1dd6f9f8c6ec4f2bda1e9d1246f4c5032fb454e9
|
/rxremote/src/main/java/io/reactivex/remote/internal/RemoteEventManager.java
|
155d91f65a9a80e821ad82ce8cea8f1ecf9a6700
|
[
"Apache-2.0"
] |
permissive
|
josesamuel/RxRemote
|
https://github.com/josesamuel/RxRemote
|
effb3d593fcdb511e69671e583ce0e39c1135b20
|
25b016f8f6bccd924d572c1205c34b8e599c98d2
|
refs/heads/master
| 2021-12-05T20:29:39.535000 | 2021-11-30T18:14:07 | 2021-11-30T18:14:07 | 104,525,531 | 8 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.reactivex.remote.internal;
import remoter.annotations.Oneway;
import remoter.annotations.Remoter;
/**
* @hide
*
* Used internally by service side to call client
*/
//@Remoter
public interface RemoteEventManager {
String REMOTE_DATA_KEY = "RemoteData";
String REMOTE_DATA_TYPE = "RemoteDataType";
String REMOTE_DATA_EXTRA = "RemoteDataExtra";
String REMOTE_DATA_LIST_SIZE = "ListSize";
@Oneway
void subscribe(RemoteEventListener listener);
@Oneway
void unsubscribe();
@Oneway
void close();
}
|
UTF-8
|
Java
| 579 |
java
|
RemoteEventManager.java
|
Java
|
[
{
"context": "teEventManager {\r\n\r\n String REMOTE_DATA_KEY = \"RemoteData\";\r\n String REMOTE_DATA_TYPE = \"RemoteDataType\"",
"end": 284,
"score": 0.9966104030609131,
"start": 274,
"tag": "KEY",
"value": "RemoteData"
}
] | null |
[] |
package io.reactivex.remote.internal;
import remoter.annotations.Oneway;
import remoter.annotations.Remoter;
/**
* @hide
*
* Used internally by service side to call client
*/
//@Remoter
public interface RemoteEventManager {
String REMOTE_DATA_KEY = "RemoteData";
String REMOTE_DATA_TYPE = "RemoteDataType";
String REMOTE_DATA_EXTRA = "RemoteDataExtra";
String REMOTE_DATA_LIST_SIZE = "ListSize";
@Oneway
void subscribe(RemoteEventListener listener);
@Oneway
void unsubscribe();
@Oneway
void close();
}
| 579 | 0.671848 | 0.671848 | 27 | 19.444445 | 18.827351 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false |
10
|
af1b2d4c9c6e75c204f4de3bb0fe7a0dadb38122
| 17,978,733,128,913 |
6db7318c4b9ca9c4bdf068cee0eef2645cb16105
|
/src/test/java/unit/bizlogic/uam/UseCase/SysAdminOperation/LoginUseCaseTest.java
|
c9e05ae8b780556328ebeb1b8b5f40105151544f
|
[
"MIT"
] |
permissive
|
Kimita/spring-boot-demo
|
https://github.com/Kimita/spring-boot-demo
|
8fb7fdc6c2155f46c982cd6d976dfe4acbd282a3
|
837005a42499834fc3379ed9868e84596ecf0bab
|
refs/heads/main
| 2023-08-21T06:54:37.255000 | 2021-09-30T15:47:56 | 2021-09-30T15:47:56 | 379,125,457 | 0 | 0 |
MIT
| true | 2021-06-22T03:02:49 | 2021-06-22T03:02:48 | 2021-06-02T06:45:46 | 2021-06-22T02:40:04 | 2,305 | 0 | 0 | 0 | null | false | false |
package unit.bizlogic.uam.UseCase.SysAdminOperation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import page.clapandwhistle.demo.spring.bizlogic.uam.UseCase.SysAdminOperation.Login.LoginUseCase;
import page.clapandwhistle.demo.spring.bizlogic.uam.UseCase.SysAdminOperation.Login.Result;
import page.clapandwhistle.demo.spring.bizlogic.uam.Aggregate.Exception.NotExistException;
import page.clapandwhistle.demo.spring.bizlogic.uam.Aggregate.Exception.PasswordIsNotMatchException;
import unit.infrastructure.uam.AggregateRepository.AdminUser.ForTestAdminUserAggregateRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
final public class LoginUseCaseTest {
private final static ForTestAdminUserAggregateRepository adminUserRepos = ForTestAdminUserAggregateRepository.getInstance();
@BeforeEach
void setUp(TestInfo testInfo) {
// System.out.println(String.format("test started: %s", testInfo.getDisplayName()));
}
@Test
public void 基本系列_システム管理コンソールへログインする() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.テスト用の有効な管理者メールアドレス,
ForTestAdminUserAggregateRepository.テスト用Password
);
assertTrue(result.isSuccess());
assertThat(result.adminId()).isGreaterThan(0);
}
@Test
public void 代替系列_入力されたメールアドレスの一致する有効な管理ユーザアカウントが無い() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.システムログイン時例外用_使用されていないメールアドレス
, ForTestAdminUserAggregateRepository.テスト用Password
);
RuntimeException exception = result.exception();
assertFalse(result.isSuccess());
assertThat(result.eMessage()).isEqualTo(LoginUseCase.E_MSG_NOT_EXISTS);
assertNotNull(exception);
assertEquals(NotExistException.class, exception.getClass());
}
@Test
public void 代替系列_入力されたパスワードが対象管理ユーザアカウントの管理ユーザパスワードと一致しない() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.テスト用の有効な管理者メールアドレス
, ForTestAdminUserAggregateRepository.テスト用の誤ったPassword
);
RuntimeException exception = result.exception();
assertFalse(result.isSuccess());
assertThat(result.eMessage()).isEqualTo(LoginUseCase.E_MSG_PASSWORD_IS_NOT_MATCH);
assertNotNull(exception);
assertEquals(PasswordIsNotMatchException.class, exception.getClass());
}
}
|
UTF-8
|
Java
| 3,165 |
java
|
LoginUseCaseTest.java
|
Java
|
[] | null |
[] |
package unit.bizlogic.uam.UseCase.SysAdminOperation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import page.clapandwhistle.demo.spring.bizlogic.uam.UseCase.SysAdminOperation.Login.LoginUseCase;
import page.clapandwhistle.demo.spring.bizlogic.uam.UseCase.SysAdminOperation.Login.Result;
import page.clapandwhistle.demo.spring.bizlogic.uam.Aggregate.Exception.NotExistException;
import page.clapandwhistle.demo.spring.bizlogic.uam.Aggregate.Exception.PasswordIsNotMatchException;
import unit.infrastructure.uam.AggregateRepository.AdminUser.ForTestAdminUserAggregateRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
final public class LoginUseCaseTest {
private final static ForTestAdminUserAggregateRepository adminUserRepos = ForTestAdminUserAggregateRepository.getInstance();
@BeforeEach
void setUp(TestInfo testInfo) {
// System.out.println(String.format("test started: %s", testInfo.getDisplayName()));
}
@Test
public void 基本系列_システム管理コンソールへログインする() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.テスト用の有効な管理者メールアドレス,
ForTestAdminUserAggregateRepository.テスト用Password
);
assertTrue(result.isSuccess());
assertThat(result.adminId()).isGreaterThan(0);
}
@Test
public void 代替系列_入力されたメールアドレスの一致する有効な管理ユーザアカウントが無い() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.システムログイン時例外用_使用されていないメールアドレス
, ForTestAdminUserAggregateRepository.テスト用Password
);
RuntimeException exception = result.exception();
assertFalse(result.isSuccess());
assertThat(result.eMessage()).isEqualTo(LoginUseCase.E_MSG_NOT_EXISTS);
assertNotNull(exception);
assertEquals(NotExistException.class, exception.getClass());
}
@Test
public void 代替系列_入力されたパスワードが対象管理ユーザアカウントの管理ユーザパスワードと一致しない() throws Exception {
LoginUseCase useCase = new LoginUseCase(adminUserRepos);
Result result = useCase.execute(
ForTestAdminUserAggregateRepository.テスト用の有効な管理者メールアドレス
, ForTestAdminUserAggregateRepository.テスト用の誤ったPassword
);
RuntimeException exception = result.exception();
assertFalse(result.isSuccess());
assertThat(result.eMessage()).isEqualTo(LoginUseCase.E_MSG_PASSWORD_IS_NOT_MATCH);
assertNotNull(exception);
assertEquals(PasswordIsNotMatchException.class, exception.getClass());
}
}
| 3,165 | 0.748661 | 0.748304 | 64 | 42.765625 | 33.438725 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578125 | false | false |
10
|
881af188ed8cb6e4e84ead06a77f03701cca7eb8
| 22,471,268,894,992 |
ed0cc441117524bd510cfa3f47d0577960e8b128
|
/src/main/java/com/hb/design/principle/demeter/Boss.java
|
a532c1c0c4b8f7c4d4eb356db6293c6bbfe398ff
|
[
"Apache-2.0"
] |
permissive
|
hbheyho/DesignPatternLearning
|
https://github.com/hbheyho/DesignPatternLearning
|
d5d89a4714c92d1287d003b4d2201890083ffe45
|
ab51de1e0b62fd7c91af891145319483e47d074e
|
refs/heads/master
| 2022-12-21T09:26:12.124000 | 2020-03-14T07:57:07 | 2020-03-14T07:57:07 | 242,640,719 | 1 | 0 |
Apache-2.0
| false | 2022-12-16T03:37:37 | 2020-02-24T03:46:15 | 2022-03-28T01:03:19 | 2022-12-16T03:37:32 | 7,387 | 0 | 0 | 3 |
Java
| false | false |
package com.hb.design.principle.demeter;
/**
* @Author:HB
* @Description:
* @Createdata:Created in 13:11 2020/1/7.
*/
public class Boss {
public void commandCheckCourse(TeamLeader teamLeader){ // TeamLeader出现在参数中 - 直接的朋友
// Course出现在成员变量中,不属于直接朋友,Boss类不需要关注Course的详细信息
/* List<Course> courseList = new ArrayList<Course>();
for (int i = 0; i<= 20 ; i++){
courseList.add(new Course());
}*/
teamLeader.checkNumberOfCourses();
}
}
|
UTF-8
|
Java
| 575 |
java
|
Boss.java
|
Java
|
[
{
"context": " com.hb.design.principle.demeter;\n\n/**\n * @Author:HB\n * @Description:\n * @Createdata:Created in 13:11",
"end": 59,
"score": 0.9898776412010193,
"start": 57,
"tag": "USERNAME",
"value": "HB"
}
] | null |
[] |
package com.hb.design.principle.demeter;
/**
* @Author:HB
* @Description:
* @Createdata:Created in 13:11 2020/1/7.
*/
public class Boss {
public void commandCheckCourse(TeamLeader teamLeader){ // TeamLeader出现在参数中 - 直接的朋友
// Course出现在成员变量中,不属于直接朋友,Boss类不需要关注Course的详细信息
/* List<Course> courseList = new ArrayList<Course>();
for (int i = 0; i<= 20 ; i++){
courseList.add(new Course());
}*/
teamLeader.checkNumberOfCourses();
}
}
| 575 | 0.623742 | 0.597585 | 17 | 28.235294 | 24.613552 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false |
10
|
417695f42e7893803d867e39019918c8faa8440a
| 32,950,989,163,916 |
b811e6448957ad696dbf74ba41292057d228f353
|
/app/src/main/java/com/huntor/mscrm/app/ui/TicketInfoActivity.java
|
c11d5fd04f4edafc3c64ed5c048dddb9f50cdffd
|
[] |
no_license
|
Hn1993/work
|
https://github.com/Hn1993/work
|
c016e0f1fba67ac9d9e2b505a7e69df8ccab8325
|
1323c0283b442884fa608bad3257db6717aeb55d
|
refs/heads/master
| 2018-01-07T23:11:09.969000 | 2015-10-13T07:09:23 | 2015-10-13T07:09:23 | 44,235,080 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.huntor.mscrm.app.ui;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.huntor.mscrm.app.R;
import com.huntor.mscrm.app.adapter.TicketInfoExpandableListViewAdapter;
import com.huntor.mscrm.app.adapter.VerificationInfoAdapter;
import com.huntor.mscrm.app.model.EmployeeWecardList;
import com.huntor.mscrm.app.model.ShowListDialog;
import com.huntor.mscrm.app.model.WecardConsumeList;
import com.huntor.mscrm.app.net.BaseResponse;
import com.huntor.mscrm.app.net.HttpRequestController;
import com.huntor.mscrm.app.net.HttpResponseListener;
import com.huntor.mscrm.app.net.api.ApiEmployeeWecardConsumeCount;
import com.huntor.mscrm.app.net.api.ApiEmployeeWecardList;
import com.huntor.mscrm.app.net.api.ApiWecardConsumeList;
import com.huntor.mscrm.app.ui.component.BaseActivity;
import com.huntor.mscrm.app.utils.*;
import java.util.*;
/**
* Created by Admin on 2015/8/6.
* 核销记录
*/
public class TicketInfoActivity extends BaseActivity implements View.OnClickListener{
String TAG="TicketInfoActivity";
private ListView mVerificationInfoListView;
private ArrayList<WecardConsumeList.consumeRecord> mData;
private VerificationInfoAdapter mVerficationInfoAdapter;
private ExpandableListView mExpandableListView;
private TextView Year,MonthAndDay;//年月日
private TextView ticketName;
private TextView ticketInfo;
private TextView ticketCount;
private ArrayList<EmployeeWecardList.CardsEntity> parent=null;
private Map<String , ArrayList> map=null;
private ExpandableListAdapter mExpandableListViewAdapter=null;
private DatePickerDialog dialog;//时间对话框
//private int voucherId;
private long startTime;
private long endTime;
private int empId;
private int count;//核销次数
String nowDate,totalDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_ticketinfo);
findViewById(R.id.img_left_corner).setOnClickListener(this);
empId= PreferenceUtils.getInt(TicketInfoActivity.this,"id",-1);
Log.e(TAG, "empId= :" + empId);
parent=new ArrayList<EmployeeWecardList.CardsEntity>();
map=new HashMap<String, ArrayList>();
findViews();
//initData();
getHttpconsumeCount();//获取核销次数
getHttpWecardList();//卡券列表查询
}
/**
*卡券列表查询
*/
private void getHttpWecardList() {
Log.e(TAG,"卡券列表查询");
Log.e(TAG,"getHttpWecardList empId=:"+empId);
Log.e(TAG, "getHttpconsumeCount startTime=:" + startTime);
Log.e(TAG, "getHttpconsumeCount endTime=:" + endTime);
showCustomDialog(R.string.loading);
HttpRequestController.getEmployeeWecardList(TicketInfoActivity.this, empId, new HttpResponseListener<ApiEmployeeWecardList.ApiEmployeeWecardListResponse>() {
@Override
public void onResult(ApiEmployeeWecardList.ApiEmployeeWecardListResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
if (response.employeeWecardList != null) {
parent = (ArrayList<EmployeeWecardList.CardsEntity>) response.employeeWecardList.cards;
Log.e(TAG, "parent=:" + parent.size());
for (int i = 0; i < parent.size(); i++) {
getHttpConsumeList(parent.get(i).id, parent.get(i).name);
}
}
//getHttpConsumeList(parent.get(0).id, parent.get(0).name);
dismissCustomDialog();
} else {
Utils.toast(TicketInfoActivity.this, "获取数据失败!");
dismissCustomDialog();
}
}
});
//dismissCustomDialog();
}
/**
* 查询核销次数
*/
private void getHttpconsumeCount() {
Log.e(TAG,"查询核销次数");
Log.e(TAG,"getHttpconsumeCount empId=:"+empId);
Log.e(TAG,"getHttpconsumeCount startTime=:"+startTime);
Log.e(TAG,"getHttpconsumeCount endTime=:"+endTime);
HttpRequestController.getEmployeeWecardConsumeCount(TicketInfoActivity.this, empId, startTime, endTime, new HttpResponseListener<ApiEmployeeWecardConsumeCount.ApiEmployeeWecardConsumeCountResponse>() {
@Override
public void onResult(ApiEmployeeWecardConsumeCount.ApiEmployeeWecardConsumeCountResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
Message message = new Message();
if (response.employeeWecardConsumeCount != null) {
message.what = 0;
count = response.employeeWecardConsumeCount.count;
handler.sendMessage(message);
}
} else {
Utils.toast(TicketInfoActivity.this, "查询核销次数失败!");
}
}
});
}
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
ticketCount.setText(count+"");
break;
}
}
};
private void getHttpConsumeList(int voucherId, final String name) {
//showCustomDialog(R.string.loading);
Log.e(TAG,"getHttpConsumeList empId=:"+empId);
Log.e(TAG,"getHttpConsumeList startTime=:"+startTime);
Log.e(TAG,"getHttpConsumeList endTime=:"+endTime);
Log.e(TAG,"voucherId=:"+voucherId);
showCustomDialog(R.string.loading);
HttpRequestController.getApiWecardConsumeList(TicketInfoActivity.this, voucherId, empId, startTime, endTime, 100, 1, 1, 2, new HttpResponseListener<ApiWecardConsumeList.ApiWecardConsumeListResponse>() {
@Override
public void onResult(ApiWecardConsumeList.ApiWecardConsumeListResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
//Utils.toast(TicketVerificationActivity.this, wecardInfo.card.cardType + "");
if (response.wecardConsumeList != null) {
map.put(name, (ArrayList) response.wecardConsumeList.consumeRecord);
final List<WecardConsumeList.consumeRecord> list = response.wecardConsumeList.consumeRecord;
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
Intent intent = new Intent(TicketInfoActivity.this, DetailedInformationActivity.class);
WecardConsumeList.consumeRecord item = list.get(i);
Log.e(TAG,"i1==============="+i1);
Log.e(TAG,"i==============="+i);
intent.putExtra(Constant.FANS_ID, item.id);
startActivity(intent);
return false;
}
});
}
Log.e(TAG, "map=:" + map.size());
initData();
dismissCustomDialog();
} else{
Utils.toast(TicketInfoActivity.this, "获取数据失败!");
dismissCustomDialog();
}
}
});
dismissCustomDialog();
}
private void initData() {
mExpandableListViewAdapter=new TicketInfoExpandableListViewAdapter(TicketInfoActivity.this,parent,map);
mExpandableListView.setAdapter(mExpandableListViewAdapter);
}
private void findViews() {
mVerificationInfoListView = (ListView) findViewById(R.id.listview_verification_info);
findViewById(R.id.ticket_info_select_time).setOnClickListener(this);
Year= (TextView) findViewById(R.id.ticket_info_time_select_year);
MonthAndDay= (TextView) findViewById(R.id.ticket_info_time_select_day);
ticketName= (TextView) findViewById(R.id.ticket_info_ticket_name);
ticketName.setOnClickListener(this);
ticketInfo= (TextView) findViewById(R.id.ticket_info_detail);
ticketCount= (TextView) findViewById(R.id.ticket_info_count);
TextPaint tp = ticketInfo.getPaint();//
tp.setFakeBoldText(true); //加粗字体
mExpandableListView= (ExpandableListView) findViewById(R.id.expandableListView_ticket_info);
mExpandableListView.setGroupIndicator(null);//去掉左边的图片下标
nowDate = DateFormatUtils.getPatternTime();
Log.e(TAG,"nowDate==="+nowDate);
String[] datas = nowDate.split("-");
totalDate = nowDate;
Year.setText(datas[0]);
MonthAndDay.setText(Integer.parseInt(datas[1]) + "月");
startTime=DateFormatUtils.String2long(DateFormatUtils.getFirstDayOfMonth(nowDate));
endTime=DateFormatUtils.String2long(DateFormatUtils.getLastDayOfMonth(nowDate));
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.img_left_corner:
this.finish();
break;
case R.id.ticket_info_select_time://时间选择器
timeSelect();
break;
case R.id.ticket_info_ticket_name://卡券名称
Intent intent=new Intent(this, TicketVerificationActivity.class);
intent.putExtra(Constant.ENTER_TICKET,"TicketInfo");
startActivity(intent);
break;
}
}
private void timeSelect(){
Calendar cal=Calendar.getInstance();
String[] datas = totalDate.split("-");
dialog=new CustomerDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
Year.setText(i+"年");
MonthAndDay.setText(i1+1+"月");
//startTime=DateFormatUtils.String2long();
//getHttpWecardList();
totalDate=i+"-"+(i1+1);
PreferenceUtils.putString(TicketInfoActivity.this, Constant.TICKET_INFO_DATE, totalDate);
startTime=DateFormatUtils.String2long(DateFormatUtils.getFirstDayOfMonth(totalDate));
endTime=DateFormatUtils.String2long(DateFormatUtils.getLastDayOfMonth(totalDate));
Log.e(TAG,"totlaDate="+totalDate);
getHttpconsumeCount();//获取核销次数
getHttpWecardList();//卡券列表查询
}
},Integer.parseInt(datas[0]),Integer.parseInt(datas[1]) - 1,cal.get(Calendar.DAY_OF_MONTH));
//cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
((ViewGroup) ((ViewGroup) dialog.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(2)
.setVisibility(View.GONE);
dialog.setTitle("请选择时间");
dialog.show();
}
class CustomerDatePickerDialog extends DatePickerDialog {
public CustomerDatePickerDialog(Context context,
OnDateSetListener callBack, int year, int monthOfYear,
int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
super.onDateChanged(view, year, month, day);
if(dialog!=null){
dialog.setTitle(year+"年"+(month + 1) + "月");
}
}
}
}
|
UTF-8
|
Java
| 12,394 |
java
|
TicketInfoActivity.java
|
Java
|
[
{
"context": "p.utils.*;\n\nimport java.util.*;\n\n/**\n * Created by Admin on 2015/8/6.\n * 核销记录\n */\npublic class TicketInfoA",
"end": 1202,
"score": 0.7588437795639038,
"start": 1197,
"tag": "USERNAME",
"value": "Admin"
}
] | null |
[] |
package com.huntor.mscrm.app.ui;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.huntor.mscrm.app.R;
import com.huntor.mscrm.app.adapter.TicketInfoExpandableListViewAdapter;
import com.huntor.mscrm.app.adapter.VerificationInfoAdapter;
import com.huntor.mscrm.app.model.EmployeeWecardList;
import com.huntor.mscrm.app.model.ShowListDialog;
import com.huntor.mscrm.app.model.WecardConsumeList;
import com.huntor.mscrm.app.net.BaseResponse;
import com.huntor.mscrm.app.net.HttpRequestController;
import com.huntor.mscrm.app.net.HttpResponseListener;
import com.huntor.mscrm.app.net.api.ApiEmployeeWecardConsumeCount;
import com.huntor.mscrm.app.net.api.ApiEmployeeWecardList;
import com.huntor.mscrm.app.net.api.ApiWecardConsumeList;
import com.huntor.mscrm.app.ui.component.BaseActivity;
import com.huntor.mscrm.app.utils.*;
import java.util.*;
/**
* Created by Admin on 2015/8/6.
* 核销记录
*/
public class TicketInfoActivity extends BaseActivity implements View.OnClickListener{
String TAG="TicketInfoActivity";
private ListView mVerificationInfoListView;
private ArrayList<WecardConsumeList.consumeRecord> mData;
private VerificationInfoAdapter mVerficationInfoAdapter;
private ExpandableListView mExpandableListView;
private TextView Year,MonthAndDay;//年月日
private TextView ticketName;
private TextView ticketInfo;
private TextView ticketCount;
private ArrayList<EmployeeWecardList.CardsEntity> parent=null;
private Map<String , ArrayList> map=null;
private ExpandableListAdapter mExpandableListViewAdapter=null;
private DatePickerDialog dialog;//时间对话框
//private int voucherId;
private long startTime;
private long endTime;
private int empId;
private int count;//核销次数
String nowDate,totalDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_ticketinfo);
findViewById(R.id.img_left_corner).setOnClickListener(this);
empId= PreferenceUtils.getInt(TicketInfoActivity.this,"id",-1);
Log.e(TAG, "empId= :" + empId);
parent=new ArrayList<EmployeeWecardList.CardsEntity>();
map=new HashMap<String, ArrayList>();
findViews();
//initData();
getHttpconsumeCount();//获取核销次数
getHttpWecardList();//卡券列表查询
}
/**
*卡券列表查询
*/
private void getHttpWecardList() {
Log.e(TAG,"卡券列表查询");
Log.e(TAG,"getHttpWecardList empId=:"+empId);
Log.e(TAG, "getHttpconsumeCount startTime=:" + startTime);
Log.e(TAG, "getHttpconsumeCount endTime=:" + endTime);
showCustomDialog(R.string.loading);
HttpRequestController.getEmployeeWecardList(TicketInfoActivity.this, empId, new HttpResponseListener<ApiEmployeeWecardList.ApiEmployeeWecardListResponse>() {
@Override
public void onResult(ApiEmployeeWecardList.ApiEmployeeWecardListResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
if (response.employeeWecardList != null) {
parent = (ArrayList<EmployeeWecardList.CardsEntity>) response.employeeWecardList.cards;
Log.e(TAG, "parent=:" + parent.size());
for (int i = 0; i < parent.size(); i++) {
getHttpConsumeList(parent.get(i).id, parent.get(i).name);
}
}
//getHttpConsumeList(parent.get(0).id, parent.get(0).name);
dismissCustomDialog();
} else {
Utils.toast(TicketInfoActivity.this, "获取数据失败!");
dismissCustomDialog();
}
}
});
//dismissCustomDialog();
}
/**
* 查询核销次数
*/
private void getHttpconsumeCount() {
Log.e(TAG,"查询核销次数");
Log.e(TAG,"getHttpconsumeCount empId=:"+empId);
Log.e(TAG,"getHttpconsumeCount startTime=:"+startTime);
Log.e(TAG,"getHttpconsumeCount endTime=:"+endTime);
HttpRequestController.getEmployeeWecardConsumeCount(TicketInfoActivity.this, empId, startTime, endTime, new HttpResponseListener<ApiEmployeeWecardConsumeCount.ApiEmployeeWecardConsumeCountResponse>() {
@Override
public void onResult(ApiEmployeeWecardConsumeCount.ApiEmployeeWecardConsumeCountResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
Message message = new Message();
if (response.employeeWecardConsumeCount != null) {
message.what = 0;
count = response.employeeWecardConsumeCount.count;
handler.sendMessage(message);
}
} else {
Utils.toast(TicketInfoActivity.this, "查询核销次数失败!");
}
}
});
}
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
ticketCount.setText(count+"");
break;
}
}
};
private void getHttpConsumeList(int voucherId, final String name) {
//showCustomDialog(R.string.loading);
Log.e(TAG,"getHttpConsumeList empId=:"+empId);
Log.e(TAG,"getHttpConsumeList startTime=:"+startTime);
Log.e(TAG,"getHttpConsumeList endTime=:"+endTime);
Log.e(TAG,"voucherId=:"+voucherId);
showCustomDialog(R.string.loading);
HttpRequestController.getApiWecardConsumeList(TicketInfoActivity.this, voucherId, empId, startTime, endTime, 100, 1, 1, 2, new HttpResponseListener<ApiWecardConsumeList.ApiWecardConsumeListResponse>() {
@Override
public void onResult(ApiWecardConsumeList.ApiWecardConsumeListResponse response) {
if (response.getRetCode() == BaseResponse.RET_HTTP_STATUS_OK) {
//Utils.toast(TicketVerificationActivity.this, wecardInfo.card.cardType + "");
if (response.wecardConsumeList != null) {
map.put(name, (ArrayList) response.wecardConsumeList.consumeRecord);
final List<WecardConsumeList.consumeRecord> list = response.wecardConsumeList.consumeRecord;
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
Intent intent = new Intent(TicketInfoActivity.this, DetailedInformationActivity.class);
WecardConsumeList.consumeRecord item = list.get(i);
Log.e(TAG,"i1==============="+i1);
Log.e(TAG,"i==============="+i);
intent.putExtra(Constant.FANS_ID, item.id);
startActivity(intent);
return false;
}
});
}
Log.e(TAG, "map=:" + map.size());
initData();
dismissCustomDialog();
} else{
Utils.toast(TicketInfoActivity.this, "获取数据失败!");
dismissCustomDialog();
}
}
});
dismissCustomDialog();
}
private void initData() {
mExpandableListViewAdapter=new TicketInfoExpandableListViewAdapter(TicketInfoActivity.this,parent,map);
mExpandableListView.setAdapter(mExpandableListViewAdapter);
}
private void findViews() {
mVerificationInfoListView = (ListView) findViewById(R.id.listview_verification_info);
findViewById(R.id.ticket_info_select_time).setOnClickListener(this);
Year= (TextView) findViewById(R.id.ticket_info_time_select_year);
MonthAndDay= (TextView) findViewById(R.id.ticket_info_time_select_day);
ticketName= (TextView) findViewById(R.id.ticket_info_ticket_name);
ticketName.setOnClickListener(this);
ticketInfo= (TextView) findViewById(R.id.ticket_info_detail);
ticketCount= (TextView) findViewById(R.id.ticket_info_count);
TextPaint tp = ticketInfo.getPaint();//
tp.setFakeBoldText(true); //加粗字体
mExpandableListView= (ExpandableListView) findViewById(R.id.expandableListView_ticket_info);
mExpandableListView.setGroupIndicator(null);//去掉左边的图片下标
nowDate = DateFormatUtils.getPatternTime();
Log.e(TAG,"nowDate==="+nowDate);
String[] datas = nowDate.split("-");
totalDate = nowDate;
Year.setText(datas[0]);
MonthAndDay.setText(Integer.parseInt(datas[1]) + "月");
startTime=DateFormatUtils.String2long(DateFormatUtils.getFirstDayOfMonth(nowDate));
endTime=DateFormatUtils.String2long(DateFormatUtils.getLastDayOfMonth(nowDate));
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.img_left_corner:
this.finish();
break;
case R.id.ticket_info_select_time://时间选择器
timeSelect();
break;
case R.id.ticket_info_ticket_name://卡券名称
Intent intent=new Intent(this, TicketVerificationActivity.class);
intent.putExtra(Constant.ENTER_TICKET,"TicketInfo");
startActivity(intent);
break;
}
}
private void timeSelect(){
Calendar cal=Calendar.getInstance();
String[] datas = totalDate.split("-");
dialog=new CustomerDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
Year.setText(i+"年");
MonthAndDay.setText(i1+1+"月");
//startTime=DateFormatUtils.String2long();
//getHttpWecardList();
totalDate=i+"-"+(i1+1);
PreferenceUtils.putString(TicketInfoActivity.this, Constant.TICKET_INFO_DATE, totalDate);
startTime=DateFormatUtils.String2long(DateFormatUtils.getFirstDayOfMonth(totalDate));
endTime=DateFormatUtils.String2long(DateFormatUtils.getLastDayOfMonth(totalDate));
Log.e(TAG,"totlaDate="+totalDate);
getHttpconsumeCount();//获取核销次数
getHttpWecardList();//卡券列表查询
}
},Integer.parseInt(datas[0]),Integer.parseInt(datas[1]) - 1,cal.get(Calendar.DAY_OF_MONTH));
//cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH));
((ViewGroup) ((ViewGroup) dialog.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(2)
.setVisibility(View.GONE);
dialog.setTitle("请选择时间");
dialog.show();
}
class CustomerDatePickerDialog extends DatePickerDialog {
public CustomerDatePickerDialog(Context context,
OnDateSetListener callBack, int year, int monthOfYear,
int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
super.onDateChanged(view, year, month, day);
if(dialog!=null){
dialog.setTitle(year+"年"+(month + 1) + "月");
}
}
}
}
| 12,394 | 0.620763 | 0.617391 | 280 | 42.410713 | 33.340118 | 210 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.878571 | false | false |
10
|
213258bed08a3b1ab7582d55655c65d9fb693fd3
| 8,186,207,679,544 |
b9ac805904d9664a2c332e7fe1018cbcb5bec6fe
|
/src/cs2321/JosephusTest.java
|
404fc44cfb379fefbf29c5a635cbe418883d1bc4
|
[] |
no_license
|
Ericgi231/MTU_DS_StackQueueApplication
|
https://github.com/Ericgi231/MTU_DS_StackQueueApplication
|
b8eb838c4dd6a86ffced1703de0abcb0aef5c838
|
5e3cefb0bb74d8105d48262ba5e62fb178513539
|
refs/heads/master
| 2020-11-27T13:38:41.474000 | 2019-12-21T18:18:56 | 2019-12-21T18:18:56 | 229,466,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cs2321;
import org.junit.Before;
import org.junit.Test;
public class JosephusTest {
private Josephus game = init();
private String[] people = new String[6];
public Josephus init() {
return new Josephus();
}
@Before
public void setUp() throws Exception {
people[0] = "Alice";
people[1] = "Bob";
people[2] = "Cindy";
people[3] = "Doug";
people[4] = "Ed";
people[5] = "Fred";
}
@Test
@jug.TestName("number between 0 and array.size gives correct answer")
public void testOrder1() {
org.junit.Assert.assertEquals("Ed",game.order(people,2).last().getElement());
}
@Test
@jug.TestName("number 1 returns last name in array")
public void testOrder2() {
org.junit.Assert.assertEquals("Fred",game.order(people,1).last().getElement());
}
@Test
@jug.TestName("number greater than array size returns correct answer")
public void testOrder3() {
org.junit.Assert.assertEquals("Cindy",game.order(people,8).last().getElement());
}
@Test
@jug.TestName("number equal to array.size returns correct answer")
public void testOrder4() {
org.junit.Assert.assertEquals("Doug",game.order(people,6).last().getElement());
}
@Test
@jug.TestName("Extra number between 0 and array.size gives correct answer")
public void testOrder5() {
org.junit.Assert.assertEquals("Alice",game.order(people,3).last().getElement());
}
@Test
@jug.TestName("Extra number between 0 and array.size gives correct answer")
public void testOrder6() {
org.junit.Assert.assertEquals("Ed",game.order(people,4).last().getElement());
}
}
|
UTF-8
|
Java
| 1,558 |
java
|
JosephusTest.java
|
Java
|
[
{
"context": "ic void setUp() throws Exception {\n\t\tpeople[0] = \"Alice\";\n\t\tpeople[1] = \"Bob\";\n\t\tpeople[2] = \"Cindy\";\n\t\tp",
"end": 296,
"score": 0.9998261332511902,
"start": 291,
"tag": "NAME",
"value": "Alice"
},
{
"context": "Exception {\n\t\tpeople[0] = \"Alice\";\n\t\tpeople[1] = \"Bob\";\n\t\tpeople[2] = \"Cindy\";\n\t\tpeople[3] = \"Doug\";\n\t\t",
"end": 317,
"score": 0.9998263716697693,
"start": 314,
"tag": "NAME",
"value": "Bob"
},
{
"context": "0] = \"Alice\";\n\t\tpeople[1] = \"Bob\";\n\t\tpeople[2] = \"Cindy\";\n\t\tpeople[3] = \"Doug\";\n\t\tpeople[4] = \"Ed\";\n\t\tpeo",
"end": 340,
"score": 0.9998065829277039,
"start": 335,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "1] = \"Bob\";\n\t\tpeople[2] = \"Cindy\";\n\t\tpeople[3] = \"Doug\";\n\t\tpeople[4] = \"Ed\";\n\t\tpeople[5] = \"Fred\";\n\t}\n\n\t",
"end": 362,
"score": 0.9998064637184143,
"start": 358,
"tag": "NAME",
"value": "Doug"
},
{
"context": "] = \"Cindy\";\n\t\tpeople[3] = \"Doug\";\n\t\tpeople[4] = \"Ed\";\n\t\tpeople[5] = \"Fred\";\n\t}\n\n\t@Test\n\t@jug.TestName",
"end": 382,
"score": 0.9998515844345093,
"start": 380,
"tag": "NAME",
"value": "Ed"
},
{
"context": "e[3] = \"Doug\";\n\t\tpeople[4] = \"Ed\";\n\t\tpeople[5] = \"Fred\";\n\t}\n\n\t@Test\n\t@jug.TestName(\"number between 0 and",
"end": 404,
"score": 0.9998477101325989,
"start": 400,
"tag": "NAME",
"value": "Fred"
},
{
"context": "d testOrder1() {\n\t\torg.junit.Assert.assertEquals(\"Ed\",game.order(people,2).last().getElement());\n\t}\n\n\t",
"end": 552,
"score": 0.9867217540740967,
"start": 550,
"tag": "NAME",
"value": "Ed"
},
{
"context": "d testOrder2() {\n\t\torg.junit.Assert.assertEquals(\"Fred\",game.order(people,1).last().getElement());\n\t}\n\n\t",
"end": 727,
"score": 0.9996687173843384,
"start": 723,
"tag": "NAME",
"value": "Fred"
},
{
"context": "d testOrder3() {\n\t\torg.junit.Assert.assertEquals(\"Cindy\",game.order(people,8).last().getElement());\n\t}\n\n\t",
"end": 921,
"score": 0.979078471660614,
"start": 916,
"tag": "NAME",
"value": "Cindy"
},
{
"context": "d testOrder4() {\n\t\torg.junit.Assert.assertEquals(\"Doug\",game.order(people,6).last().getElement());\n\t}\n\t\n",
"end": 1110,
"score": 0.9635515213012695,
"start": 1106,
"tag": "NAME",
"value": "Doug"
},
{
"context": "d testOrder5() {\n\t\torg.junit.Assert.assertEquals(\"Alice\",game.order(people,3).last().getElement());\n\t}\n\t\n",
"end": 1310,
"score": 0.9982435703277588,
"start": 1305,
"tag": "NAME",
"value": "Alice"
},
{
"context": "d testOrder6() {\n\t\torg.junit.Assert.assertEquals(\"Ed\",game.order(people,4).last().getElement());\n\t}\n\n}",
"end": 1507,
"score": 0.9940897226333618,
"start": 1505,
"tag": "NAME",
"value": "Ed"
}
] | null |
[] |
package cs2321;
import org.junit.Before;
import org.junit.Test;
public class JosephusTest {
private Josephus game = init();
private String[] people = new String[6];
public Josephus init() {
return new Josephus();
}
@Before
public void setUp() throws Exception {
people[0] = "Alice";
people[1] = "Bob";
people[2] = "Cindy";
people[3] = "Doug";
people[4] = "Ed";
people[5] = "Fred";
}
@Test
@jug.TestName("number between 0 and array.size gives correct answer")
public void testOrder1() {
org.junit.Assert.assertEquals("Ed",game.order(people,2).last().getElement());
}
@Test
@jug.TestName("number 1 returns last name in array")
public void testOrder2() {
org.junit.Assert.assertEquals("Fred",game.order(people,1).last().getElement());
}
@Test
@jug.TestName("number greater than array size returns correct answer")
public void testOrder3() {
org.junit.Assert.assertEquals("Cindy",game.order(people,8).last().getElement());
}
@Test
@jug.TestName("number equal to array.size returns correct answer")
public void testOrder4() {
org.junit.Assert.assertEquals("Doug",game.order(people,6).last().getElement());
}
@Test
@jug.TestName("Extra number between 0 and array.size gives correct answer")
public void testOrder5() {
org.junit.Assert.assertEquals("Alice",game.order(people,3).last().getElement());
}
@Test
@jug.TestName("Extra number between 0 and array.size gives correct answer")
public void testOrder6() {
org.junit.Assert.assertEquals("Ed",game.order(people,4).last().getElement());
}
}
| 1,558 | 0.698973 | 0.681643 | 61 | 24.540983 | 27.41519 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.47541 | false | false |
10
|
178bc237f677126667f99d9d9f0588930a3e0d1b
| 20,555,713,481,207 |
2c319d505e8f6a21708be831e9b5426aaa86d61e
|
/oauth2/server/src/main/java/leap/oauth2/server/endpoint/token/AbstractGrantTypeHandler.java
|
36376d28f30c0c3301b0912f683569d3d3ec2059
|
[
"Apache-2.0"
] |
permissive
|
leapframework/framework
|
https://github.com/leapframework/framework
|
ed0584a1468288b3a6af83c1923fad2fd228a952
|
0703acbc0e246519ee50aa9957f68d931fab10c5
|
refs/heads/dev
| 2023-08-17T02:14:02.236000 | 2023-08-01T09:39:07 | 2023-08-01T09:39:07 | 48,562,236 | 47 | 23 |
Apache-2.0
| false | 2022-12-14T20:36:57 | 2015-12-25T01:54:52 | 2022-01-05T10:07:18 | 2022-12-14T20:36:54 | 16,207 | 43 | 19 | 12 |
Java
| false | false |
/*
* Copyright 2015 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
*
* 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 leap.oauth2.server.endpoint.token;
import leap.core.annotation.Inject;
import leap.core.i18n.MessageKey;
import leap.lang.NamedError;
import leap.lang.Strings;
import leap.lang.codec.Base64;
import leap.lang.http.HTTP;
import leap.oauth2.server.*;
import leap.oauth2.server.client.*;
import leap.web.Request;
import leap.web.Response;
import java.util.function.Function;
import static leap.oauth2.server.Oauth2MessageKey.*;
public abstract class AbstractGrantTypeHandler implements GrantTypeHandler {
protected @Inject OAuth2AuthzServerConfig config;
protected @Inject AuthzClientManager clientManager;
protected @Inject GrantTypeHandleFailHandler[] failHandlers;
protected AuthzClient validateClient(Request request, Response response, OAuth2Params params, AuthzClientCredentials credentials) throws Throwable {
String clientId = credentials.getClientId();
if (Strings.isEmpty(clientId)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id required"),
INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
String redirectUri = params.getRedirectUri();
if (Strings.isEmpty(redirectUri)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "redirect_uri required"), INVALID_REQUEST_REDIRECT_URI_REQUIRED));
return null;
}
String clientSecret = credentials.getClientSecret();
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret required"), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
AuthzClient client = clientManager.loadClientById(credentials.getClientId());
if (client == null) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidClientError(request, key, "client not found"), ERROR_INVALID_GRANT_CLIENT_NOT_FOUND));
return null;
}
if (!client.acceptsRedirectUri(redirectUri)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidGrantError(request, key, "redirect_uri invalid"), ERROR_INVALID_GRANT_REDIRECT_URI_INVALID));
return null;
}
return client;
}
protected AuthzClient validateClientSecret(Request request, Response response, AuthzClientCredentials credentials) throws Throwable {
String clientId = credentials.getClientId();
if (Strings.isEmpty(clientId)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id required"), INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
String clientSecret = credentials.getClientSecret();
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret required"), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
AuthzClientAuthenticationContext context = new DefaultAuthzClientAuthenticationContext(request, response);
AuthzClient client = clientManager.authenticate(context, credentials);
if (!context.errors().isEmpty()) {
NamedError error = context.errors().first();
handleError(request, response, new RequestOAuth2Params(request), getOauth2Error(key -> OAuth2ErrorBuilder.createUnauthorized()
.withError(error.getCode())
.withErrorDescription(error.getMessage())
.withMessageKey(key)
.build(),
error.getName()));
return null;
}
return client;
}
protected AuthzClientCredentials extractClientCredentials(Request request, Response response, OAuth2Params params) {
String header = request.getHeader(OAuth2Constants.TOKEN_HEADER);
if (header != null && !Strings.isEmpty(header)) {
if (!header.startsWith(OAuth2Constants.BASIC_TYPE)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "invalid Authorization header."), INVALID_REQUEST_INVALID_AUTHZ_HEADER));
return null;
}
String base64Token = Strings.trim(header.substring(OAuth2Constants.BASIC_TYPE.length()));
String token = Base64.decode(base64Token);
String[] idAndSecret = Strings.split(token, ":");
if (idAndSecret.length != 2) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "invalid Authorization header."), INVALID_REQUEST_INVALID_AUTHZ_HEADER));
return null;
}
return new SamplingAuthzClientCredentials(idAndSecret[0], idAndSecret[1]);
}
String clientId = params.getClientId();
String clientSecret = params.getClientSecret();
if (Strings.isEmpty(clientId)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id is required."), INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret is required."), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
return new SamplingAuthzClientCredentials(clientId, clientSecret);
}
protected void handleError(Request request, Response response, OAuth2Params params, OAuth2Error error) {
if (!handleFail(request, response, params, error)) {
OAuth2Errors.response(response, error);
}
}
protected OAuth2Error getOauth2Error(Function<MessageKey, OAuth2Error> function, String messageKey, Object... args) {
MessageKey key = Oauth2MessageKey.getMessageKey(messageKey, args);
return function.apply(key);
}
@Override
public boolean handleFail(Request request, Response response, OAuth2Params params, OAuth2Error error) {
for(GrantTypeHandleFailHandler h : failHandlers) {
if (h.handle(request, response, params, error, this)) {
return true;
}
}
return false;
}
}
|
UTF-8
|
Java
| 7,701 |
java
|
AbstractGrantTypeHandler.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2015 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
*
* 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 leap.oauth2.server.endpoint.token;
import leap.core.annotation.Inject;
import leap.core.i18n.MessageKey;
import leap.lang.NamedError;
import leap.lang.Strings;
import leap.lang.codec.Base64;
import leap.lang.http.HTTP;
import leap.oauth2.server.*;
import leap.oauth2.server.client.*;
import leap.web.Request;
import leap.web.Response;
import java.util.function.Function;
import static leap.oauth2.server.Oauth2MessageKey.*;
public abstract class AbstractGrantTypeHandler implements GrantTypeHandler {
protected @Inject OAuth2AuthzServerConfig config;
protected @Inject AuthzClientManager clientManager;
protected @Inject GrantTypeHandleFailHandler[] failHandlers;
protected AuthzClient validateClient(Request request, Response response, OAuth2Params params, AuthzClientCredentials credentials) throws Throwable {
String clientId = credentials.getClientId();
if (Strings.isEmpty(clientId)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id required"),
INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
String redirectUri = params.getRedirectUri();
if (Strings.isEmpty(redirectUri)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "redirect_uri required"), INVALID_REQUEST_REDIRECT_URI_REQUIRED));
return null;
}
String clientSecret = credentials.getClientSecret();
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret required"), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
AuthzClient client = clientManager.loadClientById(credentials.getClientId());
if (client == null) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidClientError(request, key, "client not found"), ERROR_INVALID_GRANT_CLIENT_NOT_FOUND));
return null;
}
if (!client.acceptsRedirectUri(redirectUri)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidGrantError(request, key, "redirect_uri invalid"), ERROR_INVALID_GRANT_REDIRECT_URI_INVALID));
return null;
}
return client;
}
protected AuthzClient validateClientSecret(Request request, Response response, AuthzClientCredentials credentials) throws Throwable {
String clientId = credentials.getClientId();
if (Strings.isEmpty(clientId)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id required"), INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
String clientSecret = credentials.getClientSecret();
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, new RequestOAuth2Params(request),
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret required"), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
AuthzClientAuthenticationContext context = new DefaultAuthzClientAuthenticationContext(request, response);
AuthzClient client = clientManager.authenticate(context, credentials);
if (!context.errors().isEmpty()) {
NamedError error = context.errors().first();
handleError(request, response, new RequestOAuth2Params(request), getOauth2Error(key -> OAuth2ErrorBuilder.createUnauthorized()
.withError(error.getCode())
.withErrorDescription(error.getMessage())
.withMessageKey(key)
.build(),
error.getName()));
return null;
}
return client;
}
protected AuthzClientCredentials extractClientCredentials(Request request, Response response, OAuth2Params params) {
String header = request.getHeader(OAuth2Constants.TOKEN_HEADER);
if (header != null && !Strings.isEmpty(header)) {
if (!header.startsWith(OAuth2Constants.BASIC_TYPE)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "invalid Authorization header."), INVALID_REQUEST_INVALID_AUTHZ_HEADER));
return null;
}
String base64Token = Strings.trim(header.substring(OAuth2Constants.BASIC_TYPE.length()));
String token = Base64.decode(base64Token);
String[] idAndSecret = Strings.split(token, ":");
if (idAndSecret.length != 2) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "invalid Authorization header."), INVALID_REQUEST_INVALID_AUTHZ_HEADER));
return null;
}
return new SamplingAuthzClientCredentials(idAndSecret[0], idAndSecret[1]);
}
String clientId = params.getClientId();
String clientSecret = params.getClientSecret();
if (Strings.isEmpty(clientId)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_id is required."), INVALID_REQUEST_CLIENT_ID_REQUIRED));
return null;
}
if (Strings.isEmpty(clientSecret)) {
handleError(request, response, params,
getOauth2Error(key -> OAuth2Errors.invalidRequestError(request, key, "client_secret is required."), INVALID_REQUEST_CLIENT_SECRET_REQUIRED));
return null;
}
return new SamplingAuthzClientCredentials(clientId, clientSecret);
}
protected void handleError(Request request, Response response, OAuth2Params params, OAuth2Error error) {
if (!handleFail(request, response, params, error)) {
OAuth2Errors.response(response, error);
}
}
protected OAuth2Error getOauth2Error(Function<MessageKey, OAuth2Error> function, String messageKey, Object... args) {
MessageKey key = Oauth2MessageKey.getMessageKey(messageKey, args);
return function.apply(key);
}
@Override
public boolean handleFail(Request request, Response response, OAuth2Params params, OAuth2Error error) {
for(GrantTypeHandleFailHandler h : failHandlers) {
if (h.handle(request, response, params, error, this)) {
return true;
}
}
return false;
}
}
| 7,701 | 0.668355 | 0.658875 | 159 | 47.433964 | 42.824127 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.062893 | false | false |
10
|
888f543607c75902ea27127efd7b0d960a0c83aa
| 14,456,859,944,903 |
dad59829613bf8ac9f84eb5a96223fabf26e3345
|
/src/main/java/com/kfa/bank/dao/CustomFileDao.java
|
e59e974d05f64d73ea6268cc65be3e87fe8a2b45
|
[] |
no_license
|
Karl911/Spring-projects
|
https://github.com/Karl911/Spring-projects
|
a213bbaed8120dd867f558169da7b5eca0b0ae16
|
a50ae4eefcdd56d9a2a5b6717f3a746d53e899b0
|
refs/heads/master
| 2021-04-15T18:51:26.871000 | 2020-04-30T02:05:50 | 2020-04-30T02:05:50 | 126,370,552 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kfa.bank.dao;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.kfa.bank.entity.CustomFile;
import com.kfa.bank.exception.CustomFileTransactionException;
import com.kfa.bank.model.CustomFileInfo;
@Repository
public class CustomFileDao {
@Autowired
private EntityManager entityManager;
public CustomFileDao () {
}
public CustomFile findById(Long id)
{
return this.entityManager.find(CustomFile.class, id);
}
public List<CustomFileInfo> getFiles() {
String sql = "Select new " + CustomFileInfo.class.getName() //
+ "(e.id,e.filename,e.extension, e.folderid, e.size, e.absolutepath, e.creationdate, e.updatedate) " //
+ " from " + CustomFile.class.getName() + " As e order by e.size desc";
Query query = entityManager.createQuery(sql, CustomFileInfo.class);
return query.getResultList();
}
public CustomFile findCustomFileByFolderIdAndName(int folderId, String filename) {
String sql = "SELECT f FROM CustomFile f"
+ " where f.folderid='"+ folderId+"'"
+ " and f.filename = :filename";
try {
TypedQuery<CustomFile> query = entityManager.createQuery(sql, CustomFile.class);
query.setParameter("filename", filename);
return (CustomFile) query.getSingleResult();
}
catch (NoResultException e)
{
return null;
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW,
rollbackFor = CustomFileTransactionException.class)
public void saveFile(String filename, String extension, int folderId, long size, String absolutePath, Date creationDate, Date updateDate) throws CustomFileTransactionException {
CustomFile file = new CustomFile();
file.setFilename(filename);
if (null != extension && extension.length() >3)
{
System.out.println("Warning unusual extension");
}
file.setExtension(extension);
file.setFolderId(folderId);
file.setSize(size);
file.setAbsolutepath(absolutePath);
file.setCreationdate(null);
file.setUpdatedate(null);
this.entityManager.persist(file);
//this.entityManager.flush();
}
private String escapeQuotes (String aString) {
String escapedString = aString.replaceAll("%","\"");
return escapedString;
}
}
|
UTF-8
|
Java
| 2,576 |
java
|
CustomFileDao.java
|
Java
|
[] | null |
[] |
package com.kfa.bank.dao;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.kfa.bank.entity.CustomFile;
import com.kfa.bank.exception.CustomFileTransactionException;
import com.kfa.bank.model.CustomFileInfo;
@Repository
public class CustomFileDao {
@Autowired
private EntityManager entityManager;
public CustomFileDao () {
}
public CustomFile findById(Long id)
{
return this.entityManager.find(CustomFile.class, id);
}
public List<CustomFileInfo> getFiles() {
String sql = "Select new " + CustomFileInfo.class.getName() //
+ "(e.id,e.filename,e.extension, e.folderid, e.size, e.absolutepath, e.creationdate, e.updatedate) " //
+ " from " + CustomFile.class.getName() + " As e order by e.size desc";
Query query = entityManager.createQuery(sql, CustomFileInfo.class);
return query.getResultList();
}
public CustomFile findCustomFileByFolderIdAndName(int folderId, String filename) {
String sql = "SELECT f FROM CustomFile f"
+ " where f.folderid='"+ folderId+"'"
+ " and f.filename = :filename";
try {
TypedQuery<CustomFile> query = entityManager.createQuery(sql, CustomFile.class);
query.setParameter("filename", filename);
return (CustomFile) query.getSingleResult();
}
catch (NoResultException e)
{
return null;
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW,
rollbackFor = CustomFileTransactionException.class)
public void saveFile(String filename, String extension, int folderId, long size, String absolutePath, Date creationDate, Date updateDate) throws CustomFileTransactionException {
CustomFile file = new CustomFile();
file.setFilename(filename);
if (null != extension && extension.length() >3)
{
System.out.println("Warning unusual extension");
}
file.setExtension(extension);
file.setFolderId(folderId);
file.setSize(size);
file.setAbsolutepath(absolutePath);
file.setCreationdate(null);
file.setUpdatedate(null);
this.entityManager.persist(file);
//this.entityManager.flush();
}
private String escapeQuotes (String aString) {
String escapedString = aString.replaceAll("%","\"");
return escapedString;
}
}
| 2,576 | 0.748059 | 0.747671 | 88 | 28.261364 | 29.55061 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.818182 | false | false |
10
|
88f84794f33928c5d0ce39809850855e6a2321b4
| 11,656,541,300,072 |
0c207c2c8996f9e5fd79077484858b217a22ca36
|
/day15_pattern_observer/src/main/java/com/nan/day15_pattern_observer/simple1/observer/WXUser.java
|
ae7f4e2e086ec07b417789f5589e400cd1ce3cf6
|
[] |
no_license
|
huannan/Architecture
|
https://github.com/huannan/Architecture
|
13a75919eaa2a952125aa2c5868ee17ad111b9d5
|
f41ac58b1533c75bd8945a30efd9ff23c243bfe1
|
refs/heads/master
| 2022-08-23T07:52:43.482000 | 2022-06-30T08:45:23 | 2022-06-30T08:45:23 | 292,816,424 | 11 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.nan.day15_pattern_observer.simple1.observer;
/**
* 微信公众号 - 具体订阅用户(Darren,高岩)
*/
public class WXUser implements IWXUser {
private String name;
public WXUser(String name) {
this.name = name;
}
@Override
public void push(String article) {
System.out.println(name + " 收到了一篇文章:" + article);
}
}
|
UTF-8
|
Java
| 414 |
java
|
WXUser.java
|
Java
|
[
{
"context": "erver.simple1.observer;\r\n\r\n/**\r\n * 微信公众号 - 具体订阅用户(Darren,高岩)\r\n */\r\npublic class WXUser implements IWXUser ",
"end": 89,
"score": 0.999037504196167,
"start": 83,
"tag": "NAME",
"value": "Darren"
},
{
"context": "imple1.observer;\r\n\r\n/**\r\n * 微信公众号 - 具体订阅用户(Darren,高岩)\r\n */\r\npublic class WXUser implements IWXUser {\r\n",
"end": 92,
"score": 0.9275460839271545,
"start": 90,
"tag": "NAME",
"value": "高岩"
}
] | null |
[] |
package com.nan.day15_pattern_observer.simple1.observer;
/**
* 微信公众号 - 具体订阅用户(Darren,高岩)
*/
public class WXUser implements IWXUser {
private String name;
public WXUser(String name) {
this.name = name;
}
@Override
public void push(String article) {
System.out.println(name + " 收到了一篇文章:" + article);
}
}
| 414 | 0.603825 | 0.595628 | 18 | 18.333334 | 19.186222 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false |
10
|
fdfa363b33d49419977c223a42b5228b2c8adae9
| 7,713,761,280,399 |
e79ee294843cb24ca0a37c0c29d4ad287f0020f5
|
/Poker/src/version_graphics/view/StatisticsView.java
|
5bacefe8f8fb5baf455d08a617ddc698cf542fbd
|
[] |
no_license
|
MMB360A/Poker
|
https://github.com/MMB360A/Poker
|
c18ec28f8267cad488e24d351f2c583fc5aa40f8
|
450a9df1469677dbf80e05cf80085b886611ca8d
|
refs/heads/master
| 2020-04-26T04:14:26.237000 | 2020-04-01T18:56:09 | 2020-04-01T18:56:09 | 173,295,192 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package version_graphics.view;
import java.text.DecimalFormat;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import version_graphics.PokerGame;
import version_graphics.model.HandType;
import version_graphics.model.Player;
import version_graphics.model.PokerGameModel;
import version_graphics.view.MultiLang.MultiLangModule;
/**
* Shows detail statistics in a popup view
* @author mibe1
*
*/
public class StatisticsView extends Stage{
public StatisticsView(PokerGameModel model) {
super();
//Root element
TabPane pane = new TabPane();
pane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
if(PokerGame.numberOfGames > 0) {
//Winners statistic with Pie Chart
Tab players = new Tab(PokerGame.MULTILANGMODULE.getTranslation("player"));
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
for(Player p : model.getPlayers()) {
PieChart.Data data = new PieChart.Data(p.getPlayerName() + ": " + p.getTotalWinns() + " Wins", p.getTotalWinns());
pieChartData.add(data);
}
final PieChart chart = new PieChart(pieChartData);
chart.setTitle(PokerGame.MULTILANGMODULE.getTranslation("player"));
players.setContent(chart);
//Hands statistic with BarChart
Tab hands = new Tab(PokerGame.MULTILANGMODULE.getTranslation("hands"));
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
bc.setTitle(PokerGame.MULTILANGMODULE.getTranslation("hands"));
XYChart.Series seriesHand = new XYChart.Series();
seriesHand.setName(PokerGame.MULTILANGMODULE.getTranslation("hands"));
for(HandType h : HandType.values()) {
seriesHand.getData().add(new XYChart.Data(h.name() + ": " + h.getStatisticNumber(), h.getStatisticNumber()));
}
bc.getData().add(seriesHand);
hands.setContent(bc);
//Add all statistics to the TabPane
pane.getTabs().addAll(players, hands);
}
Scene scene = new Scene(pane, 750, 400);
//Set CSS Class
if(PokerGameView.darkthem) scene.getStylesheets().add(getClass().getResource("css\\statisticsDark.css").toExternalForm());
else scene.getStylesheets().add(getClass().getResource("css\\statisticsLight.css").toExternalForm());
this.setTitle(PokerGame.MULTILANGMODULE.getTranslation("statistics"));
this.setScene(scene);
// Specifies the modality for new window.
this.initModality(Modality.WINDOW_MODAL);
}
}
|
UTF-8
|
Java
| 3,208 |
java
|
StatisticsView.java
|
Java
|
[
{
"context": "Shows detail statistics in a popup view\n * @author mibe1\n *\n */\npublic class StatisticsView extends Stage{",
"end": 1030,
"score": 0.9996175765991211,
"start": 1025,
"tag": "USERNAME",
"value": "mibe1"
}
] | null |
[] |
package version_graphics.view;
import java.text.DecimalFormat;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TabPane.TabClosingPolicy;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import version_graphics.PokerGame;
import version_graphics.model.HandType;
import version_graphics.model.Player;
import version_graphics.model.PokerGameModel;
import version_graphics.view.MultiLang.MultiLangModule;
/**
* Shows detail statistics in a popup view
* @author mibe1
*
*/
public class StatisticsView extends Stage{
public StatisticsView(PokerGameModel model) {
super();
//Root element
TabPane pane = new TabPane();
pane.setTabClosingPolicy(TabClosingPolicy.UNAVAILABLE);
if(PokerGame.numberOfGames > 0) {
//Winners statistic with Pie Chart
Tab players = new Tab(PokerGame.MULTILANGMODULE.getTranslation("player"));
ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
for(Player p : model.getPlayers()) {
PieChart.Data data = new PieChart.Data(p.getPlayerName() + ": " + p.getTotalWinns() + " Wins", p.getTotalWinns());
pieChartData.add(data);
}
final PieChart chart = new PieChart(pieChartData);
chart.setTitle(PokerGame.MULTILANGMODULE.getTranslation("player"));
players.setContent(chart);
//Hands statistic with BarChart
Tab hands = new Tab(PokerGame.MULTILANGMODULE.getTranslation("hands"));
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis();
BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
bc.setTitle(PokerGame.MULTILANGMODULE.getTranslation("hands"));
XYChart.Series seriesHand = new XYChart.Series();
seriesHand.setName(PokerGame.MULTILANGMODULE.getTranslation("hands"));
for(HandType h : HandType.values()) {
seriesHand.getData().add(new XYChart.Data(h.name() + ": " + h.getStatisticNumber(), h.getStatisticNumber()));
}
bc.getData().add(seriesHand);
hands.setContent(bc);
//Add all statistics to the TabPane
pane.getTabs().addAll(players, hands);
}
Scene scene = new Scene(pane, 750, 400);
//Set CSS Class
if(PokerGameView.darkthem) scene.getStylesheets().add(getClass().getResource("css\\statisticsDark.css").toExternalForm());
else scene.getStylesheets().add(getClass().getResource("css\\statisticsLight.css").toExternalForm());
this.setTitle(PokerGame.MULTILANGMODULE.getTranslation("statistics"));
this.setScene(scene);
// Specifies the modality for new window.
this.initModality(Modality.WINDOW_MODAL);
}
}
| 3,208 | 0.735037 | 0.732544 | 79 | 39.607594 | 27.618292 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.101266 | false | false |
10
|
891d701da6170af4a617837f1324055b1accdd63
| 23,622,320,158,473 |
e9a14a21652996674e651bdb86c81152694e9773
|
/Basics/src/arbitrMeth/ArbithMethodTest.java
|
995dbd5be215af05d7b31f95c09e62ce531d1486
|
[] |
no_license
|
SarcasticNickname/LearningJava
|
https://github.com/SarcasticNickname/LearningJava
|
00ff4bca976eaf4392ec010873924eef0835fa7f
|
e63468a16d6a259de295a85b1a9f61e44ae7dea6
|
refs/heads/main
| 2023-06-17T18:57:13.323000 | 2021-07-08T17:03:27 | 2021-07-08T17:03:27 | 372,636,271 | 1 | 0 | null | false | 2021-07-08T17:03:28 | 2021-05-31T21:50:15 | 2021-07-01T19:13:29 | 2021-07-08T17:03:27 | 25 | 0 | 0 | 0 |
Java
| false | false |
package arbitrMeth;
public class ArbithMethodTest {
static void printMany(String ...strings) {
for(String word: strings) {
System.out.println(word);
}
}
public static void main(String[] args) {
printMany("Ikotika","Sokol","CutTheCrap");
}
}
|
UTF-8
|
Java
| 274 |
java
|
ArbithMethodTest.java
|
Java
|
[] | null |
[] |
package arbitrMeth;
public class ArbithMethodTest {
static void printMany(String ...strings) {
for(String word: strings) {
System.out.println(word);
}
}
public static void main(String[] args) {
printMany("Ikotika","Sokol","CutTheCrap");
}
}
| 274 | 0.645985 | 0.645985 | 15 | 16.266666 | 17.249025 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.266667 | false | false |
10
|
07f992a37bf26551a4948d24d1928558c0d76851
| 27,144,193,368,074 |
f899a0bffbe7018c4dccb5674b357db387a7d11b
|
/src/test/java/io/github/loustler/algorithm/FibonacciTest.java
|
ccf9a3233cc8b2feaf5ef31d15b1325287d24c3b
|
[
"Apache-2.0"
] |
permissive
|
loustler/algorithm-dst-java
|
https://github.com/loustler/algorithm-dst-java
|
07c546ca1d7409504b3d6f4e2e59ff706a15baf7
|
40edbc02d8f3aedd83b0fc156e02b9588bee3972
|
refs/heads/master
| 2017-11-04T17:29:46.283000 | 2017-07-13T17:44:48 | 2017-07-13T17:44:51 | 94,910,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.github.loustler.algorithm;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author loustler
* @since 07/12/2017 00:18
*/
public class FibonacciTest {
@Test
public void oneFibonacciShouldBeOne() {
final int n = 1;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 1);
}
@Test
public void fiveFibonacciShouldBeFive() {
final int n = 5;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 5);
}
@Test
public void tenFibonacciShouldBeFifyFive() {
final int n = 10;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 55);
}
@Test
public void twentyFibonacciShouldBe6765() {
final int n = 20;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 6765);
}
}
|
UTF-8
|
Java
| 859 |
java
|
FibonacciTest.java
|
Java
|
[
{
"context": "package io.github.loustler.algorithm;\n\nimport org.junit.Test;\n\nimport sta",
"end": 23,
"score": 0.8729531764984131,
"start": 18,
"tag": "USERNAME",
"value": "loust"
},
{
"context": "tic org.junit.Assert.assertEquals;\n\n/**\n * @author loustler\n * @since 07/12/2017 00:18\n */\npublic class Fibon",
"end": 132,
"score": 0.9996325969696045,
"start": 124,
"tag": "USERNAME",
"value": "loustler"
}
] | null |
[] |
package io.github.loustler.algorithm;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author loustler
* @since 07/12/2017 00:18
*/
public class FibonacciTest {
@Test
public void oneFibonacciShouldBeOne() {
final int n = 1;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 1);
}
@Test
public void fiveFibonacciShouldBeFive() {
final int n = 5;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 5);
}
@Test
public void tenFibonacciShouldBeFifyFive() {
final int n = 10;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 55);
}
@Test
public void twentyFibonacciShouldBe6765() {
final int n = 20;
final int result = Fibonacci.fibonacci(n);
assertEquals(result, 6765);
}
}
| 859 | 0.647264 | 0.61234 | 43 | 18.976744 | 17.771793 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44186 | false | false |
10
|
01378f7c83f528d67cad529b43f58414fda9b211
| 25,829,933,335,721 |
a6c05ba97b20e1446eb882bca4c9bc3ac3f3cf74
|
/src/main/java/io/cfapps/shoppinglist/domain/ShoppingList.java
|
24f1d73d74fb3831f39be266a11bec7c26e4e9d3
|
[] |
no_license
|
david-deck/shoppinglist
|
https://github.com/david-deck/shoppinglist
|
88a6062c8b173437f6fcf77a347ab8ad0656812f
|
1412f2bfd67fccace4c5e0f372230cfb76757904
|
refs/heads/master
| 2019-03-12T18:33:35.828000 | 2019-02-09T16:02:03 | 2019-02-09T16:02:03 | 13,602,382 | 0 | 0 | null | false | 2014-02-19T19:46:19 | 2013-10-15T21:11:35 | 2014-02-19T19:46:19 | 2014-02-19T19:46:19 | 624 | 0 | 0 | 0 |
Java
| null | null |
package io.cfapps.shoppinglist.domain;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Future;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.json.RooJson;
@RooJavaBean
@RooToString
@RooJpaActiveRecord
@RooJson
public class ShoppingList extends AbstractNamedEntity {
/**
*/
@Future
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm")
private Date dueDate;
}
|
UTF-8
|
Java
| 741 |
java
|
ShoppingList.java
|
Java
|
[] | null |
[] |
package io.cfapps.shoppinglist.domain;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Future;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.json.RooJson;
@RooJavaBean
@RooToString
@RooJpaActiveRecord
@RooJson
public class ShoppingList extends AbstractNamedEntity {
/**
*/
@Future
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm")
private Date dueDate;
}
| 741 | 0.808367 | 0.808367 | 24 | 29.875 | 21.858089 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false |
10
|
fbc32339a7fa2063826b7de107671c0808037e01
| 27,633,819,610,632 |
16183aaf8b45c69b5b0979a59c4d6e869e94d64a
|
/src/Produto.java
|
70b3e576ee1fbe80b32f0f8d556c25d885ad9dc9
|
[] |
no_license
|
pablomariz/TarefaConstrutor
|
https://github.com/pablomariz/TarefaConstrutor
|
3b77e7f7b5fc3fa53e7b374fe059969e72d8c7a2
|
b602d6431b96fceefd2553e1f57cc6cb00636694
|
refs/heads/master
| 2020-07-31T19:04:37.017000 | 2019-09-25T00:43:30 | 2019-09-25T00:43:30 | 210,721,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Produto {
private String nome;
private double preco;
public Produto(String n, double p){
this.setNome(n);
this.setPreco(p);
}
public String getNome(){
return this.nome;
}
public void setNome(String n) {
this.nome = n;
}
public double getPreco(){
return this.preco;
}
public void setPreco(double p) {
this.preco = p;
}
public double diminuir10(){
double desconto = this.preco - (this.preco * 0.1);
return desconto;
}
public double aumenta25(){
double aumento = this.preco + (this.preco * 0.25);
return aumento;
}
}
|
UTF-8
|
Java
| 751 |
java
|
Produto.java
|
Java
|
[] | null |
[] |
public class Produto {
private String nome;
private double preco;
public Produto(String n, double p){
this.setNome(n);
this.setPreco(p);
}
public String getNome(){
return this.nome;
}
public void setNome(String n) {
this.nome = n;
}
public double getPreco(){
return this.preco;
}
public void setPreco(double p) {
this.preco = p;
}
public double diminuir10(){
double desconto = this.preco - (this.preco * 0.1);
return desconto;
}
public double aumenta25(){
double aumento = this.preco + (this.preco * 0.25);
return aumento;
}
}
| 751 | 0.50466 | 0.492676 | 37 | 18.351351 | 15.157224 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.351351 | false | false |
10
|
df1df54bfc13ef7b1826e1bb96229c2a6512cb76
| 6,502,580,510,904 |
b0041ebe5bc592e2f9e67023b5956a11e96ae0c1
|
/array/Array01.java
|
c1b148521ae22a7a86004d7c7428a576a6d3d524
|
[] |
no_license
|
saniyat013/data-structures-101
|
https://github.com/saniyat013/data-structures-101
|
eeeaa86cba7b73fd1f2599d938be19236b0cc702
|
3be3b6a15b3b0e9eea9022ca76bccc2de6454aeb
|
refs/heads/master
| 2023-03-02T20:07:43.969000 | 2021-02-09T11:47:08 | 2021-02-09T11:47:08 | 325,786,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package array;
import java.util.ArrayList;
public class Array01 {
public static void main(String[] args) {
// int expenses[] = new int[5];
ArrayList<Integer> expenses = new ArrayList();
expenses.add(2200);
expenses.add(2350);
expenses.add(2600);
expenses.add(2130);
expenses.add(2190);
// 1. In Feb, how many dollars you spent extra compare to January?
System.out.println("Spent extra in February compare to January: " + (expenses.get(1) - expenses.get(0)));
// Find out your total expense in first quarter (first three months) of the year.
System.out.println("Total expense in first quarter (first three months): " + (expenses.get(0) + expenses.get(1) + expenses.get(2)));
// Find out if you spent exactly 2000 dollars in any month
System.out.println("Spent exactly 2000 dollars in any month?");
System.out.print("Ans: ");
int count = 0;
for(int x : expenses) {
if(x == 2000) {
count++;
}
}
if(count > 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
// June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list
expenses.add(1980);
System.out.println("Expense in June: " + expenses.get(5));
/*You returned an item that you bought in a month of April and got a refund of 200$.
Make a correction to your monthly expense list based on this*/
expenses.set(3, (expenses.get(3) - 200));
System.out.println("Updated expense in April: " + expenses.get(3));
System.out.println("Whole Array Now:");
for(int x : expenses) {
System.out.print(x + " ");
}
}
}
|
UTF-8
|
Java
| 1,893 |
java
|
Array01.java
|
Java
|
[] | null |
[] |
package array;
import java.util.ArrayList;
public class Array01 {
public static void main(String[] args) {
// int expenses[] = new int[5];
ArrayList<Integer> expenses = new ArrayList();
expenses.add(2200);
expenses.add(2350);
expenses.add(2600);
expenses.add(2130);
expenses.add(2190);
// 1. In Feb, how many dollars you spent extra compare to January?
System.out.println("Spent extra in February compare to January: " + (expenses.get(1) - expenses.get(0)));
// Find out your total expense in first quarter (first three months) of the year.
System.out.println("Total expense in first quarter (first three months): " + (expenses.get(0) + expenses.get(1) + expenses.get(2)));
// Find out if you spent exactly 2000 dollars in any month
System.out.println("Spent exactly 2000 dollars in any month?");
System.out.print("Ans: ");
int count = 0;
for(int x : expenses) {
if(x == 2000) {
count++;
}
}
if(count > 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
// June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list
expenses.add(1980);
System.out.println("Expense in June: " + expenses.get(5));
/*You returned an item that you bought in a month of April and got a refund of 200$.
Make a correction to your monthly expense list based on this*/
expenses.set(3, (expenses.get(3) - 200));
System.out.println("Updated expense in April: " + expenses.get(3));
System.out.println("Whole Array Now:");
for(int x : expenses) {
System.out.print(x + " ");
}
}
}
| 1,893 | 0.567353 | 0.535129 | 51 | 36.117645 | 31.588436 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490196 | false | false |
10
|
c22c7b08758de5d78b5cb54266ed59953aedd0ea
| 5,858,335,402,499 |
23b9b5fece05bc97f34ca1651412159ea0bad020
|
/src/com/codepath/hughhn/instagramviewer/InstagramPhoto.java
|
334c8c4d365d098187f82b438b66ede11f2cce56
|
[] |
no_license
|
hugohn/instagramviewer
|
https://github.com/hugohn/instagramviewer
|
0740e80dc365c33c61718be6eb925465c9f0eb60
|
bcd781bc77024b14026ee0576da76e66fa343d6a
|
refs/heads/master
| 2021-01-22T00:29:02.001000 | 2014-09-17T22:14:07 | 2014-09-17T22:14:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.codepath.hughhn.instagramviewer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InstagramPhoto {
// username, caption, image_url, height, likes_count
public String username;
public String profileImgUrl;
public String caption;
public String imageUrl;
public int imageHeight;
public int imageWidth;
public int likes_count;
public long created_time;
public ArrayList<PhotoComment> comments;
public InstagramPhoto(JSONObject photoJSON) {
try {
JSONArray commentsJSON = null;
username = photoJSON.getJSONObject("user").getString("username");
profileImgUrl = photoJSON.getJSONObject("user").getString(
"profile_picture");
if (photoJSON.optJSONObject("caption") != null) {
caption = photoJSON.getJSONObject("caption").getString("text");
}
imageUrl = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getString("url");
imageHeight = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getInt("height");
imageWidth = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getInt("width");
likes_count = photoJSON.getJSONObject("likes").getInt("count");
created_time = photoJSON.getLong("created_time");
commentsJSON = photoJSON.getJSONObject("comments").getJSONArray(
"data");
if (commentsJSON != null) {
comments = new ArrayList<PhotoComment>();
for (int j = 0; j < commentsJSON.length(); j++) {
JSONObject comment = commentsJSON.getJSONObject(j);
PhotoComment cmt = new PhotoComment();
cmt.text = comment.getString("text");
cmt.username = comment.getJSONObject("from").getString(
"username");
cmt.profileImgUrl = comment.getJSONObject("from")
.getString("profile_picture");
comments.add(cmt);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,952 |
java
|
InstagramPhoto.java
|
Java
|
[
{
"context": "name = photoJSON.getJSONObject(\"user\").getString(\"username\");\n\t\t\tprofileImgUrl = photoJSON.getJSONObject(\"us",
"end": 649,
"score": 0.9568977355957031,
"start": 641,
"tag": "USERNAME",
"value": "username"
},
{
"context": " comment.getJSONObject(\"from\").getString(\n\t\t\t\t\t\t\t\"username\");\n\t\t\t\t\tcmt.profileImgUrl = comment.getJSONObject",
"end": 1753,
"score": 0.9904459714889526,
"start": 1745,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.codepath.hughhn.instagramviewer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InstagramPhoto {
// username, caption, image_url, height, likes_count
public String username;
public String profileImgUrl;
public String caption;
public String imageUrl;
public int imageHeight;
public int imageWidth;
public int likes_count;
public long created_time;
public ArrayList<PhotoComment> comments;
public InstagramPhoto(JSONObject photoJSON) {
try {
JSONArray commentsJSON = null;
username = photoJSON.getJSONObject("user").getString("username");
profileImgUrl = photoJSON.getJSONObject("user").getString(
"profile_picture");
if (photoJSON.optJSONObject("caption") != null) {
caption = photoJSON.getJSONObject("caption").getString("text");
}
imageUrl = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getString("url");
imageHeight = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getInt("height");
imageWidth = photoJSON.getJSONObject("images")
.getJSONObject("standard_resolution").getInt("width");
likes_count = photoJSON.getJSONObject("likes").getInt("count");
created_time = photoJSON.getLong("created_time");
commentsJSON = photoJSON.getJSONObject("comments").getJSONArray(
"data");
if (commentsJSON != null) {
comments = new ArrayList<PhotoComment>();
for (int j = 0; j < commentsJSON.length(); j++) {
JSONObject comment = commentsJSON.getJSONObject(j);
PhotoComment cmt = new PhotoComment();
cmt.text = comment.getString("text");
cmt.username = comment.getJSONObject("from").getString(
"username");
cmt.profileImgUrl = comment.getJSONObject("from")
.getString("profile_picture");
comments.add(cmt);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
| 1,952 | 0.710041 | 0.709529 | 62 | 30.483871 | 21.644297 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.983871 | false | false |
10
|
b879863dc7283be08bd8c5651303dbe76513fc55
| 5,858,335,402,313 |
8d06854afacfe340ec03627685f2ebb4c8f8defe
|
/uc/uc-ms/src/main/java/com/letv/uc/ms/controller/IndexController.java
|
d670a03a576740d8d40bd5e13692ab6b4687245b
|
[] |
no_license
|
mad3310/matrix-vm-portal-uc
|
https://github.com/mad3310/matrix-vm-portal-uc
|
8b5ff27c02d1dbb0e48761782b727f3f12b22208
|
77cf094bcd42d76bd9b40a3943f47481610d6317
|
refs/heads/master
| 2021-06-28T13:34:05.526000 | 2017-09-17T18:43:52 | 2017-09-17T18:43:52 | 103,850,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.letv.uc.ms.controller;
import com.letvcloud.saas.util.session.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* index页面和登陆页面controller
*
* @author liufengyu
* @date 2014年4月15日
*/
@Controller
@RequestMapping(value = "/*")
public class IndexController {
@Autowired
private SessionProvider sessionProvider;
/**
* 进入index页面
*
* @param request request
* @return
* @author fangqi
* @date 2012-9-25
*/
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("index");
// 设置session不过期
modelAndView.addObject("userName", sessionProvider.getAttribute(request, "userName"));
modelAndView.addObject("tel", sessionProvider.getAttribute(request, "tel"));
modelAndView.addObject("userId", sessionProvider.getAttribute(request, "userId"));
return modelAndView;
}
}
|
UTF-8
|
Java
| 1,341 |
java
|
IndexController.java
|
Java
|
[
{
"context": "uest;\n\n/**\n * index页面和登陆页面controller\n *\n * @author liufengyu\n * @date 2014年4月15日\n */\n@Controller\n@RequestMappi",
"end": 484,
"score": 0.9959148168563843,
"start": 475,
"tag": "USERNAME",
"value": "liufengyu"
},
{
"context": "aram request request\n * @return\n * @author fangqi\n * @date 2012-9-25\n */\n @RequestMappin",
"end": 741,
"score": 0.993889331817627,
"start": 735,
"tag": "USERNAME",
"value": "fangqi"
},
{
"context": "userName\", sessionProvider.getAttribute(request, \"userName\"));\n modelAndView.addObject(\"tel\", session",
"end": 1084,
"score": 0.9943496584892273,
"start": 1076,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.letv.uc.ms.controller;
import com.letvcloud.saas.util.session.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* index页面和登陆页面controller
*
* @author liufengyu
* @date 2014年4月15日
*/
@Controller
@RequestMapping(value = "/*")
public class IndexController {
@Autowired
private SessionProvider sessionProvider;
/**
* 进入index页面
*
* @param request request
* @return
* @author fangqi
* @date 2012-9-25
*/
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("index");
// 设置session不过期
modelAndView.addObject("userName", sessionProvider.getAttribute(request, "userName"));
modelAndView.addObject("tel", sessionProvider.getAttribute(request, "tel"));
modelAndView.addObject("userId", sessionProvider.getAttribute(request, "userId"));
return modelAndView;
}
}
| 1,341 | 0.726017 | 0.715272 | 43 | 29.302326 | 27.019833 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511628 | false | false |
10
|
ae69069332dacfc57609971cea19fabb86974677
| 29,901,562,375,129 |
636c9ff0ba899a890c9a99cd0d007624e506bf22
|
/server/src/main/java/org/jesko/picture/sucker/upload/UploadController.java
|
f7656eec6588832133e52db65c0f5f1256c79661
|
[] |
no_license
|
jeske717/wifi-picture-pusher
|
https://github.com/jeske717/wifi-picture-pusher
|
5d68779ec1c3fe6ace2cd5bd85ef1deb55c390ad
|
fd4abd97417e59c51863663aa92cd8824402e6cd
|
refs/heads/master
| 2020-11-26T14:06:25.056000 | 2013-02-15T01:48:10 | 2013-02-15T01:48:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.jesko.picture.sucker.upload;
import java.io.IOException;
import javax.inject.Inject;
import org.jesko.picture.pusher.beans.UploadResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@Inject
private UploadService uploadService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody UploadResult uploadImage(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
uploadService.saveFile(file);
UploadResult uploadResult = new UploadResult();
uploadResult.setResult("SUCCESS");
return uploadResult;
}
}
|
UTF-8
|
Java
| 945 |
java
|
UploadController.java
|
Java
|
[] | null |
[] |
package org.jesko.picture.sucker.upload;
import java.io.IOException;
import javax.inject.Inject;
import org.jesko.picture.pusher.beans.UploadResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadController {
@Inject
private UploadService uploadService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody UploadResult uploadImage(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
uploadService.saveFile(file);
UploadResult uploadResult = new UploadResult();
uploadResult.setResult("SUCCESS");
return uploadResult;
}
}
| 945 | 0.82328 | 0.82328 | 28 | 32.75 | 29.881462 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.107143 | false | false |
10
|
7b3123581d760df109f28c984865f125ecf496f7
| 1,795,296,360,410 |
166a99193149ffb70ed0f3c0a3aa7ecb607ba8d7
|
/src/lia/Monitor/JiniClient/CommonGUI/OSG/OSGHistoryMenu.java
|
f23e7682606af81553376c9a03f372abf0fb8ed4
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
costing/Monalisa
|
https://github.com/costing/Monalisa
|
735c99ab77a92f908564098a6474d6bb085b2e4f
|
2e4ab0fa3e198313397edb5bd1d48549ce138a25
|
refs/heads/master
| 2021-05-02T12:05:18.501000 | 2020-10-09T20:10:32 | 2020-10-09T20:10:32 | 120,735,433 | 0 | 0 | null | true | 2018-02-08T08:50:04 | 2018-02-08T08:50:04 | 2018-02-07T10:54:48 | 2018-02-07T10:54:24 | 232,464 | 0 | 0 | 0 | null | false | null |
package lia.Monitor.JiniClient.CommonGUI.OSG;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class OSGHistoryMenu extends JPanel {
static final long serialVersionUID = 2030012005L;
private OSGPanel owner;
JPanel radioPanel;
ButtonGroup group;
RadioListener myListener;
String []buttonLabel = { "Last hour", "Last 3 hours" };
long []historyTime = { 60 * 60 * 1000, 180 * 60 * 1000 };
JRadioButton []historyButton = new JRadioButton[2];
public OSGHistoryMenu(OSGPanel owner){
super();
this.owner = owner;
init();
}
public void init() {
// Group the radio buttons.
group = new ButtonGroup();
// Register a listener for the radio buttons.
myListener = new RadioListener();
// Put the radio buttons in a column in a panel.
radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.X_AXIS));
for(int i = 0; i < historyButton.length; i++){
historyButton[i] = new JRadioButton(buttonLabel[i]);
historyButton[i].setActionCommand(buttonLabel[i]);
historyButton[i].setSelected(i == 0 ? true : false);
historyButton[i].addActionListener(myListener);
group.add(historyButton[i]);
radioPanel.add(historyButton[i]);
}
add(radioPanel);
}
class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.print("ActionEvent received: ");
for(int i = 0; i < buttonLabel.length; i++){
if (e.getActionCommand() == buttonLabel[i]) {
System.out.println(buttonLabel[i] + " pressed. Setting historyTime to " + historyTime[i]);
owner.historyTime = historyTime[i];
}
}
}
}
}
|
UTF-8
|
Java
| 1,837 |
java
|
OSGHistoryMenu.java
|
Java
|
[] | null |
[] |
package lia.Monitor.JiniClient.CommonGUI.OSG;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class OSGHistoryMenu extends JPanel {
static final long serialVersionUID = 2030012005L;
private OSGPanel owner;
JPanel radioPanel;
ButtonGroup group;
RadioListener myListener;
String []buttonLabel = { "Last hour", "Last 3 hours" };
long []historyTime = { 60 * 60 * 1000, 180 * 60 * 1000 };
JRadioButton []historyButton = new JRadioButton[2];
public OSGHistoryMenu(OSGPanel owner){
super();
this.owner = owner;
init();
}
public void init() {
// Group the radio buttons.
group = new ButtonGroup();
// Register a listener for the radio buttons.
myListener = new RadioListener();
// Put the radio buttons in a column in a panel.
radioPanel = new JPanel();
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.X_AXIS));
for(int i = 0; i < historyButton.length; i++){
historyButton[i] = new JRadioButton(buttonLabel[i]);
historyButton[i].setActionCommand(buttonLabel[i]);
historyButton[i].setSelected(i == 0 ? true : false);
historyButton[i].addActionListener(myListener);
group.add(historyButton[i]);
radioPanel.add(historyButton[i]);
}
add(radioPanel);
}
class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.print("ActionEvent received: ");
for(int i = 0; i < buttonLabel.length; i++){
if (e.getActionCommand() == buttonLabel[i]) {
System.out.println(buttonLabel[i] + " pressed. Setting historyTime to " + historyTime[i]);
owner.historyTime = historyTime[i];
}
}
}
}
}
| 1,837 | 0.685901 | 0.668481 | 66 | 26.848484 | 22.38184 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.924242 | false | false |
10
|
739a8bb46449758589b22388dd26930e38f48916
| 4,999,341,981,629 |
88770006a1ef9e85011e1a5436bfd3b0145b30cd
|
/bytebank-composto/src/TestaEncapsulamento.java
|
d752a7e90d576a713c0b23d72179c2e805e05d21
|
[] |
no_license
|
kbentes/JavaSE8
|
https://github.com/kbentes/JavaSE8
|
03f3c2cafba13afafd773606895ea22d2e55083a
|
f789a2a21a4fe2d5c525d85017c9b83f79549877
|
refs/heads/master
| 2020-03-14T20:40:05.789000 | 2018-05-02T01:03:23 | 2018-05-02T01:03:23 | 131,779,619 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class TestaEncapsulamento {
public static void main(String[] args) {
Conta conta = new Conta();
conta.deposita(1000);
conta.saca(300);
System.out.println("Saldo da conta eh: " + conta.getSaldo());
//conta.saldo = 800;
}
}
|
UTF-8
|
Java
| 248 |
java
|
TestaEncapsulamento.java
|
Java
|
[] | null |
[] |
public class TestaEncapsulamento {
public static void main(String[] args) {
Conta conta = new Conta();
conta.deposita(1000);
conta.saca(300);
System.out.println("Saldo da conta eh: " + conta.getSaldo());
//conta.saldo = 800;
}
}
| 248 | 0.657258 | 0.616935 | 11 | 21.454546 | 18.773113 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.909091 | false | false |
10
|
cbf97f89cf71ca1b28ff71afc3f59884494f820c
| 4,999,341,983,259 |
7705f681ae78802194f83741e971f5a875061e47
|
/rocketmq-canal/src/main/java/com/hexun/rocketmq/canal/CanalRocketmqEntry.java
|
d495f8366af3df01d143e9182441663e07645981
|
[] |
no_license
|
xiongyanokok/rocketmq
|
https://github.com/xiongyanokok/rocketmq
|
9cbfe4a6e149d834b24f46ce941e64ff4b70fc71
|
874c97428442fe823131be4da891338ba437a547
|
refs/heads/master
| 2020-03-06T15:24:55.115000 | 2018-03-17T03:06:01 | 2018-03-17T03:06:01 | 126,955,565 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hexun.rocketmq.canal;
import java.util.ArrayList;
import java.util.List;
public class CanalRocketmqEntry {
private long executeTime;
private int entryType;
private String logFileName;
private long logFileOffset;
private int eventType;
private String schemaName;
private String tableName;
private List<List<CanalRocketmqDbColumn>> datas = new ArrayList<>();
public List<List<CanalRocketmqDbColumn>> getDatas() {
return datas;
}
public void addData(List<CanalRocketmqDbColumn> data) {
this.datas.add(data);
}
public void setExecuteTime(long executeTime) {
this.executeTime = executeTime;
}
public long getExecuteTime() {
return executeTime;
}
public void setEntryType(int entryType) {
this.entryType = entryType;
}
public int getEntryType() {
return entryType;
}
public void setLogFileName(String logFileName) {
this.logFileName = logFileName;
}
public String getLogFileName() {
return logFileName;
}
public void setLogFileOffset(long logFileOffset) {
this.logFileOffset = logFileOffset;
}
public long getLogFileOffset() {
return logFileOffset;
}
public void setEventType(int eventType) {
this.eventType = eventType;
}
public int getEventType() {
return eventType;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getSchemaName() {
return schemaName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getTableName() {
return tableName;
}
}
|
UTF-8
|
Java
| 1,743 |
java
|
CanalRocketmqEntry.java
|
Java
|
[] | null |
[] |
package com.hexun.rocketmq.canal;
import java.util.ArrayList;
import java.util.List;
public class CanalRocketmqEntry {
private long executeTime;
private int entryType;
private String logFileName;
private long logFileOffset;
private int eventType;
private String schemaName;
private String tableName;
private List<List<CanalRocketmqDbColumn>> datas = new ArrayList<>();
public List<List<CanalRocketmqDbColumn>> getDatas() {
return datas;
}
public void addData(List<CanalRocketmqDbColumn> data) {
this.datas.add(data);
}
public void setExecuteTime(long executeTime) {
this.executeTime = executeTime;
}
public long getExecuteTime() {
return executeTime;
}
public void setEntryType(int entryType) {
this.entryType = entryType;
}
public int getEntryType() {
return entryType;
}
public void setLogFileName(String logFileName) {
this.logFileName = logFileName;
}
public String getLogFileName() {
return logFileName;
}
public void setLogFileOffset(long logFileOffset) {
this.logFileOffset = logFileOffset;
}
public long getLogFileOffset() {
return logFileOffset;
}
public void setEventType(int eventType) {
this.eventType = eventType;
}
public int getEventType() {
return eventType;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public String getSchemaName() {
return schemaName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getTableName() {
return tableName;
}
}
| 1,743 | 0.654045 | 0.654045 | 79 | 21.063292 | 18.692949 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341772 | false | false |
10
|
ff911473a0b71d0b21931d8187f2eaa2941e01d1
| 36,971,078,522,206 |
c260c6c73d7fe0fad87b027e267f1b689c06baa0
|
/Control/Main.java
|
a17daff270cf09a4ce2036170bc7783cb89017e5
|
[] |
no_license
|
PolinaBrusova/JAVAuni
|
https://github.com/PolinaBrusova/JAVAuni
|
24ff03e133498c7d2bc6baca7211aee3c665cafa
|
b9ad38873157eea0a1769a6edbd90942d213209b
|
refs/heads/master
| 2023-04-26T08:48:17.122000 | 2021-05-17T06:54:03 | 2021-05-17T06:54:03 | 296,302,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Control;
import javax.print.DocFlavor;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Double> conts = new HashMap<>();//словарь для характеристик блюда/напитка
conts.put("Price", 340.50);
conts.put("Weight", 300.0);
Menu menu = new Menu();//открываем меню
menu.addToMenu("Оливье", conts);//добавляем блюдо с названием и характеристиками
conts.clear();
conts.put("Price", 560.90);
conts.put("Weight", 475.0);
menu.addToMenu("Ризотто с креветками", conts);
menu.show();//выводим меню на экран
menu.addToStop("Оливье");//переносим блюдо в стоп-лист
menu.show();//снова выводим меню и видим, что блюдо стоп-листа исчезло из меню
menu.removeFromStop("Оливье");//удаляем из стоп-листа
menu.show();//снова выводим меню и видим, что блюдо вернулось в меню
conts.clear();
conts.put("Price", 80.);
conts.put("Weight", 330.);
menu.addToMenu("Кока-кола", conts);
menu.show();
Table table1 = new Table("1", menu.getMenu());//открываем столик 1
Table table2 = new Table("4", menu.getMenu());//открываем столик 4
table1.addProduct("Ризотто с креветками");//первому столику заказано блюдо - добавляется в счет
table2.addProduct("Оливье");
table1.addProduct("Ризотто с креветками");
table1.addProduct("Оливье");
table1.tableInfo();//информация по текущему заказу столика
table1.FinalReceipt();//выводим счет для столика (здесь же столик закрывается
Table table3 = new Table("4", menu.getMenu());//пытаемся открыть счет на уже занятый столик
}
}
|
UTF-8
|
Java
| 2,252 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package Control;
import javax.print.DocFlavor;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Double> conts = new HashMap<>();//словарь для характеристик блюда/напитка
conts.put("Price", 340.50);
conts.put("Weight", 300.0);
Menu menu = new Menu();//открываем меню
menu.addToMenu("Оливье", conts);//добавляем блюдо с названием и характеристиками
conts.clear();
conts.put("Price", 560.90);
conts.put("Weight", 475.0);
menu.addToMenu("Ризотто с креветками", conts);
menu.show();//выводим меню на экран
menu.addToStop("Оливье");//переносим блюдо в стоп-лист
menu.show();//снова выводим меню и видим, что блюдо стоп-листа исчезло из меню
menu.removeFromStop("Оливье");//удаляем из стоп-листа
menu.show();//снова выводим меню и видим, что блюдо вернулось в меню
conts.clear();
conts.put("Price", 80.);
conts.put("Weight", 330.);
menu.addToMenu("Кока-кола", conts);
menu.show();
Table table1 = new Table("1", menu.getMenu());//открываем столик 1
Table table2 = new Table("4", menu.getMenu());//открываем столик 4
table1.addProduct("Ризотто с креветками");//первому столику заказано блюдо - добавляется в счет
table2.addProduct("Оливье");
table1.addProduct("Ризотто с креветками");
table1.addProduct("Оливье");
table1.tableInfo();//информация по текущему заказу столика
table1.FinalReceipt();//выводим счет для столика (здесь же столик закрывается
Table table3 = new Table("4", menu.getMenu());//пытаемся открыть счет на уже занятый столик
}
}
| 2,252 | 0.64294 | 0.621528 | 39 | 43.307693 | 29.567093 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.179487 | false | false |
10
|
22e13edd69947e44d953be03cd41568a0f5bef41
| 33,878,702,092,392 |
dc9cb9e11a472597b73ddd925a58ee9d331c139d
|
/src/com/company/Virazjenie.java
|
7192eeab9500c600a8a2f6e2452877bb00de7360
|
[] |
no_license
|
NeAlexei/TREN
|
https://github.com/NeAlexei/TREN
|
e85b3f8796ce0cbb29bb3f23be65d44408c73f42
|
ce5ea73c891978ac3f709ed5ad9a3afe81d0f146
|
refs/heads/master
| 2020-04-14T00:53:59.143000 | 2019-01-06T21:11:32 | 2019-01-06T21:11:32 | 163,545,633 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.company;
public class Virazjenie { //написать метод, который вычисляет выражение a*b+(c/d*e)
public int countVirazh(int a, int b, int c, int d, int e) {
int result = a * b + (c/d*e);
return result;
}
}
|
UTF-8
|
Java
| 277 |
java
|
Virazjenie.java
|
Java
|
[] | null |
[] |
package com.company;
public class Virazjenie { //написать метод, который вычисляет выражение a*b+(c/d*e)
public int countVirazh(int a, int b, int c, int d, int e) {
int result = a * b + (c/d*e);
return result;
}
}
| 277 | 0.615063 | 0.615063 | 8 | 28.875 | 28.431662 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
10
|
c3928d4ed2731457a5f0ee6cbe06eb34362b2965
| 39,582,418,607,989 |
341103418bf279a121ddb6ad8180284e0921eb03
|
/v1/WU_RAYMOND/ArrayPriorityQueue.java
|
a945edf01ba29ba00c459c180aad1eb3b36241a3
|
[] |
no_license
|
wu-rymd/MissingCurlyBracket
|
https://github.com/wu-rymd/MissingCurlyBracket
|
ba42c9c33b2b6183efe0db51abbd5477cc52b446
|
a7f59dde408af07ebfe9006ae4f614501bbc1c29
|
refs/heads/master
| 2020-03-16T19:49:38.178000 | 2018-05-18T09:54:35 | 2018-05-18T09:54:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// Raymond Wu
// APCS2 pd8
// HW46 -- Arrr, There Be Priorities Here Matey . . .
// 2018-05-10
/**
* This file will also work if we do ...
* import java.util.*;
* ... and implement the proper PriorityQueue interface ...
* ... and allow generic typing for ArrayPriorityQueue ...
* public class ArrayPriorityQueue<T> implements PriorityQueue<T>
*/
import java.util.ArrayList;
public class ArrayPriorityQueue implements PriorityQueue
{
// inst var
ArrayList<String> _data;
//constructor
public ArrayPriorityQueue()
{ _data = new ArrayList<String>(); }
//methods ... implementing PriorityQueue interface
/**
* void add(String)
* Adds an item to this priority queue
* Worst & average case O(1)
* Add to end of ArrayList
*/
public void add(String s)
{ _data.add(s); }
/**
* boolean isEmpty()
* Returns true if this stack is empty, o/w returns false
* Worst & average case O(1)
* Use ArrayList size()
*/
public boolean isEmpty()
{ return _data.size() == 0; }
/**
* boolean peekMin()
* Returns smallest item stored in PriorityQueue w/o removing it
* Worst & average case O(n)
* Iterate through APQ, return String w/ least val
*/
public String peekMin()
{
if ( isEmpty() )
{ throw new RuntimeException("PriorityQueue is empty"); }
else {
String least = _data.get(0);
for (String s : _data) {
if ( s.compareTo(least) < 0 )
least = s;
}
return least;
} // end else
}
/**
* boolean removeMin()
* Removes and returns smallest item stored in priority queue
* Worst & average case O(n)
* Iterate through APQ, return & remove String w/ least val
*/
public String removeMin()
{
if ( isEmpty() )
{ throw new RuntimeException("PriorityQueue is empty"); }
else {
String least = _data.get(0);
int index = 0;
for (int i = 0; i < _data.size(); i++) {
if ( _data.get(i).compareTo(least) < 0 )
{
least = _data.get(i);
index = i;
}
}
_data.remove(index);
return least;
} // end else
} // end class peekMin()
// for testing purposes...
public String toString() {
String retStr = "[";
for (String s : _data)
retStr += s + " ";
return retStr + "]";
}
public static void main (String[] args)
{
System.out.println("APQ instantiated...");
ArrayPriorityQueue myAPQ = new ArrayPriorityQueue();
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // true
System.out.println("adding foo...");
myAPQ.add("foo");
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // false
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [foo ]
System.out.println("adding moo...");
myAPQ.add("moo");
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // false
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [foo moo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // foo
System.out.print("removing min: ");
System.out.println( myAPQ.removeMin() ); // foo
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // moo
System.out.println("adding goo, hoo, doo...");
myAPQ.add("goo");
myAPQ.add("hoo");
myAPQ.add("doo");
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo goo hoo doo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // doo
System.out.print("removing min: ");
System.out.println( myAPQ.removeMin() ); // doo
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo goo hoo ]
} // end main method
} // end ArrayPriorityQueue class
|
UTF-8
|
Java
| 4,027 |
java
|
ArrayPriorityQueue.java
|
Java
|
[
{
"context": "// Raymond Wu\n// APCS2 pd8\n// HW46 -- Arrr, There Be Priorities",
"end": 13,
"score": 0.999820351600647,
"start": 3,
"tag": "NAME",
"value": "Raymond Wu"
}
] | null |
[] |
// <NAME>
// APCS2 pd8
// HW46 -- Arrr, There Be Priorities Here Matey . . .
// 2018-05-10
/**
* This file will also work if we do ...
* import java.util.*;
* ... and implement the proper PriorityQueue interface ...
* ... and allow generic typing for ArrayPriorityQueue ...
* public class ArrayPriorityQueue<T> implements PriorityQueue<T>
*/
import java.util.ArrayList;
public class ArrayPriorityQueue implements PriorityQueue
{
// inst var
ArrayList<String> _data;
//constructor
public ArrayPriorityQueue()
{ _data = new ArrayList<String>(); }
//methods ... implementing PriorityQueue interface
/**
* void add(String)
* Adds an item to this priority queue
* Worst & average case O(1)
* Add to end of ArrayList
*/
public void add(String s)
{ _data.add(s); }
/**
* boolean isEmpty()
* Returns true if this stack is empty, o/w returns false
* Worst & average case O(1)
* Use ArrayList size()
*/
public boolean isEmpty()
{ return _data.size() == 0; }
/**
* boolean peekMin()
* Returns smallest item stored in PriorityQueue w/o removing it
* Worst & average case O(n)
* Iterate through APQ, return String w/ least val
*/
public String peekMin()
{
if ( isEmpty() )
{ throw new RuntimeException("PriorityQueue is empty"); }
else {
String least = _data.get(0);
for (String s : _data) {
if ( s.compareTo(least) < 0 )
least = s;
}
return least;
} // end else
}
/**
* boolean removeMin()
* Removes and returns smallest item stored in priority queue
* Worst & average case O(n)
* Iterate through APQ, return & remove String w/ least val
*/
public String removeMin()
{
if ( isEmpty() )
{ throw new RuntimeException("PriorityQueue is empty"); }
else {
String least = _data.get(0);
int index = 0;
for (int i = 0; i < _data.size(); i++) {
if ( _data.get(i).compareTo(least) < 0 )
{
least = _data.get(i);
index = i;
}
}
_data.remove(index);
return least;
} // end else
} // end class peekMin()
// for testing purposes...
public String toString() {
String retStr = "[";
for (String s : _data)
retStr += s + " ";
return retStr + "]";
}
public static void main (String[] args)
{
System.out.println("APQ instantiated...");
ArrayPriorityQueue myAPQ = new ArrayPriorityQueue();
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // true
System.out.println("adding foo...");
myAPQ.add("foo");
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // false
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [foo ]
System.out.println("adding moo...");
myAPQ.add("moo");
System.out.print("is my APQ empty?: ");
System.out.println( myAPQ.isEmpty() ); // false
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [foo moo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // foo
System.out.print("removing min: ");
System.out.println( myAPQ.removeMin() ); // foo
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // moo
System.out.println("adding goo, hoo, doo...");
myAPQ.add("goo");
myAPQ.add("hoo");
myAPQ.add("doo");
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo goo hoo doo ]
System.out.print("min String now: ");
System.out.println( myAPQ.peekMin() ); // doo
System.out.print("removing min: ");
System.out.println( myAPQ.removeMin() ); // doo
System.out.print("APQ now: ");
System.out.println( myAPQ ); // [moo goo hoo ]
} // end main method
} // end ArrayPriorityQueue class
| 4,023 | 0.583809 | 0.578595 | 173 | 22.277456 | 20.117672 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.820809 | false | false |
10
|
dbc3619b1e85a2e43d2d95c33538dacfdd7f0479
| 34,230,889,410,264 |
df5ab3da87ed04d7c0354a924538fe6cb127fba8
|
/algorithms/src/main/java/algo/ch18/StringRWayTrie.java
|
5445dd3e704adb95c7be72c2068b06b10fcac3a3
|
[] |
no_license
|
cpekyaman/AlgorithmsAndDS
|
https://github.com/cpekyaman/AlgorithmsAndDS
|
d929c7b2c99746db8cfd7d88bd639182826376ac
|
933db19edbce3b398d55ef1e0b8b87772d6c7fdd
|
refs/heads/master
| 2022-07-23T04:59:47.152000 | 2022-01-30T21:47:32 | 2022-01-30T21:47:32 | 104,676,218 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package algo.ch18;
public final class StringRWayTrie<VAL> extends RWayTrie<String, VAL> {
public StringRWayTrie() {
super(256);
}
@Override
protected String empty() {
return "";
}
@Override
protected String concat(String prefix, char c) {
return prefix + c;
}
}
|
UTF-8
|
Java
| 321 |
java
|
StringRWayTrie.java
|
Java
|
[] | null |
[] |
package algo.ch18;
public final class StringRWayTrie<VAL> extends RWayTrie<String, VAL> {
public StringRWayTrie() {
super(256);
}
@Override
protected String empty() {
return "";
}
@Override
protected String concat(String prefix, char c) {
return prefix + c;
}
}
| 321 | 0.601246 | 0.58567 | 17 | 17.882353 | 18.798882 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false |
10
|
669ca50ad2426b38eba8db73140dcb1fe4e67d6d
| 38,852,274,210,992 |
6c1fa91051b868a868bac24679474348cc0f340b
|
/src/main/java/com/example/demo/services/TacheServiceImpl.java
|
bee9adf92cd8ca4f1bf696266d27cae0c318792e
|
[] |
no_license
|
Mdidu/tp_gestionProjetBack
|
https://github.com/Mdidu/tp_gestionProjetBack
|
42125ce831aabdc0504ba4d38f4c3e441b296e0b
|
f5a292c1e8332afd06705f386edde7acf361d861
|
refs/heads/main
| 2023-05-07T17:20:11.849000 | 2021-06-03T13:34:33 | 2021-06-03T13:34:33 | 368,242,858 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.domain.Module;
import com.example.demo.domain.Tache;
import com.example.demo.repository.TacheRepository;
@Service
@Transactional
public class TacheServiceImpl implements TacheService {
@Autowired
TacheRepository tacheRepository;
@Override
public void add(Tache tache) {
tacheRepository.save(tache);
}
@Override
public void delete(Tache tache) {
tacheRepository.delete(tache);
}
@Override
public void update(Tache tache) {
tacheRepository.save(tache);
}
@Override
public List<Tache> findAll() {
return tacheRepository.findAll();
}
@Override
public Tache findById(long id) {
return tacheRepository.findById(id).get();
}
@Override
public List<Tache> findByModule(Module module) {
return tacheRepository.findByModule(module);
}
}
|
UTF-8
|
Java
| 1,027 |
java
|
TacheServiceImpl.java
|
Java
|
[] | null |
[] |
package com.example.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.domain.Module;
import com.example.demo.domain.Tache;
import com.example.demo.repository.TacheRepository;
@Service
@Transactional
public class TacheServiceImpl implements TacheService {
@Autowired
TacheRepository tacheRepository;
@Override
public void add(Tache tache) {
tacheRepository.save(tache);
}
@Override
public void delete(Tache tache) {
tacheRepository.delete(tache);
}
@Override
public void update(Tache tache) {
tacheRepository.save(tache);
}
@Override
public List<Tache> findAll() {
return tacheRepository.findAll();
}
@Override
public Tache findById(long id) {
return tacheRepository.findById(id).get();
}
@Override
public List<Tache> findByModule(Module module) {
return tacheRepository.findByModule(module);
}
}
| 1,027 | 0.779942 | 0.779942 | 50 | 19.559999 | 19.455755 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.96 | false | false |
10
|
3bc6712294c697012f8ff2055424b373472321ae
| 34,703,335,806,253 |
59b4c226b824d85cd9daf8badfd78240e69bedce
|
/src/com/aioerp/interceptor/OpenAccountInterceptor.java
|
c181d88e837184ed868f3deb37c24cf9b5a48c9b
|
[] |
no_license
|
NingKangMing/erpdemo
|
https://github.com/NingKangMing/erpdemo
|
fdc11c6b23de89f96ec0736197fe0eadb8d0f973
|
9256cf19679db49b0841401ce5156d22b5b13fa9
|
refs/heads/master
| 2021-07-09T08:55:34.964000 | 2017-10-09T06:24:12 | 2017-10-09T06:24:12 | 106,242,137 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.aioerp.interceptor;
import com.aioerp.common.AioConstants;
import com.aioerp.model.sys.AioerpSys;
import com.aioerp.model.sys.User;
import com.aioerp.util.DateUtils;
import com.aioerp.util.Dog;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class OpenAccountInterceptor
implements Interceptor
{
public void intercept(ActionInvocation ai)
{
Controller controller = ai.getController();
Record user = (Record)controller.getSessionAttr("user");
String actionKey = ai.getActionKey();
System.out.println(actionKey);
Map<String, String> actionKeyMap = new HashMap();
actionKeyMap.put("/bought/purchase/add", "");
actionKeyMap.put("/bought/return/add", "");
actionKeyMap.put("/bought/barter/add", "");
actionKeyMap.put("/sell/sell/add", "销售单添加");
actionKeyMap.put("/sell/return/add", "销售退货单添加");
actionKeyMap.put("/sell/barter/add", "销售换货单添加");
actionKeyMap.put("/stock/takeStock/add", "");
actionKeyMap.put("/stock/breakage/add", "");
actionKeyMap.put("/stock/overflow/add", "");
actionKeyMap.put("/stock/otherin/add", "其它入库单");
actionKeyMap.put("/stock/otherout/add", "其它出库单");
actionKeyMap.put("/stock/parityAllot/add", "");
actionKeyMap.put("/stock/difftAllot/add", "");
actionKeyMap.put("/stock/dismount/add", "");
actionKeyMap.put("/finance/getMoney/add", "收款单");
actionKeyMap.put("/finance/payMoney/add", "付款单");
actionKeyMap.put("/finance/fee/add", "费用单");
actionKeyMap.put("/finance/otherEarn/add", "其它收入单");
actionKeyMap.put("/finance/transfer/add", "内部转款单");
actionKeyMap.put("/finance/adjustCost/add", "成本调价单");
actionKeyMap.put("/finance/addAssets/add", "固定资产购置单");
actionKeyMap.put("/finance/deprAssets/add", "固定资产折旧单");
actionKeyMap.put("/finance/subAssets/add", "固定资产变卖单");
actionKeyMap.put("/finance/changeUnit/add", "应收应付 资金 变化");
actionKeyMap.put("/finance/accountVoucher/add", "会计凭证");
if (user != null)
{
String loginConfigId = user.getStr("loginConfigId") == null ? AioConstants.CONFIG_NAME : user.getStr("loginConfigId");
boolean isTry = true;
Map<String, String> result = new HashMap();
boolean isFalse = true;
try
{
if (("no".equals(AioConstants.IS_FREE_VERSION)) && (!"".equals(Dog.getID())) && (Dog.getVersion() == AioConstants.VERSION))
{
isTry = false;
if (actionKeyMap.containsKey(actionKey)) {
if ((!Dog.isRegister()) && (Dog.getLastDay() <= 0))
{
result.put("statusCode", "300");
result.put("message", "加密狗未注册,请帮助中心注册!");
isFalse = false;
}
else
{
int userCount = User.dao.getUserCount(user.getStr("loginConfigId"));
if ((userCount > Dog.getUserCount()) && (actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "您购买的软件为" + Dog.getUserCount() + "用户版,请先删除多余用户!");
isFalse = false;
}
}
}
}
}
catch (Error localError) {}
if (AioConstants.IS_FREE_VERSION != "yes") {
if ((isTry) && (actionKeyMap.containsKey(actionKey)))
{
Date currentDate = new Date();
Date time = DateUtils.addDays(user.getDate("loginConfigCreatTime"), AioConstants.TEST_DAY);
if (currentDate.after(time))
{
result.put("statusCode", "300");
result.put("message", "试用版到期,请购买正式版本");
isFalse = false;
}
else
{
Integer billCount = (Integer)AioConstants.accountBillCount.get(loginConfigId);
if ((billCount != null) && (billCount.intValue() > AioConstants.TEST_BILL_COUNT))
{
result.put("statusCode", "300");
result.put("message", "试用版到期,请购买正式版本");
isFalse = false;
}
}
}
}
if ((AioConstants.IO_OVER) && (actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "数据库被损坏或者中毒,请联系简易软件总部 020-87530321");
isFalse = false;
}
if ((isTry) && (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() != AioConstants.PROJECT_STATUS0))
{
result.put("statusCode", "300");
isFalse = false;
if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS1) {
result.put("message", "当前账套系统正在备份,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS2) {
result.put("message", "当前账套系统正在恢复 ,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS3) {
result.put("message", "当前账套系统正在重建,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS4) {
result.put("message", "当前账套系统正在成本重算,请稍后再试...");
}
}
if ((user.getStr("loginConfigId") == null) || (user.getStr("loginConfigId").equals(AioConstants.CONFIG_NAME)))
{
if (isFalse) {
ai.invoke();
}
}
else
{
if ((loginConfigId != null) && (!loginConfigId.equals(AioConstants.CONFIG_NAME)))
{
Integer status = (Integer)AioConstants.WHICHDBID_STATUS.get(loginConfigId);
if (status.intValue() == AioConstants.STATUS_DISABLE)
{
result.put("statusCode", "300");
result.put("message", "账套已经停用,请退出");
isFalse = false;
}
}
String hasOpenAccount = AioerpSys.dao.getValue1(user.getStr("loginConfigId"), "hasOpenAccount");
if ((hasOpenAccount.equals(AioConstants.HAS_OPEN_ACCOUNT0)) &&
(actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "没有开账,请先开账");
isFalse = false;
}
}
if (!isFalse) {
controller.renderJson(result);
} else {
ai.invoke();
}
}
else
{
ai.invoke();
}
}
}
|
UTF-8
|
Java
| 7,070 |
java
|
OpenAccountInterceptor.java
|
Java
|
[] | null |
[] |
package com.aioerp.interceptor;
import com.aioerp.common.AioConstants;
import com.aioerp.model.sys.AioerpSys;
import com.aioerp.model.sys.User;
import com.aioerp.util.DateUtils;
import com.aioerp.util.Dog;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class OpenAccountInterceptor
implements Interceptor
{
public void intercept(ActionInvocation ai)
{
Controller controller = ai.getController();
Record user = (Record)controller.getSessionAttr("user");
String actionKey = ai.getActionKey();
System.out.println(actionKey);
Map<String, String> actionKeyMap = new HashMap();
actionKeyMap.put("/bought/purchase/add", "");
actionKeyMap.put("/bought/return/add", "");
actionKeyMap.put("/bought/barter/add", "");
actionKeyMap.put("/sell/sell/add", "销售单添加");
actionKeyMap.put("/sell/return/add", "销售退货单添加");
actionKeyMap.put("/sell/barter/add", "销售换货单添加");
actionKeyMap.put("/stock/takeStock/add", "");
actionKeyMap.put("/stock/breakage/add", "");
actionKeyMap.put("/stock/overflow/add", "");
actionKeyMap.put("/stock/otherin/add", "其它入库单");
actionKeyMap.put("/stock/otherout/add", "其它出库单");
actionKeyMap.put("/stock/parityAllot/add", "");
actionKeyMap.put("/stock/difftAllot/add", "");
actionKeyMap.put("/stock/dismount/add", "");
actionKeyMap.put("/finance/getMoney/add", "收款单");
actionKeyMap.put("/finance/payMoney/add", "付款单");
actionKeyMap.put("/finance/fee/add", "费用单");
actionKeyMap.put("/finance/otherEarn/add", "其它收入单");
actionKeyMap.put("/finance/transfer/add", "内部转款单");
actionKeyMap.put("/finance/adjustCost/add", "成本调价单");
actionKeyMap.put("/finance/addAssets/add", "固定资产购置单");
actionKeyMap.put("/finance/deprAssets/add", "固定资产折旧单");
actionKeyMap.put("/finance/subAssets/add", "固定资产变卖单");
actionKeyMap.put("/finance/changeUnit/add", "应收应付 资金 变化");
actionKeyMap.put("/finance/accountVoucher/add", "会计凭证");
if (user != null)
{
String loginConfigId = user.getStr("loginConfigId") == null ? AioConstants.CONFIG_NAME : user.getStr("loginConfigId");
boolean isTry = true;
Map<String, String> result = new HashMap();
boolean isFalse = true;
try
{
if (("no".equals(AioConstants.IS_FREE_VERSION)) && (!"".equals(Dog.getID())) && (Dog.getVersion() == AioConstants.VERSION))
{
isTry = false;
if (actionKeyMap.containsKey(actionKey)) {
if ((!Dog.isRegister()) && (Dog.getLastDay() <= 0))
{
result.put("statusCode", "300");
result.put("message", "加密狗未注册,请帮助中心注册!");
isFalse = false;
}
else
{
int userCount = User.dao.getUserCount(user.getStr("loginConfigId"));
if ((userCount > Dog.getUserCount()) && (actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "您购买的软件为" + Dog.getUserCount() + "用户版,请先删除多余用户!");
isFalse = false;
}
}
}
}
}
catch (Error localError) {}
if (AioConstants.IS_FREE_VERSION != "yes") {
if ((isTry) && (actionKeyMap.containsKey(actionKey)))
{
Date currentDate = new Date();
Date time = DateUtils.addDays(user.getDate("loginConfigCreatTime"), AioConstants.TEST_DAY);
if (currentDate.after(time))
{
result.put("statusCode", "300");
result.put("message", "试用版到期,请购买正式版本");
isFalse = false;
}
else
{
Integer billCount = (Integer)AioConstants.accountBillCount.get(loginConfigId);
if ((billCount != null) && (billCount.intValue() > AioConstants.TEST_BILL_COUNT))
{
result.put("statusCode", "300");
result.put("message", "试用版到期,请购买正式版本");
isFalse = false;
}
}
}
}
if ((AioConstants.IO_OVER) && (actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "数据库被损坏或者中毒,请联系简易软件总部 020-87530321");
isFalse = false;
}
if ((isTry) && (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() != AioConstants.PROJECT_STATUS0))
{
result.put("statusCode", "300");
isFalse = false;
if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS1) {
result.put("message", "当前账套系统正在备份,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS2) {
result.put("message", "当前账套系统正在恢复 ,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS3) {
result.put("message", "当前账套系统正在重建,请稍后再试...");
} else if (((Integer)AioConstants.PROJECT_STATUS_MAP.get(loginConfigId)).intValue() == AioConstants.PROJECT_STATUS4) {
result.put("message", "当前账套系统正在成本重算,请稍后再试...");
}
}
if ((user.getStr("loginConfigId") == null) || (user.getStr("loginConfigId").equals(AioConstants.CONFIG_NAME)))
{
if (isFalse) {
ai.invoke();
}
}
else
{
if ((loginConfigId != null) && (!loginConfigId.equals(AioConstants.CONFIG_NAME)))
{
Integer status = (Integer)AioConstants.WHICHDBID_STATUS.get(loginConfigId);
if (status.intValue() == AioConstants.STATUS_DISABLE)
{
result.put("statusCode", "300");
result.put("message", "账套已经停用,请退出");
isFalse = false;
}
}
String hasOpenAccount = AioerpSys.dao.getValue1(user.getStr("loginConfigId"), "hasOpenAccount");
if ((hasOpenAccount.equals(AioConstants.HAS_OPEN_ACCOUNT0)) &&
(actionKeyMap.containsKey(actionKey)))
{
result.put("statusCode", "300");
result.put("message", "没有开账,请先开账");
isFalse = false;
}
}
if (!isFalse) {
controller.renderJson(result);
} else {
ai.invoke();
}
}
else
{
ai.invoke();
}
}
}
| 7,070 | 0.59589 | 0.589346 | 173 | 36.976879 | 30.582014 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.797688 | false | false |
10
|
8989121957fa52aa7b9091e5b73ed00b7ba47a61
| 37,048,387,933,234 |
e7439e2e717e2da0fef76790aa9a843a26415251
|
/app/src/main/java/com/ckw/zfsoft/mvpanddagger2/example/ExampleComponent.java
|
e6c670f0f0310a520d433caf96c45423eea0905d
|
[] |
no_license
|
China77/MVP-Retrofit-RxJava-Dagger2
|
https://github.com/China77/MVP-Retrofit-RxJava-Dagger2
|
2d3879463c0a170445a188f3125eef0a36c9e389
|
5205879f0018c2ae53814e7cb97e61c1342106bc
|
refs/heads/master
| 2020-04-20T04:40:23.697000 | 2017-11-30T09:15:12 | 2017-11-30T09:15:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ckw.zfsoft.mvpanddagger2.example;
import com.ckw.zfsoft.mvpanddagger2.global.AppComponent;
import com.ckw.zfsoft.mvpanddagger2.global.base.PerActivity;
import dagger.Component;
/**
* Created by ckw
* on 2017/11/30.
*/
@PerActivity
@Component(modules = ExamplePresenterModule.class, dependencies = AppComponent.class)
interface ExampleComponent {
void inject(ExampleActivity exampleActivity);
}
|
UTF-8
|
Java
| 418 |
java
|
ExampleComponent.java
|
Java
|
[
{
"context": "vity;\n\nimport dagger.Component;\n\n/**\n * Created by ckw\n * on 2017/11/30.\n */\n\n@PerActivity\n@Component(mo",
"end": 213,
"score": 0.9996551871299744,
"start": 210,
"tag": "USERNAME",
"value": "ckw"
}
] | null |
[] |
package com.ckw.zfsoft.mvpanddagger2.example;
import com.ckw.zfsoft.mvpanddagger2.global.AppComponent;
import com.ckw.zfsoft.mvpanddagger2.global.base.PerActivity;
import dagger.Component;
/**
* Created by ckw
* on 2017/11/30.
*/
@PerActivity
@Component(modules = ExamplePresenterModule.class, dependencies = AppComponent.class)
interface ExampleComponent {
void inject(ExampleActivity exampleActivity);
}
| 418 | 0.791866 | 0.76555 | 18 | 22.222221 | 25.384937 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
ab5361cd387c4bf702e9c51f04f876519a542eb3
| 35,467,839,981,274 |
f253b867e8bf76b28dbd92741aac63255705f392
|
/DataBinding/app/src/main/java/com/example/bhuang/databinding/MainActivityContract.java
|
79072a1b57eb46197091f5af327326ff4dfc7d41
|
[] |
no_license
|
billonline33/AndroidBootCamp
|
https://github.com/billonline33/AndroidBootCamp
|
8480c233b5165e856cf3da073c6ed52c264fcbf7
|
5a81706cab198a89019305e425b85053a393e985
|
refs/heads/master
| 2020-05-30T08:36:14.653000 | 2017-08-04T05:49:19 | 2017-08-04T05:49:19 | 94,961,034 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.bhuang.databinding;
import com.example.bhuang.databinding.TemperatureData;
/**
* Created by bhuang on 6/21/2017.
*/
public interface MainActivityContract {
public interface Presenter
{
void onShowData(TemperatureData temperatureData);
void showList();
}
public interface View
{
void showData(TemperatureData temperatureData);
void startSecondActivity();
}
}
|
UTF-8
|
Java
| 440 |
java
|
MainActivityContract.java
|
Java
|
[
{
"context": "ng.databinding.TemperatureData;\n\n/**\n * Created by bhuang on 6/21/2017.\n */\n\npublic interface MainActivityC",
"end": 121,
"score": 0.9995571970939636,
"start": 115,
"tag": "USERNAME",
"value": "bhuang"
}
] | null |
[] |
package com.example.bhuang.databinding;
import com.example.bhuang.databinding.TemperatureData;
/**
* Created by bhuang on 6/21/2017.
*/
public interface MainActivityContract {
public interface Presenter
{
void onShowData(TemperatureData temperatureData);
void showList();
}
public interface View
{
void showData(TemperatureData temperatureData);
void startSecondActivity();
}
}
| 440 | 0.693182 | 0.677273 | 21 | 19.952381 | 20.08666 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
e8e7c9d0e1070d1cbc786327352db40391125e1c
| 5,420,248,779,140 |
5b2ace6e54ecf49be4e5dd6d2411f48e733ddaf2
|
/zero-business/src/main/java/space/zero/business/module/base/service/impl/BaseOrganizationServiceImpl.java
|
6ac722c3c2e909c813dc3345f5040e78c211d3dc
|
[] |
no_license
|
Fatesta/non-zero
|
https://github.com/Fatesta/non-zero
|
6033fd8779b1aad3d945fb92d149e3c7f60c0a60
|
d58ca0220c55fec237734ed53855b1c09875df12
|
refs/heads/master
| 2020-03-31T12:39:58.222000 | 2018-10-07T14:42:00 | 2018-10-07T14:42:00 | 152,225,099 | 1 | 0 | null | true | 2018-10-09T09:33:37 | 2018-10-09T09:33:37 | 2018-10-08T05:46:44 | 2018-10-07T14:42:01 | 230 | 0 | 0 | 0 | null | false | null |
package space.zero.business.module.base.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import space.zero.business.module.base.dao.BaseOrganizationMapper;
import space.zero.business.module.base.model.BaseOrganization;
import space.zero.business.module.base.param.response.BaseOrganizationTree;
import space.zero.business.module.base.service.BaseOrganizationService;
import space.zero.business.module.sys.model.SysUserDetails;
import space.zero.common.keyGenerator.KeyGenerator;
import space.zero.common.utils.StringUtils;
import space.zero.core.service.AbstractDeleteFlagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by PG_shen on 2018/03/17.
*/
@Service
@Transactional
public class BaseOrganizationServiceImpl extends AbstractDeleteFlagService<BaseOrganization> implements BaseOrganizationService {
@Resource
private BaseOrganizationMapper baseOrganizationMapper;
@Autowired
KeyGenerator<String> keyGenerator;
public BaseOrganizationTree getOrgTree(){
BaseOrganizationTree baseOrganizationTree = new BaseOrganizationTree();
List<BaseOrganizationTree> children = new ArrayList<>();
List<BaseOrganization> baseOrganizations = baseOrganizationMapper.findAllOrganization();
for (int i = 0; i < baseOrganizations.size(); i++){
BaseOrganizationTree baseOrganizationTreeTmp = new BaseOrganizationTree(baseOrganizations.get(i).getId(),
baseOrganizations.get(i).getParentId(),
baseOrganizations.get(i).getName(),
baseOrganizations.get(i).getEmail(),
baseOrganizations.get(i).getRemark(),
baseOrganizations.get(i).getPostCode(),
baseOrganizations.get(i).getType(),
baseOrganizations.get(i).getTel(),
baseOrganizations.get(i).getDescription());
baseOrganizationTreeTmp.setChildren(getChildren(baseOrganizations.get(i).getId()));
children.add(baseOrganizationTreeTmp);
}
baseOrganizationTree.setChildren(children);
return baseOrganizationTree;
}
public List<BaseOrganizationTree> getChildren(String parentId){
if (StringUtils.isEmpty(parentId)){
return null;
}
List<BaseOrganizationTree> children = new ArrayList<>();
List<BaseOrganization> baseOrganizations = baseOrganizationMapper.findByParentID(parentId);
for (int i = 0; i < baseOrganizations.size(); i++){
BaseOrganizationTree baseOrganizationTreeTmp = new BaseOrganizationTree(baseOrganizations.get(i).getId(),
baseOrganizations.get(i).getParentId(),
baseOrganizations.get(i).getName(),
baseOrganizations.get(i).getEmail(),
baseOrganizations.get(i).getRemark(),
baseOrganizations.get(i).getPostCode(),
baseOrganizations.get(i).getType(),
baseOrganizations.get(i).getTel(),
baseOrganizations.get(i).getDescription());
baseOrganizationTreeTmp.setChildren(getChildren(baseOrganizations.get(i).getId()));
children.add(baseOrganizationTreeTmp);
}
return children;
}
@Override
public boolean preInsert(BaseOrganization data){
if (StringUtils.isEmpty(data.getId())){
data.setId(keyGenerator.getNext());
}
// 公司则父节点id为0
if (StringUtils.isEmpty(data.getParentId())){
data.setParentId("0");
}
data.setCreatedTime(new Date());
data.setUpdateTime(new Date());
SysUserDetails sysUserDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
data.setCreatedUser(sysUserDetails.getUser().getName());
return super.preInsert(data);
}
}
|
UTF-8
|
Java
| 4,201 |
java
|
BaseOrganizationServiceImpl.java
|
Java
|
[
{
"context": "l.Date;\nimport java.util.List;\n\n\n/**\n * Created by PG_shen on 2018/03/17.\n */\n@Service\n@Transactional\npublic",
"end": 930,
"score": 0.9997379779815674,
"start": 923,
"tag": "USERNAME",
"value": "PG_shen"
}
] | null |
[] |
package space.zero.business.module.base.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import space.zero.business.module.base.dao.BaseOrganizationMapper;
import space.zero.business.module.base.model.BaseOrganization;
import space.zero.business.module.base.param.response.BaseOrganizationTree;
import space.zero.business.module.base.service.BaseOrganizationService;
import space.zero.business.module.sys.model.SysUserDetails;
import space.zero.common.keyGenerator.KeyGenerator;
import space.zero.common.utils.StringUtils;
import space.zero.core.service.AbstractDeleteFlagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by PG_shen on 2018/03/17.
*/
@Service
@Transactional
public class BaseOrganizationServiceImpl extends AbstractDeleteFlagService<BaseOrganization> implements BaseOrganizationService {
@Resource
private BaseOrganizationMapper baseOrganizationMapper;
@Autowired
KeyGenerator<String> keyGenerator;
public BaseOrganizationTree getOrgTree(){
BaseOrganizationTree baseOrganizationTree = new BaseOrganizationTree();
List<BaseOrganizationTree> children = new ArrayList<>();
List<BaseOrganization> baseOrganizations = baseOrganizationMapper.findAllOrganization();
for (int i = 0; i < baseOrganizations.size(); i++){
BaseOrganizationTree baseOrganizationTreeTmp = new BaseOrganizationTree(baseOrganizations.get(i).getId(),
baseOrganizations.get(i).getParentId(),
baseOrganizations.get(i).getName(),
baseOrganizations.get(i).getEmail(),
baseOrganizations.get(i).getRemark(),
baseOrganizations.get(i).getPostCode(),
baseOrganizations.get(i).getType(),
baseOrganizations.get(i).getTel(),
baseOrganizations.get(i).getDescription());
baseOrganizationTreeTmp.setChildren(getChildren(baseOrganizations.get(i).getId()));
children.add(baseOrganizationTreeTmp);
}
baseOrganizationTree.setChildren(children);
return baseOrganizationTree;
}
public List<BaseOrganizationTree> getChildren(String parentId){
if (StringUtils.isEmpty(parentId)){
return null;
}
List<BaseOrganizationTree> children = new ArrayList<>();
List<BaseOrganization> baseOrganizations = baseOrganizationMapper.findByParentID(parentId);
for (int i = 0; i < baseOrganizations.size(); i++){
BaseOrganizationTree baseOrganizationTreeTmp = new BaseOrganizationTree(baseOrganizations.get(i).getId(),
baseOrganizations.get(i).getParentId(),
baseOrganizations.get(i).getName(),
baseOrganizations.get(i).getEmail(),
baseOrganizations.get(i).getRemark(),
baseOrganizations.get(i).getPostCode(),
baseOrganizations.get(i).getType(),
baseOrganizations.get(i).getTel(),
baseOrganizations.get(i).getDescription());
baseOrganizationTreeTmp.setChildren(getChildren(baseOrganizations.get(i).getId()));
children.add(baseOrganizationTreeTmp);
}
return children;
}
@Override
public boolean preInsert(BaseOrganization data){
if (StringUtils.isEmpty(data.getId())){
data.setId(keyGenerator.getNext());
}
// 公司则父节点id为0
if (StringUtils.isEmpty(data.getParentId())){
data.setParentId("0");
}
data.setCreatedTime(new Date());
data.setUpdateTime(new Date());
SysUserDetails sysUserDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
data.setCreatedUser(sysUserDetails.getUser().getName());
return super.preInsert(data);
}
}
| 4,201 | 0.68856 | 0.685694 | 102 | 40.049019 | 31.967318 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598039 | false | false |
10
|
d96ebb12b2bbfaa4d663dedb565db5d4c6151489
| 7,103,875,963,356 |
b6c1e12f591f0dae3fbd4a3703c5df432cb0eb92
|
/pronscrapper/src/main/java/lt/kitech/pron/controller/ImportController.java
|
0c1733c644872d773e2b387689ef0a257902882d
|
[] |
no_license
|
SoulParty/kiscrapper
|
https://github.com/SoulParty/kiscrapper
|
aa7991d30ea67dc1f56798c47116cf8005f26c07
|
cb91899478a6fc0151daaf72d325d319629f4775
|
refs/heads/master
| 2017-12-17T18:00:33.558000 | 2017-11-07T00:23:51 | 2017-11-07T00:23:51 | 77,229,539 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lt.kitech.pron.controller;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import lt.kitech.pron.domain.Digram;
import lt.kitech.pron.domain.Video;
import lt.kitech.pron.domain.Word;
import lt.kitech.pron.repository.DigramRepository;
import lt.kitech.pron.repository.VideoRepository;
import lt.kitech.pron.repository.WordRepository;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/")
public class ImportController {
private static final Logger LOG = LoggerFactory.getLogger(ImportController.class);
@Autowired
private VideoRepository videoRepository;
@Autowired
private WordRepository wordRepository;
@Autowired
private DigramRepository digramRepository;
private Map<String, Integer> wordMap = new HashMap<>();
private Map<String, Integer> digramMap = new HashMap<>();
@PostConstruct
public void init() {
}
@RequestMapping(value = "/words", method = RequestMethod.GET)
@ResponseBody
public String wordImport() {
long count = videoRepository.count();
long pages = count / 100 + 1;
for (int i = 0; i < pages; i++) {
Page<Video> videos = videoRepository.findAll(createPageRequest(i));
for (final Video video : videos.getContent()) {
for (final String word : video.getDescription().split(" ")) {
generateWord(word);
}
}
LOG.info("------------------ Page: " + i + "------------------");
}
for (final String word : wordMap.keySet()) {
Word newWord = new Word();
newWord.setWord(word);
newWord.setCount(Long.valueOf(wordMap.get(word)));
wordRepository.save(newWord);
}
return "ok";
}
@RequestMapping(value = "/ngrams", method = RequestMethod.GET)
@ResponseBody
public String ngramImport() {
long pageCount = videoRepository.count();
long pages = pageCount / 100 + 1;
for (int i = 0; i < pages; i++) {
Page<Video> videos = videoRepository.findAll(createPageRequest(i));
for (final Video video : videos.getContent()) {
generateNgrams(video.getDescription());
}
LOG.info("------------------ Page: " + i + "------------------");
}
for (final String wordPair : digramMap.keySet()) {
Long count = Long.valueOf(digramMap.get(wordPair));
if (count < 20) {
continue;
}
Digram digram = new Digram();
digram.setDigram(wordPair);
digram.setCount(count);
digramRepository.save(digram);
}
return "ok";
}
private Pageable createPageRequest(int page) {
return new PageRequest(page, 100);
}
private void generateWord(final String word) {
if (word.length() <= 2) {
return;
}
if (wordMap.containsKey(word)) {
Integer count = wordMap.get(word);
wordMap.replace(word, count + 1);
} else {
wordMap.put(word, 1);
}
}
private void generateNgrams(String text) {
try {
Reader reader = new StringReader(text);
TokenStream tokenizer = new StandardTokenizer(Version.LUCENE_46, reader);
ShingleFilter shingleFilter = new ShingleFilter(tokenizer, 2, 2);
shingleFilter.setOutputUnigrams(false);
tokenizer = shingleFilter;
CharTermAttribute charTermAttribute = tokenizer.addAttribute(CharTermAttribute.class);
tokenizer.reset();
while (tokenizer.incrementToken()) {
String token = charTermAttribute.toString();
if (token.length() <= 5) {
continue;
}
if (digramMap.containsKey(token)) {
Integer count = digramMap.get(token);
digramMap.replace(token, count + 1);
} else {
digramMap.put(token, 1);
}
}
tokenizer.end();
tokenizer.close();
} catch (IOException e) {
LOG.error("Error getting ngram", e);
}
}
}
|
UTF-8
|
Java
| 4,418 |
java
|
ImportController.java
|
Java
|
[] | null |
[] |
package lt.kitech.pron.controller;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import lt.kitech.pron.domain.Digram;
import lt.kitech.pron.domain.Video;
import lt.kitech.pron.domain.Word;
import lt.kitech.pron.repository.DigramRepository;
import lt.kitech.pron.repository.VideoRepository;
import lt.kitech.pron.repository.WordRepository;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/")
public class ImportController {
private static final Logger LOG = LoggerFactory.getLogger(ImportController.class);
@Autowired
private VideoRepository videoRepository;
@Autowired
private WordRepository wordRepository;
@Autowired
private DigramRepository digramRepository;
private Map<String, Integer> wordMap = new HashMap<>();
private Map<String, Integer> digramMap = new HashMap<>();
@PostConstruct
public void init() {
}
@RequestMapping(value = "/words", method = RequestMethod.GET)
@ResponseBody
public String wordImport() {
long count = videoRepository.count();
long pages = count / 100 + 1;
for (int i = 0; i < pages; i++) {
Page<Video> videos = videoRepository.findAll(createPageRequest(i));
for (final Video video : videos.getContent()) {
for (final String word : video.getDescription().split(" ")) {
generateWord(word);
}
}
LOG.info("------------------ Page: " + i + "------------------");
}
for (final String word : wordMap.keySet()) {
Word newWord = new Word();
newWord.setWord(word);
newWord.setCount(Long.valueOf(wordMap.get(word)));
wordRepository.save(newWord);
}
return "ok";
}
@RequestMapping(value = "/ngrams", method = RequestMethod.GET)
@ResponseBody
public String ngramImport() {
long pageCount = videoRepository.count();
long pages = pageCount / 100 + 1;
for (int i = 0; i < pages; i++) {
Page<Video> videos = videoRepository.findAll(createPageRequest(i));
for (final Video video : videos.getContent()) {
generateNgrams(video.getDescription());
}
LOG.info("------------------ Page: " + i + "------------------");
}
for (final String wordPair : digramMap.keySet()) {
Long count = Long.valueOf(digramMap.get(wordPair));
if (count < 20) {
continue;
}
Digram digram = new Digram();
digram.setDigram(wordPair);
digram.setCount(count);
digramRepository.save(digram);
}
return "ok";
}
private Pageable createPageRequest(int page) {
return new PageRequest(page, 100);
}
private void generateWord(final String word) {
if (word.length() <= 2) {
return;
}
if (wordMap.containsKey(word)) {
Integer count = wordMap.get(word);
wordMap.replace(word, count + 1);
} else {
wordMap.put(word, 1);
}
}
private void generateNgrams(String text) {
try {
Reader reader = new StringReader(text);
TokenStream tokenizer = new StandardTokenizer(Version.LUCENE_46, reader);
ShingleFilter shingleFilter = new ShingleFilter(tokenizer, 2, 2);
shingleFilter.setOutputUnigrams(false);
tokenizer = shingleFilter;
CharTermAttribute charTermAttribute = tokenizer.addAttribute(CharTermAttribute.class);
tokenizer.reset();
while (tokenizer.incrementToken()) {
String token = charTermAttribute.toString();
if (token.length() <= 5) {
continue;
}
if (digramMap.containsKey(token)) {
Integer count = digramMap.get(token);
digramMap.replace(token, count + 1);
} else {
digramMap.put(token, 1);
}
}
tokenizer.end();
tokenizer.close();
} catch (IOException e) {
LOG.error("Error getting ngram", e);
}
}
}
| 4,418 | 0.712766 | 0.706655 | 151 | 28.2649 | 22.231384 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.218543 | false | false |
10
|
4bc0aa675beb5caacfc240e9df039bd9a9403d44
| 11,192,684,821,702 |
2e485548d1f1c95bc1a6e87ad2709b29afbddab2
|
/src/main/java/hr/restart/spa/web/controllers/KamracController.java
|
19b6a35217c04d01e0697beff68acccbf1e3a3fa
|
[] |
no_license
|
rest-art/spa
|
https://github.com/rest-art/spa
|
a56a5da42d727d005402ecace1e048b734b5d41d
|
11bf8ec5f9ff553d8ff5cd8f95ff00c0b258ff21
|
refs/heads/master
| 2018-12-29T12:58:18.374000 | 2018-10-05T14:43:39 | 2018-10-05T14:43:39 | 24,493,118 | 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 hr.restart.spa.web.controllers;
import hr.restart.spa.entities.Kamrac;
import hr.restart.spa.exceptions.ErpException;
import hr.restart.spa.json.JsonMultipleResult;
import hr.restart.spa.json.JsonSingleResult;
import hr.restart.spa.reports.ReportFormat;
import hr.restart.spa.services.KamracService;
import hr.restart.spa.specifications.ErpQueryParams;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author User
*/
@Controller
public class KamracController {
@Autowired
private KamracService serviceKamrac;
@Autowired
private MessageSource messageSource;
private enum Messages {
TABLE_COLUMN_LOCALIZATION("erp.module.ok.kamrac.column."),
VALIDATION_ERROR("erp.exception.validation.fail");
private final String value;
private Messages(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamarac/create/", method = RequestMethod.POST)
public ResponseEntity createKamrac(@RequestBody @Valid Kamrac kamrac, Errors errors, Locale locale) throws ErpException {
if (errors.hasErrors()) {
String errorMessage = messageSource.getMessage(Messages.VALIDATION_ERROR.getValue(), null, locale);
throw new ErpException(errorMessage);
}
return new ResponseEntity(serviceKamrac.createKamrac(kamrac), HttpStatus.CREATED);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/update/", method = RequestMethod.PUT)
public ResponseEntity updateKamrac(@RequestBody @Valid Kamrac kamrac, Errors errors, Locale locale) throws ErpException {
if (errors.hasErrors()) {
String errorMessage = messageSource.getMessage(Messages.VALIDATION_ERROR.getValue(), null, locale);
throw new ErpException(errorMessage);
}
return new ResponseEntity(serviceKamrac.updateKamrac(kamrac), HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/search/", method = RequestMethod.POST)
public ResponseEntity searchKamrac(@RequestBody ErpQueryParams queryParams, Locale locale) throws ErpException {
List<Sort.Order> defaultOrder = new ArrayList<Sort.Order>();
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "knjig"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "cpar"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "brojdok"));
Page<Kamrac> result = serviceKamrac.searchKamrac(queryParams, defaultOrder);
JsonMultipleResult<Kamrac> jsonOut = new JsonMultipleResult<Kamrac>();
jsonOut.wrap(result, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/getbybrojdok/{brojdok}/", method = RequestMethod.GET)
public ResponseEntity dohvatKamrac(@PathVariable String brojdok, Locale locale) throws ErpException {
Kamrac agent = serviceKamrac.dohvatKamrac(brojdok);
JsonSingleResult<Kamrac> jsonOut = new JsonSingleResult<Kamrac>();
jsonOut.wrap(agent, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/get/{id}/", method = RequestMethod.GET)
public ResponseEntity getKamrac(@PathVariable Long id, Locale locale) throws ErpException {
Kamrac kamata = serviceKamrac.getKamrac(id);
JsonSingleResult<Kamrac> jsonOut = new JsonSingleResult<Kamrac>();
jsonOut.wrap(kamata, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/delete/{id}/", method = RequestMethod.DELETE)
public ResponseEntity deleteKamrac(@PathVariable Long id) throws ErpException {
return new ResponseEntity(serviceKamrac.deleteKamrac(id), HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/print", method = RequestMethod.POST)
public ModelAndView printKamrac(@RequestBody ReportFormat reportFormat) throws ErpException {
List<Sort.Order> defaultOrder = new ArrayList<Sort.Order>();
//defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "knjig"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "cpar"));
//defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "brojdok"));
return serviceKamrac.printKamrac(reportFormat, defaultOrder);
}
}
|
UTF-8
|
Java
| 5,501 |
java
|
KamracController.java
|
Java
|
[
{
"context": "ework.web.servlet.ModelAndView;\n\n/**\n *\n * @author User\n */\n@Controller\npublic class KamracController {\n\n",
"end": 1428,
"score": 0.6883496046066284,
"start": 1424,
"tag": "USERNAME",
"value": "User"
}
] | 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 hr.restart.spa.web.controllers;
import hr.restart.spa.entities.Kamrac;
import hr.restart.spa.exceptions.ErpException;
import hr.restart.spa.json.JsonMultipleResult;
import hr.restart.spa.json.JsonSingleResult;
import hr.restart.spa.reports.ReportFormat;
import hr.restart.spa.services.KamracService;
import hr.restart.spa.specifications.ErpQueryParams;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author User
*/
@Controller
public class KamracController {
@Autowired
private KamracService serviceKamrac;
@Autowired
private MessageSource messageSource;
private enum Messages {
TABLE_COLUMN_LOCALIZATION("erp.module.ok.kamrac.column."),
VALIDATION_ERROR("erp.exception.validation.fail");
private final String value;
private Messages(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamarac/create/", method = RequestMethod.POST)
public ResponseEntity createKamrac(@RequestBody @Valid Kamrac kamrac, Errors errors, Locale locale) throws ErpException {
if (errors.hasErrors()) {
String errorMessage = messageSource.getMessage(Messages.VALIDATION_ERROR.getValue(), null, locale);
throw new ErpException(errorMessage);
}
return new ResponseEntity(serviceKamrac.createKamrac(kamrac), HttpStatus.CREATED);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/update/", method = RequestMethod.PUT)
public ResponseEntity updateKamrac(@RequestBody @Valid Kamrac kamrac, Errors errors, Locale locale) throws ErpException {
if (errors.hasErrors()) {
String errorMessage = messageSource.getMessage(Messages.VALIDATION_ERROR.getValue(), null, locale);
throw new ErpException(errorMessage);
}
return new ResponseEntity(serviceKamrac.updateKamrac(kamrac), HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/search/", method = RequestMethod.POST)
public ResponseEntity searchKamrac(@RequestBody ErpQueryParams queryParams, Locale locale) throws ErpException {
List<Sort.Order> defaultOrder = new ArrayList<Sort.Order>();
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "knjig"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "cpar"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "brojdok"));
Page<Kamrac> result = serviceKamrac.searchKamrac(queryParams, defaultOrder);
JsonMultipleResult<Kamrac> jsonOut = new JsonMultipleResult<Kamrac>();
jsonOut.wrap(result, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/getbybrojdok/{brojdok}/", method = RequestMethod.GET)
public ResponseEntity dohvatKamrac(@PathVariable String brojdok, Locale locale) throws ErpException {
Kamrac agent = serviceKamrac.dohvatKamrac(brojdok);
JsonSingleResult<Kamrac> jsonOut = new JsonSingleResult<Kamrac>();
jsonOut.wrap(agent, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/get/{id}/", method = RequestMethod.GET)
public ResponseEntity getKamrac(@PathVariable Long id, Locale locale) throws ErpException {
Kamrac kamata = serviceKamrac.getKamrac(id);
JsonSingleResult<Kamrac> jsonOut = new JsonSingleResult<Kamrac>();
jsonOut.wrap(kamata, messageSource, Messages.TABLE_COLUMN_LOCALIZATION.getValue(), locale);
return new ResponseEntity(jsonOut, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/delete/{id}/", method = RequestMethod.DELETE)
public ResponseEntity deleteKamrac(@PathVariable Long id) throws ErpException {
return new ResponseEntity(serviceKamrac.deleteKamrac(id), HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = "/modules/ok/kamrac/print", method = RequestMethod.POST)
public ModelAndView printKamrac(@RequestBody ReportFormat reportFormat) throws ErpException {
List<Sort.Order> defaultOrder = new ArrayList<Sort.Order>();
//defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "knjig"));
defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "cpar"));
//defaultOrder.add(new Sort.Order(Sort.Direction.DESC, "brojdok"));
return serviceKamrac.printKamrac(reportFormat, defaultOrder);
}
}
| 5,501 | 0.768588 | 0.768588 | 151 | 35.430462 | 34.219685 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.940397 | false | false |
10
|
49cf42949ce026c6b8f1362058a12726f0fc4d25
| 7,945,689,546,093 |
4a25d92d9989066976c0c5c529a6fbfb611ec22a
|
/server/src/main/java/password/pwm/http/servlet/forgottenpw/ForgottenPasswordUtil.java
|
f830b3d51b7c17cf51b8ea4205d08260c8ff4681
|
[
"Apache-2.0"
] |
permissive
|
pwm-project/pwm
|
https://github.com/pwm-project/pwm
|
62e8b3af34383c9bd105c55d5a2896bcd9a3facd
|
9fd838b93d2ef759c3c4ec49367cbe121356b076
|
refs/heads/master
| 2023-07-31T18:26:21.967000 | 2023-06-26T22:01:26 | 2023-06-26T22:01:26 | 44,565,647 | 934 | 330 |
NOASSERTION
| false | 2023-03-01T15:47:51 | 2015-10-19T21:38:14 | 2023-02-21T23:09:34 | 2023-03-01T14:50:55 | 143,190 | 831 | 242 | 160 |
Java
| false | false |
/*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2021 The PWM Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package password.pwm.http.servlet.forgottenpw;
import com.novell.ldapchai.ChaiUser;
import com.novell.ldapchai.cr.ChaiChallenge;
import com.novell.ldapchai.cr.Challenge;
import com.novell.ldapchai.cr.ChallengeSet;
import com.novell.ldapchai.cr.ResponseSet;
import com.novell.ldapchai.cr.bean.ChallengeBean;
import com.novell.ldapchai.cr.bean.ChallengeSetBean;
import com.novell.ldapchai.exception.ChaiException;
import com.novell.ldapchai.exception.ChaiOperationException;
import com.novell.ldapchai.exception.ChaiUnavailableException;
import com.novell.ldapchai.exception.ChaiValidationException;
import password.pwm.AppProperty;
import password.pwm.PwmConstants;
import password.pwm.PwmDomain;
import password.pwm.bean.EmailItemBean;
import password.pwm.bean.ProfileID;
import password.pwm.bean.SessionLabel;
import password.pwm.bean.TokenDestinationItem;
import password.pwm.bean.UserIdentity;
import password.pwm.config.DomainConfig;
import password.pwm.config.PwmSetting;
import password.pwm.config.option.IdentityVerificationMethod;
import password.pwm.config.option.MessageSendMethod;
import password.pwm.config.option.RecoveryAction;
import password.pwm.config.option.RecoveryMinLifetimeOption;
import password.pwm.config.profile.ForgottenPasswordProfile;
import password.pwm.config.profile.ProfileDefinition;
import password.pwm.config.profile.ProfileUtility;
import password.pwm.config.value.data.FormConfiguration;
import password.pwm.error.ErrorInformation;
import password.pwm.error.PwmError;
import password.pwm.error.PwmException;
import password.pwm.error.PwmOperationalException;
import password.pwm.error.PwmUnrecoverableException;
import password.pwm.http.PwmRequest;
import password.pwm.http.PwmRequestContext;
import password.pwm.http.PwmSession;
import password.pwm.http.auth.HttpAuthRecord;
import password.pwm.http.bean.ForgottenPasswordBean;
import password.pwm.i18n.Message;
import password.pwm.ldap.LdapOperationsHelper;
import password.pwm.ldap.UserInfoFactory;
import password.pwm.svc.event.AuditEvent;
import password.pwm.svc.event.AuditRecord;
import password.pwm.svc.event.AuditRecordFactory;
import password.pwm.svc.event.AuditServiceClient;
import password.pwm.svc.stats.Statistic;
import password.pwm.svc.stats.StatisticsClient;
import password.pwm.svc.token.TokenType;
import password.pwm.svc.token.TokenUtil;
import password.pwm.user.UserInfo;
import password.pwm.util.PasswordData;
import password.pwm.util.java.CollectionUtil;
import password.pwm.util.logging.PwmLogger;
import password.pwm.util.macro.MacroRequest;
import password.pwm.util.password.PasswordUtility;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ForgottenPasswordUtil
{
private static final PwmLogger LOGGER = PwmLogger.forClass( ForgottenPasswordUtil.class );
static Set<IdentityVerificationMethod> figureRemainingAvailableOptionalAuthMethods(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
{
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = forgottenPasswordBean.getRecoveryFlags();
final ForgottenPasswordBean.Progress progress = forgottenPasswordBean.getProgress();
final Set<IdentityVerificationMethod> result = new LinkedHashSet<>( recoveryFlags.getOptionalAuthMethods() );
result.removeAll( progress.getSatisfiedMethods() );
for ( final IdentityVerificationMethod recoveryVerificationMethods : new LinkedHashSet<>( result ) )
{
try
{
verifyRequirementsForAuthMethod( pwmRequestContext, forgottenPasswordBean, recoveryVerificationMethods );
}
catch ( final PwmUnrecoverableException e )
{
result.remove( recoveryVerificationMethods );
}
}
return Collections.unmodifiableSet( result );
}
static RecoveryAction getRecoveryAction( final DomainConfig domainConfig, final ForgottenPasswordBean forgottenPasswordBean )
{
final ForgottenPasswordProfile forgottenPasswordProfile = domainConfig.getForgottenPasswordProfiles().get( forgottenPasswordBean.getForgottenPasswordProfileID() );
return forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_ACTION, RecoveryAction.class );
}
static Set<IdentityVerificationMethod> figureSatisfiedOptionalAuthMethods(
final ForgottenPasswordBean.RecoveryFlags recoveryFlags,
final ForgottenPasswordBean.Progress progress )
{
final Set<IdentityVerificationMethod> result = new LinkedHashSet<>( recoveryFlags.getOptionalAuthMethods() );
result.retainAll( progress.getSatisfiedMethods() );
return Collections.unmodifiableSet( result );
}
public static Optional<UserInfo> readUserInfo(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
if ( forgottenPasswordBean.getUserIdentity() == null )
{
return Optional.empty();
}
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
return Optional.of( UserInfoFactory.newUserInfoUsingProxy(
pwmRequestContext.getPwmApplication(),
pwmRequestContext.getSessionLabel(),
userIdentity,
pwmRequestContext.getLocale() ) );
}
static Optional<ResponseSet> readResponseSet(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
if ( forgottenPasswordBean.getUserIdentity() == null )
{
return Optional.empty();
}
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final ChaiUser theUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userIdentity );
return pwmDomain.getCrService().readUserResponseSet(
pwmRequestContext.getSessionLabel(),
userIdentity,
theUser );
}
static void sendUnlockNoticeEmail(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final DomainConfig config = pwmRequestContext.getDomainConfig();
final Locale locale = pwmRequestContext.getLocale();
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final EmailItemBean configuredEmailSetting = config.readSettingAsEmail( PwmSetting.EMAIL_UNLOCK, locale );
if ( configuredEmailSetting == null )
{
LOGGER.debug( pwmRequestContext.getSessionLabel(), () -> "skipping send unlock notice email for '" + userIdentity + "' no email configured" );
return;
}
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final MacroRequest macroRequest = MacroRequest.forUser(
pwmRequestContext.getPwmApplication(),
pwmRequestContext.getSessionLabel(),
userInfo,
null
);
pwmDomain.getPwmApplication().getEmailQueue().submitEmail(
configuredEmailSetting,
userInfo,
macroRequest
);
}
static boolean checkAuthRecord(
final PwmRequest pwmRequest,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequest.getPwmApplication().domains().get( userIdentity.getDomainID() );
final Optional<String> userGuid = LdapOperationsHelper.readLdapGuidValue(
pwmDomain,
pwmRequest.getLabel(),
userIdentity );
if ( userGuid.isEmpty() )
{
return false;
}
try
{
final String cookieName = pwmDomain.getConfig().readAppProperty( AppProperty.HTTP_COOKIE_AUTHRECORD_NAME );
if ( cookieName == null || cookieName.isEmpty() )
{
LOGGER.trace( pwmRequest, () -> "skipping auth record cookie read, cookie name parameter is blank" );
return false;
}
final Optional<HttpAuthRecord> optionalHttpAuthRecord = pwmRequest.readEncryptedCookie( cookieName, HttpAuthRecord.class );
if ( optionalHttpAuthRecord.isPresent() )
{
final HttpAuthRecord httpAuthRecord = optionalHttpAuthRecord.get();
if ( userGuid.get().equals( httpAuthRecord.getGuid() ) )
{
LOGGER.debug( pwmRequest, () -> "auth record cookie validated" );
return true;
}
}
}
catch ( final Exception e )
{
LOGGER.error( pwmRequest, () -> "unexpected error while examining cookie auth record: " + e.getMessage() );
}
return false;
}
static List<TokenDestinationItem> figureAvailableTokenDestinations(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
final ProfileID profileID = forgottenPasswordBean.getForgottenPasswordProfileID();
final ForgottenPasswordProfile forgottenPasswordProfile = pwmRequestContext.getDomainConfig().getForgottenPasswordProfiles().get( profileID );
final MessageSendMethod tokenSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_TOKEN_SEND_METHOD, MessageSendMethod.class );
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
return TokenUtil.figureAvailableTokenDestinations(
pwmRequestContext.getPwmDomain(),
pwmRequestContext.getSessionLabel(),
pwmRequestContext.getLocale(),
userInfo,
tokenSendMethod
);
}
static void verifyRequirementsForAuthMethod(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean,
final IdentityVerificationMethod recoveryVerificationMethods
)
throws PwmUnrecoverableException
{
switch ( recoveryVerificationMethods )
{
case TOKEN:
{
ForgottenPasswordUtil.figureAvailableTokenDestinations( pwmRequestContext, forgottenPasswordBean );
}
break;
case ATTRIBUTES:
{
final List<FormConfiguration> formConfiguration = forgottenPasswordBean.getAttributeForm();
if ( formConfiguration == null || formConfiguration.isEmpty() )
{
final String errorMsg = "user is required to complete LDAP attribute check, yet there are no LDAP attribute form items configured";
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_INVALID_CONFIG, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
case OTP:
{
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
if ( userInfo.getOtpUserRecord() == null )
{
final String errorMsg = "could not find a one time password configuration for " + userInfo.getUserIdentity();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_OTP_CONFIGURATION, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
case CHALLENGE_RESPONSES:
{
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final Optional<ResponseSet> responseSet = ForgottenPasswordUtil.readResponseSet( pwmRequestContext, forgottenPasswordBean );
if ( responseSet.isEmpty() )
{
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_RESPONSES_NORESPONSES );
throw new PwmUnrecoverableException( errorInformation );
}
final ChallengeSet challengeSet = userInfo.getChallengeProfile().getChallengeSet()
.orElseThrow( () -> new PwmUnrecoverableException( PwmError.ERROR_NO_CHALLENGES ) );
try
{
if ( responseSet.get().meetsChallengeSetRequirements( challengeSet ) )
{
if ( challengeSet.getRequiredChallenges().isEmpty() && ( challengeSet.getMinRandomRequired() <= 0 ) )
{
final String errorMsg = "configured challenge set policy for "
+ userInfo.getUserIdentity().toString() + " is empty, user not qualified to recover password";
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
}
catch ( final ChaiValidationException e )
{
final String errorMsg = "stored response set for user '"
+ userInfo.getUserIdentity() + "' do not meet current challenge set requirements: " + e.getLocalizedMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_RESPONSES_NORESPONSES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
default:
// continue, assume no data requirements for method.
break;
}
}
static Map<Challenge, String> readResponsesFromHttpRequest(
final PwmRequest req,
final ChallengeSetBean challengeSet
)
throws PwmUnrecoverableException
{
final Map<Challenge, String> responses = new LinkedHashMap<>();
int counter = 0;
for ( final ChallengeBean loopChallenge : challengeSet.getChallenges() )
{
counter++;
final String answer = req.readParameterAsString( PwmConstants.PARAM_RESPONSE_PREFIX + counter );
responses.put( ChaiChallenge.fromChallengeBean( loopChallenge ), answer.length() > 0 ? answer : "" );
}
return responses;
}
static Map<Challenge, String> readResponsesFromMap(
final ChallengeSetBean challengeSet,
final Map<String, String> formData
)
{
final Map<Challenge, String> responses = new LinkedHashMap<>();
int counter = 0;
for ( final ChallengeBean loopChallenge : challengeSet.getChallenges() )
{
counter++;
final String answer = formData.get( PwmConstants.PARAM_RESPONSE_PREFIX + counter );
responses.put( ChaiChallenge.fromChallengeBean( loopChallenge ), answer.length() > 0 ? answer : "" );
}
return responses;
}
static void initializeAndSendToken(
final PwmRequestContext pwmRequestContext,
final UserInfo userInfo,
final TokenDestinationItem tokenDestinationItem
)
throws PwmUnrecoverableException
{
TokenUtil.initializeAndSendToken(
pwmRequestContext,
TokenUtil.TokenInitAndSendRequest.builder()
.userInfo( userInfo )
.tokenDestinationItem( tokenDestinationItem )
.emailToSend( PwmSetting.EMAIL_CHALLENGE_TOKEN )
.tokenType( TokenType.FORGOTTEN_PW )
.smsToSend( PwmSetting.SMS_CHALLENGE_TOKEN_TEXT )
.build()
);
StatisticsClient.incrementStat( pwmRequestContext.getPwmApplication(), Statistic.RECOVERY_TOKENS_SENT );
}
static void doActionSendNewPassword( final PwmRequest pwmRequest )
throws ChaiUnavailableException, IOException, ServletException, PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequest.getPwmDomain();
final ForgottenPasswordBean forgottenPasswordBean = ForgottenPasswordServlet.forgottenPasswordBean( pwmRequest );
final ForgottenPasswordProfile forgottenPasswordProfile = forgottenPasswordProfile( pwmRequest.getPwmDomain(), pwmRequest.getLabel(), forgottenPasswordBean );
final RecoveryAction recoveryAction = ForgottenPasswordUtil.getRecoveryAction( pwmDomain.getConfig(), forgottenPasswordBean );
LOGGER.trace( pwmRequest, () -> "beginning process to send new password to user" );
if ( !forgottenPasswordBean.getProgress().isAllPassed() )
{
return;
}
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final ChaiUser theUser = pwmRequest.getPwmDomain().getProxiedChaiUser( pwmRequest.getLabel(), userIdentity );
try
{
// try unlocking user
theUser.unlockPassword();
LOGGER.trace( pwmRequest, () -> "unlock account succeeded" );
}
catch ( final ChaiOperationException e )
{
final String errorMsg = "unable to unlock user " + theUser.getEntryDN() + " error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_UNLOCK_FAILURE, errorMsg );
LOGGER.error( pwmRequest, errorInformation::toDebugStr );
pwmRequest.respondWithError( errorInformation );
return;
}
try
{
final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(
pwmRequest.getPwmApplication(),
pwmRequest.getLabel(),
userIdentity,
pwmRequest.getLocale()
);
LOGGER.info( pwmRequest, () -> "user successfully supplied password recovery responses, emailing new password to: "
+ theUser.getEntryDN() );
// create new password
final PasswordData newPassword = PasswordUtility.generateRandom(
pwmRequest.getLabel(),
userInfo.getPasswordPolicy(),
pwmDomain );
LOGGER.trace( pwmRequest, () -> "generated random password value based on password policy for "
+ userIdentity.toDisplayString() );
// set the password
try
{
theUser.setPassword( newPassword.getStringValue() );
LOGGER.trace( pwmRequest, () -> "set user " + userIdentity.toDisplayString()
+ " password to system generated random value" );
}
catch ( final ChaiException e )
{
throw PwmUnrecoverableException.fromChaiException( e );
}
if ( recoveryAction == RecoveryAction.SENDNEWPW_AND_EXPIRE )
{
LOGGER.debug( pwmRequest, () -> "marking user " + userIdentity.toDisplayString() + " password as expired" );
theUser.expirePassword();
}
// mark the event log
{
final AuditRecord auditRecord = AuditRecordFactory.make( pwmRequest ).createUserAuditRecord(
AuditEvent.RECOVER_PASSWORD,
userIdentity,
pwmRequest.getLabel()
);
AuditServiceClient.submit( pwmRequest, auditRecord );
}
final MessageSendMethod messageSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_SENDNEWPW_METHOD, MessageSendMethod.class );
// send email or SMS
final String toAddress = PasswordUtility.sendNewPassword(
userInfo,
pwmDomain,
newPassword,
pwmRequest.getLocale(),
messageSendMethod
);
pwmRequest.getPwmResponse().forwardToSuccessPage( Message.Success_PasswordSend, toAddress );
}
catch ( final PwmException e )
{
LOGGER.warn( pwmRequest, () -> "unexpected error setting new password during recovery process for user: " + e.getMessage() );
pwmRequest.respondWithError( e.getErrorInformation() );
}
catch ( final ChaiOperationException e )
{
final ErrorInformation errorInformation = new ErrorInformation(
PwmError.ERROR_INTERNAL,
"unexpected ldap error while processing recovery action " + recoveryAction + ", error: " + e.getMessage()
);
LOGGER.warn( pwmRequest, errorInformation::toDebugStr );
pwmRequest.respondWithError( errorInformation );
}
finally
{
ForgottenPasswordServlet.clearForgottenPasswordBean( pwmRequest );
final PwmSession pwmSession = pwmRequest.getPwmSession();
// the user should not be authenticated, this is a safety method
pwmSession.unAuthenticateUser( pwmRequest );
// the password set flag should not have been set, this is a safety method
pwmSession.getSessionStateBean().setPasswordModified( false );
}
}
static void initBogusForgottenPasswordBean( final PwmRequestContext pwmRequestContext, final ForgottenPasswordBean forgottenPasswordBean )
throws PwmUnrecoverableException
{
forgottenPasswordBean.setUserIdentity( null );
forgottenPasswordBean.setPresentableChallengeSet( null );
final List<Challenge> challengeList;
{
final ProfileID firstProfile = pwmRequestContext.getDomainConfig().getChallengeProfileIDs().get( 0 );
final ChallengeSet challengeSet = pwmRequestContext.getDomainConfig().getChallengeProfile( firstProfile, PwmConstants.DEFAULT_LOCALE ).getChallengeSet()
.orElseThrow( () -> new PwmUnrecoverableException( PwmError.ERROR_NO_CHALLENGES.toInfo() ) );
challengeList = new ArrayList<>( challengeSet.getRequiredChallenges() );
for ( int i = 0; i < challengeSet.getMinRandomRequired(); i++ )
{
challengeList.add( challengeSet.getRandomChallenges().get( i ) );
}
}
final List<FormConfiguration> formData = new ArrayList<>( challengeList.size() );
{
int counter = 0;
for ( final Challenge challenge: challengeList )
{
final FormConfiguration formConfiguration = FormConfiguration.builder()
.name( "challenge" + counter++ )
.type( FormConfiguration.Type.text )
.labels( Collections.singletonMap( "", challenge.getChallengeText() ) )
.minimumLength( challenge.getMinLength() )
.maximumLength( challenge.getMaxLength() )
.source( FormConfiguration.Source.bogus )
.build();
formData.add( formConfiguration );
}
}
forgottenPasswordBean.setAttributeForm( formData );
forgottenPasswordBean.setBogusUser( true );
{
final ProfileID profileID = pwmRequestContext.getDomainConfig().getForgottenPasswordProfiles().keySet().iterator().next();
forgottenPasswordBean.setForgottenPasswordProfileID( profileID );
}
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = new ForgottenPasswordBean.RecoveryFlags(
false,
Collections.singleton( IdentityVerificationMethod.ATTRIBUTES ),
Collections.emptySet(),
0
);
forgottenPasswordBean.getProgress().setInProgressVerificationMethod( IdentityVerificationMethod.ATTRIBUTES );
forgottenPasswordBean.setRecoveryFlags( recoveryFlags );
}
public static boolean permitPwChangeDuringMinLifetime(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final UserIdentity userIdentity
)
{
ForgottenPasswordProfile forgottenPasswordProfile = null;
try
{
forgottenPasswordProfile = ForgottenPasswordUtil.forgottenPasswordProfile(
pwmDomain,
sessionLabel,
userIdentity
);
}
catch ( final PwmUnrecoverableException e )
{
LOGGER.debug( sessionLabel, () -> "can't read user's forgotten password profile - assuming no profile assigned, error: " + e.getMessage() );
}
if ( forgottenPasswordProfile == null )
{
// default is true.
return true;
}
final RecoveryMinLifetimeOption option = forgottenPasswordProfile.readSettingAsEnum(
PwmSetting.RECOVERY_MINIMUM_PASSWORD_LIFETIME_OPTIONS,
RecoveryMinLifetimeOption.class
);
return option == RecoveryMinLifetimeOption.ALLOW;
}
private static ForgottenPasswordProfile forgottenPasswordProfile(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
final Optional<ProfileID> profileID = ProfileUtility.discoverProfileIDForUser(
pwmDomain,
sessionLabel,
userIdentity,
ProfileDefinition.ForgottenPassword
);
if ( profileID.isPresent() )
{
return pwmDomain.getConfig().getForgottenPasswordProfiles().get( profileID.get() );
}
final String msg = "user does not have a forgotten password profile assigned";
throw PwmUnrecoverableException.newException( PwmError.ERROR_NO_PROFILE_ASSIGNED, msg );
}
static ForgottenPasswordProfile forgottenPasswordProfile(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final ForgottenPasswordBean forgottenPasswordBean
)
{
final ProfileID forgottenProfileID = forgottenPasswordBean.getForgottenPasswordProfileID();
if ( forgottenProfileID == null )
{
throw new IllegalStateException( "cannot load forgotten profile without ID registered in bean" );
}
final ForgottenPasswordProfile profile = pwmDomain.getConfig().getForgottenPasswordProfiles().get( forgottenProfileID );
if ( profile == null )
{
LOGGER.trace( sessionLabel, () -> "forgotten password bean references an invalid profile, clearing value in bean" );
forgottenPasswordBean.setForgottenPasswordProfileID( null );
}
return profile;
}
static void initForgottenPasswordBean(
final PwmRequestContext pwmRequestContext,
final UserIdentity userIdentity,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException, PwmOperationalException
{
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final Locale locale = pwmRequestContext.getLocale();
final SessionLabel sessionLabel = pwmRequestContext.getSessionLabel();
forgottenPasswordBean.setUserIdentity( userIdentity );
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final ForgottenPasswordProfile forgottenPasswordProfile = forgottenPasswordProfile(
pwmDomain,
pwmRequestContext.getSessionLabel(),
userIdentity
);
final ProfileID forgottenProfileID = forgottenPasswordProfile.getId();
forgottenPasswordBean.setForgottenPasswordProfileID( forgottenProfileID );
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = calculateRecoveryFlags(
pwmDomain,
forgottenProfileID
);
final ChallengeSet challengeSet;
if ( recoveryFlags.getRequiredAuthMethods().contains( IdentityVerificationMethod.CHALLENGE_RESPONSES )
|| recoveryFlags.getOptionalAuthMethods().contains( IdentityVerificationMethod.CHALLENGE_RESPONSES ) )
{
final Optional<ResponseSet> responseSet;
try
{
final ChaiUser theUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userInfo.getUserIdentity() );
responseSet = pwmDomain.getCrService().readUserResponseSet(
sessionLabel,
userInfo.getUserIdentity(),
theUser
);
challengeSet = responseSet.isEmpty() ? null : responseSet.get().getPresentableChallengeSet();
}
catch ( final ChaiValidationException e )
{
final String errorMsg = "unable to determine presentable challengeSet for stored responses: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
else
{
challengeSet = null;
}
if ( !recoveryFlags.isAllowWhenLdapIntruderLocked() )
{
try
{
final ChaiUser chaiUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userInfo.getUserIdentity() );
if ( chaiUser.isPasswordLocked() )
{
throw new PwmUnrecoverableException( new ErrorInformation( PwmError.ERROR_INTRUDER_LDAP ) );
}
}
catch ( final ChaiOperationException e )
{
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_INTERNAL,
"error checking user '" + userInfo.getUserIdentity() + "' ldap intruder lock status: " + e.getMessage() );
LOGGER.error( sessionLabel, errorInformation );
throw new PwmUnrecoverableException( errorInformation );
}
catch ( final ChaiUnavailableException e )
{
throw new PwmUnrecoverableException( PwmError.forChaiError( e.getErrorCode() ).orElse( PwmError.ERROR_INTERNAL ) );
}
}
final List<FormConfiguration> attributeForm = figureAttributeForm( forgottenPasswordProfile, forgottenPasswordBean, pwmRequestContext );
forgottenPasswordBean.setUserLocale( locale );
forgottenPasswordBean.setPresentableChallengeSet( challengeSet == null ? null : challengeSet.asChallengeSetBean() );
forgottenPasswordBean.setAttributeForm( attributeForm );
forgottenPasswordBean.setRecoveryFlags( recoveryFlags );
forgottenPasswordBean.setProgress( new ForgottenPasswordBean.Progress() );
for ( final IdentityVerificationMethod recoveryVerificationMethods : recoveryFlags.getRequiredAuthMethods() )
{
verifyRequirementsForAuthMethod( pwmRequestContext, forgottenPasswordBean, recoveryVerificationMethods );
}
}
static List<FormConfiguration> figureAttributeForm(
final ForgottenPasswordProfile forgottenPasswordProfile,
final ForgottenPasswordBean forgottenPasswordBean,
final PwmRequestContext pwmRequestContext
)
throws PwmOperationalException, PwmUnrecoverableException
{
final List<FormConfiguration> requiredAttributesForm = forgottenPasswordProfile.readSettingAsForm( PwmSetting.RECOVERY_ATTRIBUTE_FORM );
if ( requiredAttributesForm.isEmpty() )
{
return requiredAttributesForm;
}
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final List<FormConfiguration> returnList = new ArrayList<>();
for ( final FormConfiguration formItem : requiredAttributesForm )
{
if ( formItem.isRequired() )
{
returnList.add( formItem );
}
else
{
try
{
final String currentValue = userInfo.readStringAttribute( formItem.getName() );
if ( currentValue != null && currentValue.length() > 0 )
{
returnList.add( formItem );
}
else
{
LOGGER.trace( pwmRequestContext.getSessionLabel(), () -> "excluding optional required attribute(" + formItem.getName() + "), user has no value" );
}
}
catch ( final PwmUnrecoverableException e )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, "unexpected error reading value for attribute " + formItem.getName() ) );
}
}
}
if ( returnList.isEmpty() )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, "user has no values for any optional attribute" ) );
}
return returnList;
}
static ForgottenPasswordBean.RecoveryFlags calculateRecoveryFlags(
final PwmDomain pwmDomain,
final ProfileID forgottenPasswordProfileID
)
{
final DomainConfig config = pwmDomain.getConfig();
final ForgottenPasswordProfile forgottenPasswordProfile = config.getForgottenPasswordProfiles().get( forgottenPasswordProfileID );
final Set<IdentityVerificationMethod> requiredRecoveryVerificationMethods = forgottenPasswordProfile.requiredRecoveryAuthenticationMethods();
final Set<IdentityVerificationMethod> optionalRecoveryVerificationMethods = forgottenPasswordProfile.optionalRecoveryAuthenticationMethods();
final int minimumOptionalRecoveryAuthMethods = forgottenPasswordProfile.getMinOptionalRequired();
final boolean allowWhenLdapIntruderLocked = forgottenPasswordProfile.readSettingAsBoolean( PwmSetting.RECOVERY_ALLOW_WHEN_LOCKED );
return new ForgottenPasswordBean.RecoveryFlags(
allowWhenLdapIntruderLocked,
requiredRecoveryVerificationMethods,
optionalRecoveryVerificationMethods,
minimumOptionalRecoveryAuthMethods
);
}
static boolean hasOtherMethodChoices(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean,
final IdentityVerificationMethod thisMethod
)
{
if ( forgottenPasswordBean.getRecoveryFlags().getRequiredAuthMethods().contains( thisMethod ) )
{
return false;
}
{
// check if previously satisfied any other optional methods.
final Set<IdentityVerificationMethod> optionalAuthMethods = forgottenPasswordBean.getRecoveryFlags().getOptionalAuthMethods();
final Set<IdentityVerificationMethod> satisfiedMethods = forgottenPasswordBean.getProgress().getSatisfiedMethods();
final boolean disJoint = Collections.disjoint( optionalAuthMethods, satisfiedMethods );
if ( !disJoint )
{
return true;
}
}
{
final Set<IdentityVerificationMethod> remainingAvailableOptionalMethods = ForgottenPasswordUtil.figureRemainingAvailableOptionalAuthMethods(
pwmRequestContext,
forgottenPasswordBean
);
final Set<IdentityVerificationMethod> otherOptionalMethodChoices = CollectionUtil.copyToEnumSet( remainingAvailableOptionalMethods, IdentityVerificationMethod.class );
otherOptionalMethodChoices.remove( thisMethod );
return !otherOptionalMethodChoices.isEmpty();
}
}
}
|
UTF-8
|
Java
| 38,020 |
java
|
ForgottenPasswordUtil.java
|
Java
|
[] | null |
[] |
/*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2021 The PWM Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package password.pwm.http.servlet.forgottenpw;
import com.novell.ldapchai.ChaiUser;
import com.novell.ldapchai.cr.ChaiChallenge;
import com.novell.ldapchai.cr.Challenge;
import com.novell.ldapchai.cr.ChallengeSet;
import com.novell.ldapchai.cr.ResponseSet;
import com.novell.ldapchai.cr.bean.ChallengeBean;
import com.novell.ldapchai.cr.bean.ChallengeSetBean;
import com.novell.ldapchai.exception.ChaiException;
import com.novell.ldapchai.exception.ChaiOperationException;
import com.novell.ldapchai.exception.ChaiUnavailableException;
import com.novell.ldapchai.exception.ChaiValidationException;
import password.pwm.AppProperty;
import password.pwm.PwmConstants;
import password.pwm.PwmDomain;
import password.pwm.bean.EmailItemBean;
import password.pwm.bean.ProfileID;
import password.pwm.bean.SessionLabel;
import password.pwm.bean.TokenDestinationItem;
import password.pwm.bean.UserIdentity;
import password.pwm.config.DomainConfig;
import password.pwm.config.PwmSetting;
import password.pwm.config.option.IdentityVerificationMethod;
import password.pwm.config.option.MessageSendMethod;
import password.pwm.config.option.RecoveryAction;
import password.pwm.config.option.RecoveryMinLifetimeOption;
import password.pwm.config.profile.ForgottenPasswordProfile;
import password.pwm.config.profile.ProfileDefinition;
import password.pwm.config.profile.ProfileUtility;
import password.pwm.config.value.data.FormConfiguration;
import password.pwm.error.ErrorInformation;
import password.pwm.error.PwmError;
import password.pwm.error.PwmException;
import password.pwm.error.PwmOperationalException;
import password.pwm.error.PwmUnrecoverableException;
import password.pwm.http.PwmRequest;
import password.pwm.http.PwmRequestContext;
import password.pwm.http.PwmSession;
import password.pwm.http.auth.HttpAuthRecord;
import password.pwm.http.bean.ForgottenPasswordBean;
import password.pwm.i18n.Message;
import password.pwm.ldap.LdapOperationsHelper;
import password.pwm.ldap.UserInfoFactory;
import password.pwm.svc.event.AuditEvent;
import password.pwm.svc.event.AuditRecord;
import password.pwm.svc.event.AuditRecordFactory;
import password.pwm.svc.event.AuditServiceClient;
import password.pwm.svc.stats.Statistic;
import password.pwm.svc.stats.StatisticsClient;
import password.pwm.svc.token.TokenType;
import password.pwm.svc.token.TokenUtil;
import password.pwm.user.UserInfo;
import password.pwm.util.PasswordData;
import password.pwm.util.java.CollectionUtil;
import password.pwm.util.logging.PwmLogger;
import password.pwm.util.macro.MacroRequest;
import password.pwm.util.password.PasswordUtility;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class ForgottenPasswordUtil
{
private static final PwmLogger LOGGER = PwmLogger.forClass( ForgottenPasswordUtil.class );
static Set<IdentityVerificationMethod> figureRemainingAvailableOptionalAuthMethods(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
{
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = forgottenPasswordBean.getRecoveryFlags();
final ForgottenPasswordBean.Progress progress = forgottenPasswordBean.getProgress();
final Set<IdentityVerificationMethod> result = new LinkedHashSet<>( recoveryFlags.getOptionalAuthMethods() );
result.removeAll( progress.getSatisfiedMethods() );
for ( final IdentityVerificationMethod recoveryVerificationMethods : new LinkedHashSet<>( result ) )
{
try
{
verifyRequirementsForAuthMethod( pwmRequestContext, forgottenPasswordBean, recoveryVerificationMethods );
}
catch ( final PwmUnrecoverableException e )
{
result.remove( recoveryVerificationMethods );
}
}
return Collections.unmodifiableSet( result );
}
static RecoveryAction getRecoveryAction( final DomainConfig domainConfig, final ForgottenPasswordBean forgottenPasswordBean )
{
final ForgottenPasswordProfile forgottenPasswordProfile = domainConfig.getForgottenPasswordProfiles().get( forgottenPasswordBean.getForgottenPasswordProfileID() );
return forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_ACTION, RecoveryAction.class );
}
static Set<IdentityVerificationMethod> figureSatisfiedOptionalAuthMethods(
final ForgottenPasswordBean.RecoveryFlags recoveryFlags,
final ForgottenPasswordBean.Progress progress )
{
final Set<IdentityVerificationMethod> result = new LinkedHashSet<>( recoveryFlags.getOptionalAuthMethods() );
result.retainAll( progress.getSatisfiedMethods() );
return Collections.unmodifiableSet( result );
}
public static Optional<UserInfo> readUserInfo(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
if ( forgottenPasswordBean.getUserIdentity() == null )
{
return Optional.empty();
}
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
return Optional.of( UserInfoFactory.newUserInfoUsingProxy(
pwmRequestContext.getPwmApplication(),
pwmRequestContext.getSessionLabel(),
userIdentity,
pwmRequestContext.getLocale() ) );
}
static Optional<ResponseSet> readResponseSet(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
if ( forgottenPasswordBean.getUserIdentity() == null )
{
return Optional.empty();
}
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final ChaiUser theUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userIdentity );
return pwmDomain.getCrService().readUserResponseSet(
pwmRequestContext.getSessionLabel(),
userIdentity,
theUser );
}
static void sendUnlockNoticeEmail(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final DomainConfig config = pwmRequestContext.getDomainConfig();
final Locale locale = pwmRequestContext.getLocale();
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final EmailItemBean configuredEmailSetting = config.readSettingAsEmail( PwmSetting.EMAIL_UNLOCK, locale );
if ( configuredEmailSetting == null )
{
LOGGER.debug( pwmRequestContext.getSessionLabel(), () -> "skipping send unlock notice email for '" + userIdentity + "' no email configured" );
return;
}
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final MacroRequest macroRequest = MacroRequest.forUser(
pwmRequestContext.getPwmApplication(),
pwmRequestContext.getSessionLabel(),
userInfo,
null
);
pwmDomain.getPwmApplication().getEmailQueue().submitEmail(
configuredEmailSetting,
userInfo,
macroRequest
);
}
static boolean checkAuthRecord(
final PwmRequest pwmRequest,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequest.getPwmApplication().domains().get( userIdentity.getDomainID() );
final Optional<String> userGuid = LdapOperationsHelper.readLdapGuidValue(
pwmDomain,
pwmRequest.getLabel(),
userIdentity );
if ( userGuid.isEmpty() )
{
return false;
}
try
{
final String cookieName = pwmDomain.getConfig().readAppProperty( AppProperty.HTTP_COOKIE_AUTHRECORD_NAME );
if ( cookieName == null || cookieName.isEmpty() )
{
LOGGER.trace( pwmRequest, () -> "skipping auth record cookie read, cookie name parameter is blank" );
return false;
}
final Optional<HttpAuthRecord> optionalHttpAuthRecord = pwmRequest.readEncryptedCookie( cookieName, HttpAuthRecord.class );
if ( optionalHttpAuthRecord.isPresent() )
{
final HttpAuthRecord httpAuthRecord = optionalHttpAuthRecord.get();
if ( userGuid.get().equals( httpAuthRecord.getGuid() ) )
{
LOGGER.debug( pwmRequest, () -> "auth record cookie validated" );
return true;
}
}
}
catch ( final Exception e )
{
LOGGER.error( pwmRequest, () -> "unexpected error while examining cookie auth record: " + e.getMessage() );
}
return false;
}
static List<TokenDestinationItem> figureAvailableTokenDestinations(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException
{
final ProfileID profileID = forgottenPasswordBean.getForgottenPasswordProfileID();
final ForgottenPasswordProfile forgottenPasswordProfile = pwmRequestContext.getDomainConfig().getForgottenPasswordProfiles().get( profileID );
final MessageSendMethod tokenSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_TOKEN_SEND_METHOD, MessageSendMethod.class );
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
return TokenUtil.figureAvailableTokenDestinations(
pwmRequestContext.getPwmDomain(),
pwmRequestContext.getSessionLabel(),
pwmRequestContext.getLocale(),
userInfo,
tokenSendMethod
);
}
static void verifyRequirementsForAuthMethod(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean,
final IdentityVerificationMethod recoveryVerificationMethods
)
throws PwmUnrecoverableException
{
switch ( recoveryVerificationMethods )
{
case TOKEN:
{
ForgottenPasswordUtil.figureAvailableTokenDestinations( pwmRequestContext, forgottenPasswordBean );
}
break;
case ATTRIBUTES:
{
final List<FormConfiguration> formConfiguration = forgottenPasswordBean.getAttributeForm();
if ( formConfiguration == null || formConfiguration.isEmpty() )
{
final String errorMsg = "user is required to complete LDAP attribute check, yet there are no LDAP attribute form items configured";
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_INVALID_CONFIG, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
case OTP:
{
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
if ( userInfo.getOtpUserRecord() == null )
{
final String errorMsg = "could not find a one time password configuration for " + userInfo.getUserIdentity();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_OTP_CONFIGURATION, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
case CHALLENGE_RESPONSES:
{
final UserInfo userInfo = ForgottenPasswordUtil.readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final Optional<ResponseSet> responseSet = ForgottenPasswordUtil.readResponseSet( pwmRequestContext, forgottenPasswordBean );
if ( responseSet.isEmpty() )
{
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_RESPONSES_NORESPONSES );
throw new PwmUnrecoverableException( errorInformation );
}
final ChallengeSet challengeSet = userInfo.getChallengeProfile().getChallengeSet()
.orElseThrow( () -> new PwmUnrecoverableException( PwmError.ERROR_NO_CHALLENGES ) );
try
{
if ( responseSet.get().meetsChallengeSetRequirements( challengeSet ) )
{
if ( challengeSet.getRequiredChallenges().isEmpty() && ( challengeSet.getMinRandomRequired() <= 0 ) )
{
final String errorMsg = "configured challenge set policy for "
+ userInfo.getUserIdentity().toString() + " is empty, user not qualified to recover password";
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
}
catch ( final ChaiValidationException e )
{
final String errorMsg = "stored response set for user '"
+ userInfo.getUserIdentity() + "' do not meet current challenge set requirements: " + e.getLocalizedMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_RESPONSES_NORESPONSES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
break;
default:
// continue, assume no data requirements for method.
break;
}
}
static Map<Challenge, String> readResponsesFromHttpRequest(
final PwmRequest req,
final ChallengeSetBean challengeSet
)
throws PwmUnrecoverableException
{
final Map<Challenge, String> responses = new LinkedHashMap<>();
int counter = 0;
for ( final ChallengeBean loopChallenge : challengeSet.getChallenges() )
{
counter++;
final String answer = req.readParameterAsString( PwmConstants.PARAM_RESPONSE_PREFIX + counter );
responses.put( ChaiChallenge.fromChallengeBean( loopChallenge ), answer.length() > 0 ? answer : "" );
}
return responses;
}
static Map<Challenge, String> readResponsesFromMap(
final ChallengeSetBean challengeSet,
final Map<String, String> formData
)
{
final Map<Challenge, String> responses = new LinkedHashMap<>();
int counter = 0;
for ( final ChallengeBean loopChallenge : challengeSet.getChallenges() )
{
counter++;
final String answer = formData.get( PwmConstants.PARAM_RESPONSE_PREFIX + counter );
responses.put( ChaiChallenge.fromChallengeBean( loopChallenge ), answer.length() > 0 ? answer : "" );
}
return responses;
}
static void initializeAndSendToken(
final PwmRequestContext pwmRequestContext,
final UserInfo userInfo,
final TokenDestinationItem tokenDestinationItem
)
throws PwmUnrecoverableException
{
TokenUtil.initializeAndSendToken(
pwmRequestContext,
TokenUtil.TokenInitAndSendRequest.builder()
.userInfo( userInfo )
.tokenDestinationItem( tokenDestinationItem )
.emailToSend( PwmSetting.EMAIL_CHALLENGE_TOKEN )
.tokenType( TokenType.FORGOTTEN_PW )
.smsToSend( PwmSetting.SMS_CHALLENGE_TOKEN_TEXT )
.build()
);
StatisticsClient.incrementStat( pwmRequestContext.getPwmApplication(), Statistic.RECOVERY_TOKENS_SENT );
}
static void doActionSendNewPassword( final PwmRequest pwmRequest )
throws ChaiUnavailableException, IOException, ServletException, PwmUnrecoverableException
{
final PwmDomain pwmDomain = pwmRequest.getPwmDomain();
final ForgottenPasswordBean forgottenPasswordBean = ForgottenPasswordServlet.forgottenPasswordBean( pwmRequest );
final ForgottenPasswordProfile forgottenPasswordProfile = forgottenPasswordProfile( pwmRequest.getPwmDomain(), pwmRequest.getLabel(), forgottenPasswordBean );
final RecoveryAction recoveryAction = ForgottenPasswordUtil.getRecoveryAction( pwmDomain.getConfig(), forgottenPasswordBean );
LOGGER.trace( pwmRequest, () -> "beginning process to send new password to user" );
if ( !forgottenPasswordBean.getProgress().isAllPassed() )
{
return;
}
final UserIdentity userIdentity = forgottenPasswordBean.getUserIdentity();
final ChaiUser theUser = pwmRequest.getPwmDomain().getProxiedChaiUser( pwmRequest.getLabel(), userIdentity );
try
{
// try unlocking user
theUser.unlockPassword();
LOGGER.trace( pwmRequest, () -> "unlock account succeeded" );
}
catch ( final ChaiOperationException e )
{
final String errorMsg = "unable to unlock user " + theUser.getEntryDN() + " error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_UNLOCK_FAILURE, errorMsg );
LOGGER.error( pwmRequest, errorInformation::toDebugStr );
pwmRequest.respondWithError( errorInformation );
return;
}
try
{
final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(
pwmRequest.getPwmApplication(),
pwmRequest.getLabel(),
userIdentity,
pwmRequest.getLocale()
);
LOGGER.info( pwmRequest, () -> "user successfully supplied password recovery responses, emailing new password to: "
+ theUser.getEntryDN() );
// create new password
final PasswordData newPassword = PasswordUtility.generateRandom(
pwmRequest.getLabel(),
userInfo.getPasswordPolicy(),
pwmDomain );
LOGGER.trace( pwmRequest, () -> "generated random password value based on password policy for "
+ userIdentity.toDisplayString() );
// set the password
try
{
theUser.setPassword( newPassword.getStringValue() );
LOGGER.trace( pwmRequest, () -> "set user " + userIdentity.toDisplayString()
+ " password to system generated random value" );
}
catch ( final ChaiException e )
{
throw PwmUnrecoverableException.fromChaiException( e );
}
if ( recoveryAction == RecoveryAction.SENDNEWPW_AND_EXPIRE )
{
LOGGER.debug( pwmRequest, () -> "marking user " + userIdentity.toDisplayString() + " password as expired" );
theUser.expirePassword();
}
// mark the event log
{
final AuditRecord auditRecord = AuditRecordFactory.make( pwmRequest ).createUserAuditRecord(
AuditEvent.RECOVER_PASSWORD,
userIdentity,
pwmRequest.getLabel()
);
AuditServiceClient.submit( pwmRequest, auditRecord );
}
final MessageSendMethod messageSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_SENDNEWPW_METHOD, MessageSendMethod.class );
// send email or SMS
final String toAddress = PasswordUtility.sendNewPassword(
userInfo,
pwmDomain,
newPassword,
pwmRequest.getLocale(),
messageSendMethod
);
pwmRequest.getPwmResponse().forwardToSuccessPage( Message.Success_PasswordSend, toAddress );
}
catch ( final PwmException e )
{
LOGGER.warn( pwmRequest, () -> "unexpected error setting new password during recovery process for user: " + e.getMessage() );
pwmRequest.respondWithError( e.getErrorInformation() );
}
catch ( final ChaiOperationException e )
{
final ErrorInformation errorInformation = new ErrorInformation(
PwmError.ERROR_INTERNAL,
"unexpected ldap error while processing recovery action " + recoveryAction + ", error: " + e.getMessage()
);
LOGGER.warn( pwmRequest, errorInformation::toDebugStr );
pwmRequest.respondWithError( errorInformation );
}
finally
{
ForgottenPasswordServlet.clearForgottenPasswordBean( pwmRequest );
final PwmSession pwmSession = pwmRequest.getPwmSession();
// the user should not be authenticated, this is a safety method
pwmSession.unAuthenticateUser( pwmRequest );
// the password set flag should not have been set, this is a safety method
pwmSession.getSessionStateBean().setPasswordModified( false );
}
}
static void initBogusForgottenPasswordBean( final PwmRequestContext pwmRequestContext, final ForgottenPasswordBean forgottenPasswordBean )
throws PwmUnrecoverableException
{
forgottenPasswordBean.setUserIdentity( null );
forgottenPasswordBean.setPresentableChallengeSet( null );
final List<Challenge> challengeList;
{
final ProfileID firstProfile = pwmRequestContext.getDomainConfig().getChallengeProfileIDs().get( 0 );
final ChallengeSet challengeSet = pwmRequestContext.getDomainConfig().getChallengeProfile( firstProfile, PwmConstants.DEFAULT_LOCALE ).getChallengeSet()
.orElseThrow( () -> new PwmUnrecoverableException( PwmError.ERROR_NO_CHALLENGES.toInfo() ) );
challengeList = new ArrayList<>( challengeSet.getRequiredChallenges() );
for ( int i = 0; i < challengeSet.getMinRandomRequired(); i++ )
{
challengeList.add( challengeSet.getRandomChallenges().get( i ) );
}
}
final List<FormConfiguration> formData = new ArrayList<>( challengeList.size() );
{
int counter = 0;
for ( final Challenge challenge: challengeList )
{
final FormConfiguration formConfiguration = FormConfiguration.builder()
.name( "challenge" + counter++ )
.type( FormConfiguration.Type.text )
.labels( Collections.singletonMap( "", challenge.getChallengeText() ) )
.minimumLength( challenge.getMinLength() )
.maximumLength( challenge.getMaxLength() )
.source( FormConfiguration.Source.bogus )
.build();
formData.add( formConfiguration );
}
}
forgottenPasswordBean.setAttributeForm( formData );
forgottenPasswordBean.setBogusUser( true );
{
final ProfileID profileID = pwmRequestContext.getDomainConfig().getForgottenPasswordProfiles().keySet().iterator().next();
forgottenPasswordBean.setForgottenPasswordProfileID( profileID );
}
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = new ForgottenPasswordBean.RecoveryFlags(
false,
Collections.singleton( IdentityVerificationMethod.ATTRIBUTES ),
Collections.emptySet(),
0
);
forgottenPasswordBean.getProgress().setInProgressVerificationMethod( IdentityVerificationMethod.ATTRIBUTES );
forgottenPasswordBean.setRecoveryFlags( recoveryFlags );
}
public static boolean permitPwChangeDuringMinLifetime(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final UserIdentity userIdentity
)
{
ForgottenPasswordProfile forgottenPasswordProfile = null;
try
{
forgottenPasswordProfile = ForgottenPasswordUtil.forgottenPasswordProfile(
pwmDomain,
sessionLabel,
userIdentity
);
}
catch ( final PwmUnrecoverableException e )
{
LOGGER.debug( sessionLabel, () -> "can't read user's forgotten password profile - assuming no profile assigned, error: " + e.getMessage() );
}
if ( forgottenPasswordProfile == null )
{
// default is true.
return true;
}
final RecoveryMinLifetimeOption option = forgottenPasswordProfile.readSettingAsEnum(
PwmSetting.RECOVERY_MINIMUM_PASSWORD_LIFETIME_OPTIONS,
RecoveryMinLifetimeOption.class
);
return option == RecoveryMinLifetimeOption.ALLOW;
}
private static ForgottenPasswordProfile forgottenPasswordProfile(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final UserIdentity userIdentity
)
throws PwmUnrecoverableException
{
final Optional<ProfileID> profileID = ProfileUtility.discoverProfileIDForUser(
pwmDomain,
sessionLabel,
userIdentity,
ProfileDefinition.ForgottenPassword
);
if ( profileID.isPresent() )
{
return pwmDomain.getConfig().getForgottenPasswordProfiles().get( profileID.get() );
}
final String msg = "user does not have a forgotten password profile assigned";
throw PwmUnrecoverableException.newException( PwmError.ERROR_NO_PROFILE_ASSIGNED, msg );
}
static ForgottenPasswordProfile forgottenPasswordProfile(
final PwmDomain pwmDomain,
final SessionLabel sessionLabel,
final ForgottenPasswordBean forgottenPasswordBean
)
{
final ProfileID forgottenProfileID = forgottenPasswordBean.getForgottenPasswordProfileID();
if ( forgottenProfileID == null )
{
throw new IllegalStateException( "cannot load forgotten profile without ID registered in bean" );
}
final ForgottenPasswordProfile profile = pwmDomain.getConfig().getForgottenPasswordProfiles().get( forgottenProfileID );
if ( profile == null )
{
LOGGER.trace( sessionLabel, () -> "forgotten password bean references an invalid profile, clearing value in bean" );
forgottenPasswordBean.setForgottenPasswordProfileID( null );
}
return profile;
}
static void initForgottenPasswordBean(
final PwmRequestContext pwmRequestContext,
final UserIdentity userIdentity,
final ForgottenPasswordBean forgottenPasswordBean
)
throws PwmUnrecoverableException, PwmOperationalException
{
final PwmDomain pwmDomain = pwmRequestContext.getPwmDomain();
final Locale locale = pwmRequestContext.getLocale();
final SessionLabel sessionLabel = pwmRequestContext.getSessionLabel();
forgottenPasswordBean.setUserIdentity( userIdentity );
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final ForgottenPasswordProfile forgottenPasswordProfile = forgottenPasswordProfile(
pwmDomain,
pwmRequestContext.getSessionLabel(),
userIdentity
);
final ProfileID forgottenProfileID = forgottenPasswordProfile.getId();
forgottenPasswordBean.setForgottenPasswordProfileID( forgottenProfileID );
final ForgottenPasswordBean.RecoveryFlags recoveryFlags = calculateRecoveryFlags(
pwmDomain,
forgottenProfileID
);
final ChallengeSet challengeSet;
if ( recoveryFlags.getRequiredAuthMethods().contains( IdentityVerificationMethod.CHALLENGE_RESPONSES )
|| recoveryFlags.getOptionalAuthMethods().contains( IdentityVerificationMethod.CHALLENGE_RESPONSES ) )
{
final Optional<ResponseSet> responseSet;
try
{
final ChaiUser theUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userInfo.getUserIdentity() );
responseSet = pwmDomain.getCrService().readUserResponseSet(
sessionLabel,
userInfo.getUserIdentity(),
theUser
);
challengeSet = responseSet.isEmpty() ? null : responseSet.get().getPresentableChallengeSet();
}
catch ( final ChaiValidationException e )
{
final String errorMsg = "unable to determine presentable challengeSet for stored responses: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, errorMsg );
throw new PwmUnrecoverableException( errorInformation );
}
}
else
{
challengeSet = null;
}
if ( !recoveryFlags.isAllowWhenLdapIntruderLocked() )
{
try
{
final ChaiUser chaiUser = pwmDomain.getProxiedChaiUser( pwmRequestContext.getSessionLabel(), userInfo.getUserIdentity() );
if ( chaiUser.isPasswordLocked() )
{
throw new PwmUnrecoverableException( new ErrorInformation( PwmError.ERROR_INTRUDER_LDAP ) );
}
}
catch ( final ChaiOperationException e )
{
final ErrorInformation errorInformation = new ErrorInformation( PwmError.ERROR_INTERNAL,
"error checking user '" + userInfo.getUserIdentity() + "' ldap intruder lock status: " + e.getMessage() );
LOGGER.error( sessionLabel, errorInformation );
throw new PwmUnrecoverableException( errorInformation );
}
catch ( final ChaiUnavailableException e )
{
throw new PwmUnrecoverableException( PwmError.forChaiError( e.getErrorCode() ).orElse( PwmError.ERROR_INTERNAL ) );
}
}
final List<FormConfiguration> attributeForm = figureAttributeForm( forgottenPasswordProfile, forgottenPasswordBean, pwmRequestContext );
forgottenPasswordBean.setUserLocale( locale );
forgottenPasswordBean.setPresentableChallengeSet( challengeSet == null ? null : challengeSet.asChallengeSetBean() );
forgottenPasswordBean.setAttributeForm( attributeForm );
forgottenPasswordBean.setRecoveryFlags( recoveryFlags );
forgottenPasswordBean.setProgress( new ForgottenPasswordBean.Progress() );
for ( final IdentityVerificationMethod recoveryVerificationMethods : recoveryFlags.getRequiredAuthMethods() )
{
verifyRequirementsForAuthMethod( pwmRequestContext, forgottenPasswordBean, recoveryVerificationMethods );
}
}
static List<FormConfiguration> figureAttributeForm(
final ForgottenPasswordProfile forgottenPasswordProfile,
final ForgottenPasswordBean forgottenPasswordBean,
final PwmRequestContext pwmRequestContext
)
throws PwmOperationalException, PwmUnrecoverableException
{
final List<FormConfiguration> requiredAttributesForm = forgottenPasswordProfile.readSettingAsForm( PwmSetting.RECOVERY_ATTRIBUTE_FORM );
if ( requiredAttributesForm.isEmpty() )
{
return requiredAttributesForm;
}
final UserInfo userInfo = readUserInfo( pwmRequestContext, forgottenPasswordBean ).orElseThrow();
final List<FormConfiguration> returnList = new ArrayList<>();
for ( final FormConfiguration formItem : requiredAttributesForm )
{
if ( formItem.isRequired() )
{
returnList.add( formItem );
}
else
{
try
{
final String currentValue = userInfo.readStringAttribute( formItem.getName() );
if ( currentValue != null && currentValue.length() > 0 )
{
returnList.add( formItem );
}
else
{
LOGGER.trace( pwmRequestContext.getSessionLabel(), () -> "excluding optional required attribute(" + formItem.getName() + "), user has no value" );
}
}
catch ( final PwmUnrecoverableException e )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, "unexpected error reading value for attribute " + formItem.getName() ) );
}
}
}
if ( returnList.isEmpty() )
{
throw new PwmOperationalException( new ErrorInformation( PwmError.ERROR_NO_CHALLENGES, "user has no values for any optional attribute" ) );
}
return returnList;
}
static ForgottenPasswordBean.RecoveryFlags calculateRecoveryFlags(
final PwmDomain pwmDomain,
final ProfileID forgottenPasswordProfileID
)
{
final DomainConfig config = pwmDomain.getConfig();
final ForgottenPasswordProfile forgottenPasswordProfile = config.getForgottenPasswordProfiles().get( forgottenPasswordProfileID );
final Set<IdentityVerificationMethod> requiredRecoveryVerificationMethods = forgottenPasswordProfile.requiredRecoveryAuthenticationMethods();
final Set<IdentityVerificationMethod> optionalRecoveryVerificationMethods = forgottenPasswordProfile.optionalRecoveryAuthenticationMethods();
final int minimumOptionalRecoveryAuthMethods = forgottenPasswordProfile.getMinOptionalRequired();
final boolean allowWhenLdapIntruderLocked = forgottenPasswordProfile.readSettingAsBoolean( PwmSetting.RECOVERY_ALLOW_WHEN_LOCKED );
return new ForgottenPasswordBean.RecoveryFlags(
allowWhenLdapIntruderLocked,
requiredRecoveryVerificationMethods,
optionalRecoveryVerificationMethods,
minimumOptionalRecoveryAuthMethods
);
}
static boolean hasOtherMethodChoices(
final PwmRequestContext pwmRequestContext,
final ForgottenPasswordBean forgottenPasswordBean,
final IdentityVerificationMethod thisMethod
)
{
if ( forgottenPasswordBean.getRecoveryFlags().getRequiredAuthMethods().contains( thisMethod ) )
{
return false;
}
{
// check if previously satisfied any other optional methods.
final Set<IdentityVerificationMethod> optionalAuthMethods = forgottenPasswordBean.getRecoveryFlags().getOptionalAuthMethods();
final Set<IdentityVerificationMethod> satisfiedMethods = forgottenPasswordBean.getProgress().getSatisfiedMethods();
final boolean disJoint = Collections.disjoint( optionalAuthMethods, satisfiedMethods );
if ( !disJoint )
{
return true;
}
}
{
final Set<IdentityVerificationMethod> remainingAvailableOptionalMethods = ForgottenPasswordUtil.figureRemainingAvailableOptionalAuthMethods(
pwmRequestContext,
forgottenPasswordBean
);
final Set<IdentityVerificationMethod> otherOptionalMethodChoices = CollectionUtil.copyToEnumSet( remainingAvailableOptionalMethods, IdentityVerificationMethod.class );
otherOptionalMethodChoices.remove( thisMethod );
return !otherOptionalMethodChoices.isEmpty();
}
}
}
| 38,020 | 0.649316 | 0.648475 | 872 | 42.600918 | 39.60738 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.524083 | false | false |
10
|
006550516eadd24a16fa76dcd2f699b33f727bdb
| 4,672,924,465,094 |
4e8432b4e9b1583a7b085835981eb8d0e61d5ca1
|
/projeto-admin/src/br/com/geprofi/controlador/ProfessorExternoController.java
|
b36e150b455f12fdeda05e5bc268504612021224
|
[] |
no_license
|
carinadiass/geprofi
|
https://github.com/carinadiass/geprofi
|
b951ae18cb16d9990f3e9b8415eed140b7003c6f
|
0449f182606a270cd1268a7fef771ca065233372
|
refs/heads/master
| 2021-01-19T07:31:40.515000 | 2015-11-25T03:08:24 | 2015-11-25T03:08:24 | 87,551,233 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.geprofi.controlador;
import java.sql.SQLException;
import java.util.List;
import javax.inject.Inject;
import javax.validation.Valid;
import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.validator.Validator;
import br.com.geprofi.modelo.ProfessorExterno;
import br.com.geprofi.modelo.dao.ProfessorExternoDao;
import br.com.caelum.vraptor.validator.Validator;
@Controller
public class ProfessorExternoController {
private ProfessorExternoDao dao;
@Inject
public ProfessorExternoController(ProfessorExternoDao dao){
this.dao=dao;
}
protected ProfessorExternoController(){this(null);}
public void formulario() {}
public void pfhome(int cod_professor) {}
public ProfessorExterno edita(int codProfessorExterno, Result result) {
ProfessorExterno professorExternoEncontrado = null;
try {
professorExternoEncontrado = dao.buscaPorCodProfessorExterno(codProfessorExterno);
result.include(professorExternoEncontrado);
result.of(this).formulario();
return professorExternoEncontrado;
} catch (SQLException e) {
e.printStackTrace();
}
return professorExternoEncontrado;
}
public void salva(@Valid ProfessorExterno professorExterno,int codUsuario,Result result, Validator validator) {
try {
validator.onErrorRedirectTo(ProfessoresController.class).pfhome(codUsuario,result);
dao.adiciona(professorExterno,codUsuario);
result.include("mensagem", "Professor Externo salvo com sucesso!");
result.redirectTo(ProfessoresController.class).pfhome(codUsuario, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<ProfessorExterno> lista() {
try {
return dao.todos();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void delete(int codProfessorExterno,int codUsuario, Result result){
try {
dao.deleta(codProfessorExterno);
result.include("mensagem", "Professor Externo deletado com sucesso!");
result.redirectTo(ProfessoresController.class).pfhome(codUsuario, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 2,185 |
java
|
ProfessorExternoController.java
|
Java
|
[] | null |
[] |
package br.com.geprofi.controlador;
import java.sql.SQLException;
import java.util.List;
import javax.inject.Inject;
import javax.validation.Valid;
import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.validator.Validator;
import br.com.geprofi.modelo.ProfessorExterno;
import br.com.geprofi.modelo.dao.ProfessorExternoDao;
import br.com.caelum.vraptor.validator.Validator;
@Controller
public class ProfessorExternoController {
private ProfessorExternoDao dao;
@Inject
public ProfessorExternoController(ProfessorExternoDao dao){
this.dao=dao;
}
protected ProfessorExternoController(){this(null);}
public void formulario() {}
public void pfhome(int cod_professor) {}
public ProfessorExterno edita(int codProfessorExterno, Result result) {
ProfessorExterno professorExternoEncontrado = null;
try {
professorExternoEncontrado = dao.buscaPorCodProfessorExterno(codProfessorExterno);
result.include(professorExternoEncontrado);
result.of(this).formulario();
return professorExternoEncontrado;
} catch (SQLException e) {
e.printStackTrace();
}
return professorExternoEncontrado;
}
public void salva(@Valid ProfessorExterno professorExterno,int codUsuario,Result result, Validator validator) {
try {
validator.onErrorRedirectTo(ProfessoresController.class).pfhome(codUsuario,result);
dao.adiciona(professorExterno,codUsuario);
result.include("mensagem", "Professor Externo salvo com sucesso!");
result.redirectTo(ProfessoresController.class).pfhome(codUsuario, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<ProfessorExterno> lista() {
try {
return dao.todos();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void delete(int codProfessorExterno,int codUsuario, Result result){
try {
dao.deleta(codProfessorExterno);
result.include("mensagem", "Professor Externo deletado com sucesso!");
result.redirectTo(ProfessoresController.class).pfhome(codUsuario, result);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 2,185 | 0.749657 | 0.749657 | 66 | 31.10606 | 26.048981 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.151515 | false | false |
10
|
20d8b27e349058d1b213a4c30aa7f0191ee5b3c1
| 32,289,564,178,987 |
a6d16e3b5b47c7500956009930034efdd811a6b3
|
/WORKSPACE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/CyberSecuritySecond/org/apache/jsp/home_jsp.java
|
29e36f1f9123738014d6ac7ce1182adc79d1fe05
|
[] |
no_license
|
chetan2282/IntrusionDetectionSystem
|
https://github.com/chetan2282/IntrusionDetectionSystem
|
1dc34fa406f4afe18f517fd873d7adb4e96926cf
|
4c9eb5cb92b588321414c8f5cb3bfaa0f47a5824
|
refs/heads/master
| 2020-04-25T18:03:25.151000 | 2019-02-27T19:07:18 | 2019-02-27T19:07:18 | 172,971,168 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.65
* Generated at: 2019-02-22 10:59:32 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class home_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!DOCTYPE html PUBxLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n");
out.write("<title>IDS</title>\r\n");
out.write("<meta name=\"keywords\" content=\"\" />\r\n");
out.write("<meta name=\"description\" content=\"\" />\r\n");
out.write("<!--\r\n");
out.write("Template 2063 Wide Mode\r\n");
out.write("http://www.tooplate.com/view/2063-wide-mode\r\n");
out.write("-->\r\n");
out.write("<link href=\"tooplate_style.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
out.write("\r\n");
out.write("<script type=\"text/JavaScript\" src=\"js/jquery-1.6.3.js\"></script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/ddsmoothmenu.css\" />\r\n");
out.write("\r\n");
out.write("<script type=\"text/javascript\" src=\"js/ddsmoothmenu.js\">\r\n");
out.write("\r\n");
out.write("/***********************************************\r\n");
out.write("* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)\r\n");
out.write("* This notice MUST stay intact for legal use\r\n");
out.write("* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code\r\n");
out.write("***********************************************/\r\n");
out.write("\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<script type=\"text/javascript\">\r\n");
out.write("\r\n");
out.write("ddsmoothmenu.init({\r\n");
out.write("\tmainmenuid: \"tooplate_menu\", //menu DIV id\r\n");
out.write("\torientation: 'h', //Horizontal or vertical menu: Set to \"h\" or \"v\"\r\n");
out.write("\tclassname: 'ddsmoothmenu', //class added to menu's outer DIV\r\n");
out.write("\t//customtheme: [\"#1c5a80\", \"#18374a\"],\r\n");
out.write("\tcontentsource: \"markup\" //\"markup\" or [\"container_id\", \"path_to_menu_file\"]\r\n");
out.write("})\r\n");
out.write("\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" href=\"css/slimbox2.css\" type=\"text/css\"\r\n");
out.write("\tmedia=\"screen\" />\r\n");
out.write("<script type=\"text/JavaScript\" src=\"js/slimbox2.js\"></script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" href=\"css/nivo-slider.css\" type=\"text/css\"\r\n");
out.write("\tmedia=\"screen\" />\r\n");
out.write("\r\n");
out.write("</head>\r\n");
if(request.getParameter("login")!=null)
{
out.println("<script>alert('login Successfully')</script>");
}
out.write("\r\n");
out.write("\r\n");
out.write("<body>\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_header\">\r\n");
out.write("\t\t\t<h1>\r\n");
out.write("\t\t\t\t<center>\r\n");
out.write("\t\t\t\t\t<a href=\"index.jsp\"><font color=\"white\">Intrusion\r\n");
out.write("\t\t\t\t\t\t\tDetection System</font></a>\r\n");
out.write("\t\t\t\t</center>\r\n");
out.write("\t\t\t</h1>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t\t<!-- END of header -->\r\n");
out.write("\t\t<div id=\"tooplate_main_wrapper\">\r\n");
out.write("\t\t\t<span class=\"tmw_frame tmw_framet\"></span><span\r\n");
out.write("\t\t\t\tclass=\"tmw_frame tmw_frameb\"></span>\r\n");
out.write("\t\t\t<div id=\"tooplate_menu\" class=\"ddsmoothmenu\">\r\n");
out.write("\t\t\t\t<ul>\r\n");
out.write("\t\t\t\t\t<li><a href=\"home.jsp\" class=\"selected\">Home</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"upload.jsp\">Upload</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"received.jsp\">Receive</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"index.jsp\">Logout</a></li>\r\n");
out.write("\r\n");
out.write("\t\t\t\t</ul>\r\n");
out.write("\t\t\t\t<br style=\"clear: left\" />\r\n");
out.write("\t\t\t</div>\r\n");
out.write("\t\t\t<!-- end of tooplate_menu -->\r\n");
out.write("\t\t\t<!-- END of slider -->\r\n");
out.write("\t\t\t<div id=\"tooplate_main\">\r\n");
out.write("\t\t\t\t\r\n");
out.write("\t\t\t\t<div class=\"content_wrapper content_mb_60\">\r\n");
out.write("\t\t\t\t\t<div class=\"col_2\">\r\n");
out.write("\t\t\t\t\t\t\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\r\n");
out.write("\t\t\t\t\t<div class=\"col_2 no_margin_right\">\r\n");
out.write("\t\t\t\t\t\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\t\t\t\t</div>\r\n");
out.write("\t\t\t\t<div class=\"clear h30\"></div>\r\n");
out.write("\t\t\t\t<div style=\"display: none;\" class=\"nav_up\" id=\"nav_up\"></div>\r\n");
out.write("\t\t\t</div>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t\t<!-- END of main wrapper -->\r\n");
out.write("\t</div>\r\n");
out.write("\t<!-- END of tooplate_wrapper -->\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_footer_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_footer\">\r\n");
out.write("\t\t\t<marquee>Intrusion Detection System</marquee>\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\t\t<!-- END of tooplate_footer -->\r\n");
out.write("\t</div>\r\n");
out.write("\t<!-- END of tooplate_footer_wrapper -->\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_copyright_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_copyright\">\r\n");
out.write("\t\t\tCopyright © 2048 Your Company Name | Design: <a\r\n");
out.write("\t\t\t\thref=\"http://www.tooplate.com\">Tooplate</a>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t</div>\r\n");
out.write("\r\n");
out.write("\t<script src=\"js/scroll-startstop.events.jquery.js\"\r\n");
out.write("\t\ttype=\"text/javascript\"></script>\r\n");
out.write("\t<script type=\"text/javascript\">\r\n");
out.write("\t$(function() {\r\n");
out.write("\t\tvar $elem = $('#content');\r\n");
out.write("\t\t\r\n");
out.write("\t\t$('#nav_up').fadeIn('slow');\r\n");
out.write("\t\t\r\n");
out.write("\t\t$(window).bind('scrollstart', function(){\r\n");
out.write("\t\t\t$('#nav_up,#nav_down').stop().animate({'opacity':'0.2'});\r\n");
out.write("\t\t});\r\n");
out.write("\t\t$(window).bind('scrollstop', function(){\r\n");
out.write("\t\t\t$('#nav_up,#nav_down').stop().animate({'opacity':'1'});\r\n");
out.write("\t\t});\r\n");
out.write("\t\t\r\n");
out.write("\t\t$('#nav_up').click(\r\n");
out.write("\t\t\tfunction (e) {\r\n");
out.write("\t\t\t\t$('html, body').animate({scrollTop: '0px'}, 800);\r\n");
out.write("\t\t\t}\r\n");
out.write("\t\t);\r\n");
out.write("\t});\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
|
UTF-8
|
Java
| 10,832 |
java
|
home_jsp.java
|
Java
|
[] | null |
[] |
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.65
* Generated at: 2019-02-22 10:59:32 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class home_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!DOCTYPE html PUBxLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n");
out.write("<title>IDS</title>\r\n");
out.write("<meta name=\"keywords\" content=\"\" />\r\n");
out.write("<meta name=\"description\" content=\"\" />\r\n");
out.write("<!--\r\n");
out.write("Template 2063 Wide Mode\r\n");
out.write("http://www.tooplate.com/view/2063-wide-mode\r\n");
out.write("-->\r\n");
out.write("<link href=\"tooplate_style.css\" rel=\"stylesheet\" type=\"text/css\" />\r\n");
out.write("\r\n");
out.write("<script type=\"text/JavaScript\" src=\"js/jquery-1.6.3.js\"></script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/ddsmoothmenu.css\" />\r\n");
out.write("\r\n");
out.write("<script type=\"text/javascript\" src=\"js/ddsmoothmenu.js\">\r\n");
out.write("\r\n");
out.write("/***********************************************\r\n");
out.write("* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)\r\n");
out.write("* This notice MUST stay intact for legal use\r\n");
out.write("* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code\r\n");
out.write("***********************************************/\r\n");
out.write("\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<script type=\"text/javascript\">\r\n");
out.write("\r\n");
out.write("ddsmoothmenu.init({\r\n");
out.write("\tmainmenuid: \"tooplate_menu\", //menu DIV id\r\n");
out.write("\torientation: 'h', //Horizontal or vertical menu: Set to \"h\" or \"v\"\r\n");
out.write("\tclassname: 'ddsmoothmenu', //class added to menu's outer DIV\r\n");
out.write("\t//customtheme: [\"#1c5a80\", \"#18374a\"],\r\n");
out.write("\tcontentsource: \"markup\" //\"markup\" or [\"container_id\", \"path_to_menu_file\"]\r\n");
out.write("})\r\n");
out.write("\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" href=\"css/slimbox2.css\" type=\"text/css\"\r\n");
out.write("\tmedia=\"screen\" />\r\n");
out.write("<script type=\"text/JavaScript\" src=\"js/slimbox2.js\"></script>\r\n");
out.write("\r\n");
out.write("<link rel=\"stylesheet\" href=\"css/nivo-slider.css\" type=\"text/css\"\r\n");
out.write("\tmedia=\"screen\" />\r\n");
out.write("\r\n");
out.write("</head>\r\n");
if(request.getParameter("login")!=null)
{
out.println("<script>alert('login Successfully')</script>");
}
out.write("\r\n");
out.write("\r\n");
out.write("<body>\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_header\">\r\n");
out.write("\t\t\t<h1>\r\n");
out.write("\t\t\t\t<center>\r\n");
out.write("\t\t\t\t\t<a href=\"index.jsp\"><font color=\"white\">Intrusion\r\n");
out.write("\t\t\t\t\t\t\tDetection System</font></a>\r\n");
out.write("\t\t\t\t</center>\r\n");
out.write("\t\t\t</h1>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t\t<!-- END of header -->\r\n");
out.write("\t\t<div id=\"tooplate_main_wrapper\">\r\n");
out.write("\t\t\t<span class=\"tmw_frame tmw_framet\"></span><span\r\n");
out.write("\t\t\t\tclass=\"tmw_frame tmw_frameb\"></span>\r\n");
out.write("\t\t\t<div id=\"tooplate_menu\" class=\"ddsmoothmenu\">\r\n");
out.write("\t\t\t\t<ul>\r\n");
out.write("\t\t\t\t\t<li><a href=\"home.jsp\" class=\"selected\">Home</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"upload.jsp\">Upload</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"received.jsp\">Receive</a></li>\r\n");
out.write("\t\t\t\t\t<li><a href=\"index.jsp\">Logout</a></li>\r\n");
out.write("\r\n");
out.write("\t\t\t\t</ul>\r\n");
out.write("\t\t\t\t<br style=\"clear: left\" />\r\n");
out.write("\t\t\t</div>\r\n");
out.write("\t\t\t<!-- end of tooplate_menu -->\r\n");
out.write("\t\t\t<!-- END of slider -->\r\n");
out.write("\t\t\t<div id=\"tooplate_main\">\r\n");
out.write("\t\t\t\t\r\n");
out.write("\t\t\t\t<div class=\"content_wrapper content_mb_60\">\r\n");
out.write("\t\t\t\t\t<div class=\"col_2\">\r\n");
out.write("\t\t\t\t\t\t\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\r\n");
out.write("\t\t\t\t\t<div class=\"col_2 no_margin_right\">\r\n");
out.write("\t\t\t\t\t\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\t\t\t\t</div>\r\n");
out.write("\t\t\t\t<div class=\"clear h30\"></div>\r\n");
out.write("\t\t\t\t<div style=\"display: none;\" class=\"nav_up\" id=\"nav_up\"></div>\r\n");
out.write("\t\t\t</div>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t\t<!-- END of main wrapper -->\r\n");
out.write("\t</div>\r\n");
out.write("\t<!-- END of tooplate_wrapper -->\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_footer_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_footer\">\r\n");
out.write("\t\t\t<marquee>Intrusion Detection System</marquee>\r\n");
out.write("\t\t\t\t\t</div>\r\n");
out.write("\t\t<!-- END of tooplate_footer -->\r\n");
out.write("\t</div>\r\n");
out.write("\t<!-- END of tooplate_footer_wrapper -->\r\n");
out.write("\r\n");
out.write("\t<div id=\"tooplate_copyright_wrapper\">\r\n");
out.write("\t\t<div id=\"tooplate_copyright\">\r\n");
out.write("\t\t\tCopyright © 2048 Your Company Name | Design: <a\r\n");
out.write("\t\t\t\thref=\"http://www.tooplate.com\">Tooplate</a>\r\n");
out.write("\t\t</div>\r\n");
out.write("\t</div>\r\n");
out.write("\r\n");
out.write("\t<script src=\"js/scroll-startstop.events.jquery.js\"\r\n");
out.write("\t\ttype=\"text/javascript\"></script>\r\n");
out.write("\t<script type=\"text/javascript\">\r\n");
out.write("\t$(function() {\r\n");
out.write("\t\tvar $elem = $('#content');\r\n");
out.write("\t\t\r\n");
out.write("\t\t$('#nav_up').fadeIn('slow');\r\n");
out.write("\t\t\r\n");
out.write("\t\t$(window).bind('scrollstart', function(){\r\n");
out.write("\t\t\t$('#nav_up,#nav_down').stop().animate({'opacity':'0.2'});\r\n");
out.write("\t\t});\r\n");
out.write("\t\t$(window).bind('scrollstop', function(){\r\n");
out.write("\t\t\t$('#nav_up,#nav_down').stop().animate({'opacity':'1'});\r\n");
out.write("\t\t});\r\n");
out.write("\t\t\r\n");
out.write("\t\t$('#nav_up').click(\r\n");
out.write("\t\t\tfunction (e) {\r\n");
out.write("\t\t\t\t$('html, body').animate({scrollTop: '0px'}, 800);\r\n");
out.write("\t\t\t}\r\n");
out.write("\t\t);\r\n");
out.write("\t});\r\n");
out.write("</script>\r\n");
out.write("\r\n");
out.write("</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| 10,832 | 0.572946 | 0.565928 | 241 | 43.937759 | 28.991489 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.86722 | false | false |
10
|
90d8b05e599776dc302de2e496c57890344ac95a
| 14,405,320,356,160 |
ca19c71291828c4cf3ee6cc33984771d35b6257f
|
/src/pl/com/bottega/photostock/sales/infrastructure/repositories/fake/FakeLightBoxRepository.java
|
d864fef0cb1c12e451d48c456e61be1c0ad330f4
|
[] |
no_license
|
ksrubka/photostock
|
https://github.com/ksrubka/photostock
|
4f199a471e46cf23818f1d63a599d5f23d722aeb
|
1a2758ab448a08783bf513234dedd52308cd39f8
|
refs/heads/master
| 2021-01-21T04:47:01.667000 | 2016-06-11T21:53:01 | 2016-06-11T21:53:01 | 55,002,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pl.com.bottega.photostock.sales.infrastructure.repositories.fake;
import pl.com.bottega.photostock.sales.infrastructure.repositories.interfaces.LightBoxRepository;
import pl.com.bottega.photostock.sales.model.LightBox;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Created by Beata Iłowiecka on 21.04.16.
*/
public class FakeLightBoxRepository implements LightBoxRepository {
private static Map<String, LightBox> fakeDatabase = new HashMap<>();
@Override
public LightBox load(String number) {
LightBox lightBox = fakeDatabase.get(number);
if (lightBox == null){
throw new RuntimeException("LightBox " + number + " does not exist");
}
return lightBox;
}
@Override
public void save(LightBox lightBox) {
if (lightBox.getNumber() == null){
lightBox.setNumber(UUID.randomUUID().toString()); // symulacja generowania ID przez bazę danych
}
fakeDatabase.put(lightBox.getNumber(), lightBox);
}
}
|
UTF-8
|
Java
| 1,046 |
java
|
FakeLightBoxRepository.java
|
Java
|
[
{
"context": "til.Map;\nimport java.util.UUID;\n\n/**\n * Created by Beata Iłowiecka on 21.04.16.\n */\npublic class FakeLightBoxReposit",
"end": 334,
"score": 0.9998799562454224,
"start": 319,
"tag": "NAME",
"value": "Beata Iłowiecka"
}
] | null |
[] |
package pl.com.bottega.photostock.sales.infrastructure.repositories.fake;
import pl.com.bottega.photostock.sales.infrastructure.repositories.interfaces.LightBoxRepository;
import pl.com.bottega.photostock.sales.model.LightBox;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Created by <NAME> on 21.04.16.
*/
public class FakeLightBoxRepository implements LightBoxRepository {
private static Map<String, LightBox> fakeDatabase = new HashMap<>();
@Override
public LightBox load(String number) {
LightBox lightBox = fakeDatabase.get(number);
if (lightBox == null){
throw new RuntimeException("LightBox " + number + " does not exist");
}
return lightBox;
}
@Override
public void save(LightBox lightBox) {
if (lightBox.getNumber() == null){
lightBox.setNumber(UUID.randomUUID().toString()); // symulacja generowania ID przez bazę danych
}
fakeDatabase.put(lightBox.getNumber(), lightBox);
}
}
| 1,036 | 0.69636 | 0.690613 | 33 | 30.636364 | 30.633532 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false |
10
|
cd5f28dd08e485ee99eb92eeabfce59d518a91d2
| 10,617,159,225,553 |
2a4f36ded35fbc1a00fdc47ce8c420188a7232fb
|
/1.00.1/_build/source/process-main/build/src/com/vvt/preference_manager/PrefAddressBook.java
|
68f406afce8668677b5e378e034cf9fd59d9728d
|
[] |
no_license
|
snehankekre/BB_Cyclops_2012
|
https://github.com/snehankekre/BB_Cyclops_2012
|
de45b9737e74b89b8154f8cd99f210d61bc14e78
|
31e86c30242d346bf6b06507168e639f2af00603
|
refs/heads/master
| 2020-02-29T12:22:35.830000 | 2017-04-22T18:05:41 | 2017-04-22T18:05:41 | 89,088,933 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.vvt.preference_manager;
import java.io.Serializable;
import com.vvt.base.FxAddressbookMode;
import com.vvt.base.security.Constant;
import com.vvt.base.security.FxSecurity;
public class PrefAddressBook extends Preference implements Serializable {
private static final long serialVersionUID = 1L;
private static final String ADDRESSBOOK_PERSIST_FILE_NAME = FxSecurity.getConstant(Constant.ADDRESSBOOK_PERSIST_FILE_NAME);
private FxAddressbookMode mMode;
public PrefAddressBook() {
// TODO: Comfirm and change later
mMode = FxAddressbookMode.MONITOR;
}
public FxAddressbookMode getMode() {
return mMode;
}
public void setMode(FxAddressbookMode mode) {
mMode = mode;
}
@Override
protected PreferenceType getType() {
return PreferenceType.ADDRESSBOOK;
}
@Override
protected String getPersistFileName() {
return ADDRESSBOOK_PERSIST_FILE_NAME;
}
}
|
UTF-8
|
Java
| 895 |
java
|
PrefAddressBook.java
|
Java
|
[] | null |
[] |
package com.vvt.preference_manager;
import java.io.Serializable;
import com.vvt.base.FxAddressbookMode;
import com.vvt.base.security.Constant;
import com.vvt.base.security.FxSecurity;
public class PrefAddressBook extends Preference implements Serializable {
private static final long serialVersionUID = 1L;
private static final String ADDRESSBOOK_PERSIST_FILE_NAME = FxSecurity.getConstant(Constant.ADDRESSBOOK_PERSIST_FILE_NAME);
private FxAddressbookMode mMode;
public PrefAddressBook() {
// TODO: Comfirm and change later
mMode = FxAddressbookMode.MONITOR;
}
public FxAddressbookMode getMode() {
return mMode;
}
public void setMode(FxAddressbookMode mode) {
mMode = mode;
}
@Override
protected PreferenceType getType() {
return PreferenceType.ADDRESSBOOK;
}
@Override
protected String getPersistFileName() {
return ADDRESSBOOK_PERSIST_FILE_NAME;
}
}
| 895 | 0.778771 | 0.777654 | 39 | 21.97436 | 25.421057 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.128205 | false | false |
10
|
9450f8aba98e8158e4982c998fee0f94df6d9564
| 1,640,677,566,188 |
ec81cafd29ff51ab8cfaf7203373a37ce4c60228
|
/MiniViber-Server/src/com/comtrade/so/poruka/VratiPrivatnePoruke.java
|
2f2eec4e94ef94235896cc0fd58280edd20f4a72
|
[] |
no_license
|
emirJava/Mini-Viber
|
https://github.com/emirJava/Mini-Viber
|
d618c35fc8d344229184b2c5b1612739142aaf25
|
e8b87c4dcb8cce09acc9ee7742f0708a8d54f00c
|
refs/heads/master
| 2018-11-07T09:19:05.667000 | 2018-08-29T08:46:50 | 2018-08-29T08:46:50 | 146,206,089 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.comtrade.so.poruka;
import java.util.Map;
import com.comtrade.broker.Broker;
import com.comtrade.domen.GrupnaPoruka;
import com.comtrade.domen.PrivatnaPoruka;
import com.comtrade.so.OpstaSo;
@SuppressWarnings("unchecked")
public class VratiPrivatnePoruke extends OpstaSo {
@Override
public void izvrsikonkrektnuOperaciju(Object obj) {
Map<String, Object> mojiPodaci=(Map<String, Object>) obj;
Broker.vratiInstancu().uzmiPoruke(new PrivatnaPoruka(),new GrupnaPoruka(),mojiPodaci);
}
}
|
UTF-8
|
Java
| 531 |
java
|
VratiPrivatnePoruke.java
|
Java
|
[] | null |
[] |
package com.comtrade.so.poruka;
import java.util.Map;
import com.comtrade.broker.Broker;
import com.comtrade.domen.GrupnaPoruka;
import com.comtrade.domen.PrivatnaPoruka;
import com.comtrade.so.OpstaSo;
@SuppressWarnings("unchecked")
public class VratiPrivatnePoruke extends OpstaSo {
@Override
public void izvrsikonkrektnuOperaciju(Object obj) {
Map<String, Object> mojiPodaci=(Map<String, Object>) obj;
Broker.vratiInstancu().uzmiPoruke(new PrivatnaPoruka(),new GrupnaPoruka(),mojiPodaci);
}
}
| 531 | 0.758945 | 0.758945 | 20 | 24.549999 | 24.601778 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.05 | false | false |
10
|
4b7a7818c1016054aac6e4ddde5a1f8f204f986a
| 12,687,333,450,364 |
01988a3293813d66817044a5db33441980dcf91a
|
/src/main/java/com/ibm/watson/developer_cloud/language_translation/v2/model/package-info.java
|
a415ca00c51a67bec0b86469ed53808d2a905872
|
[
"metamail",
"LicenseRef-scancode-other-permissive",
"Beerware",
"LicenseRef-scancode-zeusbench",
"Apache-1.1",
"LicenseRef-scancode-rsa-1990",
"LicenseRef-scancode-pcre",
"Spencer-94",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"NTP",
"LicenseRef-scancode-rsa-md4",
"MIT",
"HPND-sell-variant",
"RSA-MD"
] |
permissive
|
debojyotiIBM/java-sdk
|
https://github.com/debojyotiIBM/java-sdk
|
def56c9f76b21ca3254ab3c22afb1d83836cf3eb
|
a60589a1489d6afa4958ea22bfb4aa4cc48e9825
|
refs/heads/master
| 2020-12-02T15:05:46.054000 | 2015-11-03T16:37:00 | 2015-11-03T16:37:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Language Translation POJOs
*/
package com.ibm.watson.developer_cloud.language_translation.v2.model;
|
UTF-8
|
Java
| 109 |
java
|
package-info.java
|
Java
|
[] | null |
[] |
/**
* Language Translation POJOs
*/
package com.ibm.watson.developer_cloud.language_translation.v2.model;
| 109 | 0.761468 | 0.752294 | 4 | 26 | 27 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
10
|
0a3d2b0dca33303f45064cd26dcff3f1eb074dd6
| 12,687,333,449,135 |
1bc117eb38301fed18a96f21ae4d4438869bdaf8
|
/src/main/java/bgs/geophys/library/Data/webService/DataInterval.java
|
52cd4e822850fdb30cced4ed4fb538b770feaa7b
|
[] |
no_license
|
INTERMAGNET/lib_bgs
|
https://github.com/INTERMAGNET/lib_bgs
|
5eb7c5cfcd19536939ecc5a83bfa6fe92ad43126
|
00d6c8d7af15b27ff9717336f7f5246814603b7d
|
refs/heads/master
| 2021-09-16T03:21:01.960000 | 2018-06-15T13:53:14 | 2018-06-15T13:53:14 | 108,842,012 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bgs.geophys.library.Data.webService;
/**
* Represents a data interval or cadence.
* @author sani
*/
public enum DataInterval {
/**
* DataInterval enum type literals.
*/
HOUR("1-HOUR", ".hor", 3600000), MINUTE("1-MINUTE", "", 60000), SECOND("1-SECOND", "", 1000);
private final String intervalString;
private final String fileExtension;
private final long period;
private DataInterval(String intervalString, String fileExtension, long period){
this.intervalString = intervalString;
this.fileExtension = fileExtension;
this.period = period;
}
/**
* Returns the a string representation fot the data interval.
* @return Data interval string.
*/
public String intervalString() {
return intervalString;
}
/**
* Returns the file extension for data files of the data interval type.
* @return The file extension.
*/
public String fileExtension() {
return fileExtension;
}
/**
* Returns the period of the for the data type in milli seconds.
* @return The data interval period in milli seconds.
*/
public long period() {
return period;
}
}
|
UTF-8
|
Java
| 1,324 |
java
|
DataInterval.java
|
Java
|
[
{
"context": " Represents a data interval or cadence.\n * @author sani\n */\npublic enum DataInterval {\n /**\n * Dat",
"end": 208,
"score": 0.9866487979888916,
"start": 204,
"tag": "USERNAME",
"value": "sani"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bgs.geophys.library.Data.webService;
/**
* Represents a data interval or cadence.
* @author sani
*/
public enum DataInterval {
/**
* DataInterval enum type literals.
*/
HOUR("1-HOUR", ".hor", 3600000), MINUTE("1-MINUTE", "", 60000), SECOND("1-SECOND", "", 1000);
private final String intervalString;
private final String fileExtension;
private final long period;
private DataInterval(String intervalString, String fileExtension, long period){
this.intervalString = intervalString;
this.fileExtension = fileExtension;
this.period = period;
}
/**
* Returns the a string representation fot the data interval.
* @return Data interval string.
*/
public String intervalString() {
return intervalString;
}
/**
* Returns the file extension for data files of the data interval type.
* @return The file extension.
*/
public String fileExtension() {
return fileExtension;
}
/**
* Returns the period of the for the data type in milli seconds.
* @return The data interval period in milli seconds.
*/
public long period() {
return period;
}
}
| 1,324 | 0.636707 | 0.622356 | 53 | 23.981133 | 24.185986 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433962 | false | false |
10
|
b11a0ed55b35fff365874aeec0f99576f76b2827
| 29,463,475,700,849 |
ac1ba2a334c00d4704050f06a9382e7571c328d6
|
/src/main/java/com/example/producer/controller/TestController.java
|
f91cba3593e6397b96186abd3c2514b635ca952f
|
[] |
no_license
|
Soulmate303/Kafka
|
https://github.com/Soulmate303/Kafka
|
248946adc55515e0e3d99c2af73e6a29fb91715a
|
4b515a13e0f7fc1510fe1abfbf283e4b2525f176
|
refs/heads/master
| 2022-11-25T12:48:17.071000 | 2020-07-28T15:14:31 | 2020-07-28T15:14:31 | 283,248,903 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.producer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
@RestController
public class TestController {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
@RequestMapping(value = "/kafka/normal/{message}", method = RequestMethod.POST)
public void sendMessage1(@PathVariable("message") String normalMessage) {
kafkaTemplate.send("student-score", normalMessage);
System.out.println(normalMessage);
}
}
|
UTF-8
|
Java
| 602 |
java
|
TestController.java
|
Java
|
[] | null |
[] |
package com.example.producer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
@RestController
public class TestController {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
@RequestMapping(value = "/kafka/normal/{message}", method = RequestMethod.POST)
public void sendMessage1(@PathVariable("message") String normalMessage) {
kafkaTemplate.send("student-score", normalMessage);
System.out.println(normalMessage);
}
}
| 602 | 0.765781 | 0.76412 | 19 | 30.68421 | 28.131371 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false |
10
|
4dc0074803d115a778a27c8e65b4f73920a5c71c
| 24,824,911,019,473 |
ba4ae3f9eba022a152670c96a61164bb948ddeb5
|
/lectures.tasks/src/main/java/lecture8/lambda.java
|
43b3190c7396796c961b37eb05f3a5a5f4af3ea7
|
[] |
no_license
|
bibliophagist/JavaSchoolHW
|
https://github.com/bibliophagist/JavaSchoolHW
|
529090f4b98905efe3f2f5f6985c4e459b17bdc3
|
ec0486fba29bf1463a390c6d32e6e69d603a53d1
|
refs/heads/master
| 2020-03-22T09:56:31.495000 | 2018-08-26T17:05:40 | 2018-08-26T17:05:40 | 139,865,968 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lecture8;
import java.io.File;
public class lambda {
public static void main(String[] args) {
File file = new File("C:\\");
File[] files = file.listFiles(fileL -> fileL.isDirectory());
if (files != null) {
for (File filePrint : files) {
System.out.println(filePrint.getName());
}
} else {
System.out.println("There is not subdirectories!");
}
}
}
|
UTF-8
|
Java
| 458 |
java
|
lambda.java
|
Java
|
[] | null |
[] |
package lecture8;
import java.io.File;
public class lambda {
public static void main(String[] args) {
File file = new File("C:\\");
File[] files = file.listFiles(fileL -> fileL.isDirectory());
if (files != null) {
for (File filePrint : files) {
System.out.println(filePrint.getName());
}
} else {
System.out.println("There is not subdirectories!");
}
}
}
| 458 | 0.534935 | 0.532751 | 18 | 24.444445 | 21.715899 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
1831f35c197bc2ebd849e100cbcd69706c7966fe
| 27,023,934,288,405 |
284bf504a773beff651572cb86127a8054e7f213
|
/Step06_CafeExample/src/main/java/com/test/step06/users/dao/UsersDaoImpl.java
|
57f30891eb9f46ea17fbd7d1ac31289c13efebe1
|
[] |
no_license
|
hyunhee7/spring
|
https://github.com/hyunhee7/spring
|
bcb44f4167abc70c7df4a4fe4fa2d6c705cf5e31
|
dbff7d97ba145b443a7f091d61400223f3b8fc8f
|
refs/heads/master
| 2021-05-25T10:31:37.594000 | 2017-08-03T09:28:51 | 2017-08-03T09:28:51 | 98,298,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.test.step06.users.dao;
import java.util.List;
import com.test.step06.users.dto.UsersDto;
public class UsersDaoImpl implements UsersDao{
@Override
public void insert(UsersDto dto) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(UsersDto dto) {
// TODO Auto-generated method stub
return false;
}
@Override
public UsersDto getData(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(UsersDto dto) {
// TODO Auto-generated method stub
}
@Override
public void delete(String id) {
// TODO Auto-generated method stub
}
@Override
public List<UsersDto> getList() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canUseId(String id) {
// TODO Auto-generated method stub
return false;
}
}
|
UTF-8
|
Java
| 845 |
java
|
UsersDaoImpl.java
|
Java
|
[] | null |
[] |
package com.test.step06.users.dao;
import java.util.List;
import com.test.step06.users.dto.UsersDto;
public class UsersDaoImpl implements UsersDao{
@Override
public void insert(UsersDto dto) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(UsersDto dto) {
// TODO Auto-generated method stub
return false;
}
@Override
public UsersDto getData(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(UsersDto dto) {
// TODO Auto-generated method stub
}
@Override
public void delete(String id) {
// TODO Auto-generated method stub
}
@Override
public List<UsersDto> getList() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean canUseId(String id) {
// TODO Auto-generated method stub
return false;
}
}
| 845 | 0.711243 | 0.706509 | 51 | 15.568627 | 15.781915 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.098039 | false | false |
10
|
557318292fc935dd5924baa12b8baa0cde014838
| 11,227,044,514,339 |
6b3b9ef2543ebee98adc320585a5eca712620f33
|
/sandbox/src/reflectionStuff/Reflec1.java
|
605d646429368e163fe8a74eeb9ae1de9ae5eda1
|
[] |
no_license
|
NotThe1/sandbox
|
https://github.com/NotThe1/sandbox
|
e3ec69995bacdb35b134ae98ab2c282ab64e3f04
|
8590deff26eb41de5167566c762a400075320ae2
|
refs/heads/master
| 2020-04-16T10:53:14.812000 | 2020-03-06T20:47:23 | 2020-03-06T20:47:23 | 37,475,680 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package reflectionStuff;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.prefs.Preferences;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Reflec1 {
private JFrame frmReflec;
private JButton btnNewButton;
private JButton btnNewButton_1;
private JTextField txtAbcdef;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Reflec1 window = new Reflec1();
window.frmReflec.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}// main
private void appClose() {
Preferences myPrefs = Preferences.userNodeForPackage(Reflec1.class).node(this.getClass().getSimpleName());
Dimension dim = frmReflec.getSize();
myPrefs.putInt("Height", dim.height);
myPrefs.putInt("Width", dim.width);
Point point = frmReflec.getLocation();
myPrefs.putInt("LocX", point.x);
myPrefs.putInt("LocY", point.y);
myPrefs = null;
}
// @SuppressWarnings("unchecked")
private void appInit() {
Preferences myPrefs = Preferences.userNodeForPackage(Reflec1.class).node(this.getClass().getSimpleName());
frmReflec.setSize(435,512);
frmReflec.setLocation(myPrefs.getInt("LocX", 100), myPrefs.getInt("LocY", 100));
myPrefs = null;
}//appInit
// watchButtons = new WatchButtons();
// window.addObserver(watchButtons);
/**
* Create the application.
*/
public Reflec1() {
initialize();
appInit();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmReflec = new JFrame();
// frmReflec.setIconImage(Toolkit.getDefaultToolkit().getImage(Reflec1.class.getResource("/reflectionStuff/images/Regex.jpg")));
frmReflec.setTitle("Reflec1");
frmReflec.setBounds(100, 100, 450, 300);
frmReflec.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frmReflec.getContentPane().setLayout(gridBagLayout);
btnNewButton = new JButton("0123456789 ABCDEF");
btnNewButton.setPreferredSize(new Dimension(400, 60));
Font fontDigital7 = null;
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/digital display tfb.ttf");
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/DS-DIGI.ttf");
URL fontUrl = Reflec1.class.getResource("/reflectionStuff/Digit.ttf");
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/ufonts.com_digital-7.ttf");
try {
fontDigital7 = Font.createFont(Font.TRUETYPE_FONT,fontUrl.openStream());
fontDigital7 = fontDigital7.deriveFont(Font.BOLD,45);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(fontDigital7);
// g.setFont(font);
} catch (FontFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//try
btnNewButton.setFont(fontDigital7);
// btnNewButton.setFont(new Font("Courier New", Font.PLAIN, 16));
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 1;
frmReflec.getContentPane().add(btnNewButton, gbc_btnNewButton);
btnNewButton_1 = new JButton("New button");
Icon xIcon = new ImageIcon(Reflec1.class.getResource("/reflectionStuff/images/Button-Turn-Off-icon.png"));
btnNewButton_1.setIcon(xIcon);
GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton_1.gridx = 0;
gbc_btnNewButton_1.gridy = 3;
frmReflec.getContentPane().add(btnNewButton_1, gbc_btnNewButton_1);
txtAbcdef = new JTextField();
txtAbcdef.setForeground(new Color(220, 20, 60));
txtAbcdef.setHorizontalAlignment(SwingConstants.CENTER);
txtAbcdef.setPreferredSize(new Dimension(400, 60));
txtAbcdef.setText("0123456789 ABCDEF");
txtAbcdef.setFont(fontDigital7);
GridBagConstraints gbc_txtAbcdef = new GridBagConstraints();
gbc_txtAbcdef.fill = GridBagConstraints.HORIZONTAL;
gbc_txtAbcdef.gridx = 0;
gbc_txtAbcdef.gridy = 5;
frmReflec.getContentPane().add(txtAbcdef, gbc_txtAbcdef);
txtAbcdef.setColumns(10);
JMenuBar menuBar = new JMenuBar();
frmReflec.setJMenuBar(menuBar);
frmReflec.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
appClose();
}
});
}
}//class
|
UTF-8
|
Java
| 5,355 |
java
|
Reflec1.java
|
Java
|
[] | null |
[] |
package reflectionStuff;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import java.util.prefs.Preferences;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Reflec1 {
private JFrame frmReflec;
private JButton btnNewButton;
private JButton btnNewButton_1;
private JTextField txtAbcdef;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Reflec1 window = new Reflec1();
window.frmReflec.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}// main
private void appClose() {
Preferences myPrefs = Preferences.userNodeForPackage(Reflec1.class).node(this.getClass().getSimpleName());
Dimension dim = frmReflec.getSize();
myPrefs.putInt("Height", dim.height);
myPrefs.putInt("Width", dim.width);
Point point = frmReflec.getLocation();
myPrefs.putInt("LocX", point.x);
myPrefs.putInt("LocY", point.y);
myPrefs = null;
}
// @SuppressWarnings("unchecked")
private void appInit() {
Preferences myPrefs = Preferences.userNodeForPackage(Reflec1.class).node(this.getClass().getSimpleName());
frmReflec.setSize(435,512);
frmReflec.setLocation(myPrefs.getInt("LocX", 100), myPrefs.getInt("LocY", 100));
myPrefs = null;
}//appInit
// watchButtons = new WatchButtons();
// window.addObserver(watchButtons);
/**
* Create the application.
*/
public Reflec1() {
initialize();
appInit();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmReflec = new JFrame();
// frmReflec.setIconImage(Toolkit.getDefaultToolkit().getImage(Reflec1.class.getResource("/reflectionStuff/images/Regex.jpg")));
frmReflec.setTitle("Reflec1");
frmReflec.setBounds(100, 100, 450, 300);
frmReflec.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frmReflec.getContentPane().setLayout(gridBagLayout);
btnNewButton = new JButton("0123456789 ABCDEF");
btnNewButton.setPreferredSize(new Dimension(400, 60));
Font fontDigital7 = null;
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/digital display tfb.ttf");
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/DS-DIGI.ttf");
URL fontUrl = Reflec1.class.getResource("/reflectionStuff/Digit.ttf");
// URL fontUrl = Reflec1.class.getResource("/reflectionStuff/ufonts.com_digital-7.ttf");
try {
fontDigital7 = Font.createFont(Font.TRUETYPE_FONT,fontUrl.openStream());
fontDigital7 = fontDigital7.deriveFont(Font.BOLD,45);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(fontDigital7);
// g.setFont(font);
} catch (FontFormatException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//try
btnNewButton.setFont(fontDigital7);
// btnNewButton.setFont(new Font("Courier New", Font.PLAIN, 16));
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 1;
frmReflec.getContentPane().add(btnNewButton, gbc_btnNewButton);
btnNewButton_1 = new JButton("New button");
Icon xIcon = new ImageIcon(Reflec1.class.getResource("/reflectionStuff/images/Button-Turn-Off-icon.png"));
btnNewButton_1.setIcon(xIcon);
GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton_1.gridx = 0;
gbc_btnNewButton_1.gridy = 3;
frmReflec.getContentPane().add(btnNewButton_1, gbc_btnNewButton_1);
txtAbcdef = new JTextField();
txtAbcdef.setForeground(new Color(220, 20, 60));
txtAbcdef.setHorizontalAlignment(SwingConstants.CENTER);
txtAbcdef.setPreferredSize(new Dimension(400, 60));
txtAbcdef.setText("0123456789 ABCDEF");
txtAbcdef.setFont(fontDigital7);
GridBagConstraints gbc_txtAbcdef = new GridBagConstraints();
gbc_txtAbcdef.fill = GridBagConstraints.HORIZONTAL;
gbc_txtAbcdef.gridx = 0;
gbc_txtAbcdef.gridy = 5;
frmReflec.getContentPane().add(txtAbcdef, gbc_txtAbcdef);
txtAbcdef.setColumns(10);
JMenuBar menuBar = new JMenuBar();
frmReflec.setJMenuBar(menuBar);
frmReflec.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
appClose();
}
});
}
}//class
| 5,355 | 0.713726 | 0.688515 | 158 | 31.892405 | 25.37306 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.462025 | false | false |
10
|
4c8ee2f12f5689dedb25fbd1d87e53611d4bc32b
| 18,056,042,570,631 |
e3b3a07496d67ad7e06cb61a84ab6bf54f114f20
|
/satc-web/.svn/pristine/af/af9b3f9c922ab0cfdc70fbd35ade850806dfaf6b.svn-base
|
b41c186ae2f58abe031339e32ec1694ed129bff4
|
[] |
no_license
|
jelizvt/sisatc
|
https://github.com/jelizvt/sisatc
|
19ddea0112eb4a33bfa08db6ac56e4adfbc87df6
|
ca0f8eb74feb3211c7b9cb586bbfa3952a966122
|
refs/heads/master
| 2022-12-07T21:20:34.181000 | 2020-08-19T15:30:32 | 2020-08-19T15:30:32 | 288,759,982 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sat.sisat.common.managed;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import com.sat.sisat.common.util.BaseManaged;
import com.sat.sisat.common.util.SATParameterFactory;
@ManagedBean
@ViewScoped
public class PrincipalManaged extends BaseManaged {
private static final long serialVersionUID = -50738742644178197L;
private String nombreBD;
public PrincipalManaged() {
}
@PostConstruct
public void inicializar(){
nombreBD = SATParameterFactory.getDbNombre();
}
public void tributosAction(ActionEvent ev){
getSessionManaged().setModuloFisca(false);
}
public void fiscalizacionAction(ActionEvent ev){
getSessionManaged().setModuloFisca(true);
}
public String getNombreBD() {
return nombreBD;
}
public void setNombreBD(String nombreBD) {
this.nombreBD = nombreBD;
}
}
|
UTF-8
|
Java
| 919 |
af9b3f9c922ab0cfdc70fbd35ade850806dfaf6b.svn-base
|
Java
|
[] | null |
[] |
package com.sat.sisat.common.managed;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import com.sat.sisat.common.util.BaseManaged;
import com.sat.sisat.common.util.SATParameterFactory;
@ManagedBean
@ViewScoped
public class PrincipalManaged extends BaseManaged {
private static final long serialVersionUID = -50738742644178197L;
private String nombreBD;
public PrincipalManaged() {
}
@PostConstruct
public void inicializar(){
nombreBD = SATParameterFactory.getDbNombre();
}
public void tributosAction(ActionEvent ev){
getSessionManaged().setModuloFisca(false);
}
public void fiscalizacionAction(ActionEvent ev){
getSessionManaged().setModuloFisca(true);
}
public String getNombreBD() {
return nombreBD;
}
public void setNombreBD(String nombreBD) {
this.nombreBD = nombreBD;
}
}
| 919 | 0.784548 | 0.76605 | 42 | 20.880953 | 20.101175 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
10
|
|
467ad7b98d55df61d9fe3ad13f32ec2f7645f348
| 23,983,097,390,945 |
ca57c3651db75069fcbbb7c5190e6a328331660e
|
/src/com/siwuxie095/forme/algorithm/chapter8th/question19th/answer1st/Main.java
|
fe28980525e9f84d80db9bfdeb8b21ac50bdb995
|
[] |
no_license
|
gouyanzhan/HelloWorld
|
https://github.com/gouyanzhan/HelloWorld
|
f915ec8eabf8878b0c01fb8ec29b869e6fd68c5f
|
8cd9dc117d301d10207690052f2f27de2d9b9e2c
|
refs/heads/master
| 2022-03-25T07:31:52.842000 | 2022-03-11T07:08:30 | 2022-03-11T07:08:30 | 164,224,001 | 1 | 1 | null | false | 2019-01-07T14:18:44 | 2019-01-05T14:52:23 | 2019-01-06T13:08:12 | 2019-01-07T14:18:44 | 22 | 1 | 1 | 0 |
Java
| false | null |
package com.siwuxie095.forme.algorithm.chapter8th.question19th.answer1st;
/**
* 数组中子数组的最大累乘积
*
* 题目:
* 给定一个 double 类型的数组 arr,其中的元素可正、可负、可 0,返回子数组累乘的最大乘积。例如,
* arr = [-2.5, 4, 0, 3, 0.5, 8, -1],子数组 [3, 0.5, 8] 累乘可以获得最大的乘积 12,所
* 以返回 12。
*
* 解答:
* 本题可以做到时间复杂度为 O(N)、额外空间复杂度为 O(1)。所有的子数组都会以某一个位置结束,所以,
* 如果求出以每一个位置结尾的子数组最大的累乘积,在这么多最大累乘积中最大的那个就是最终的结果。也
* 就是说,结果 = Max{以 arr[0] 结尾的所有子数组的最大累乘积,以 arr[1] 结尾的所有子数组的最大
* 累乘积 ... 以 arr[arr.length-1] 结尾的所有子数组的最大累乘积}。
* 如何快速求出所有以 i 位置结尾(arr[i])的子数组的最大乘积呢?假设以 arr[i-1] 结尾的最小累乘
* 积为 min,以 arr[i-1] 结尾的最大累乘积为 max,那么,以 arr[i] 结尾的最大累乘积只有以下三种
* 可能:
* (1)可能是 max*arr[i]。max 既然表示以 arr[i-1] 结尾的最大累乘积,那么当然有可能以 arr[i]
* 结尾的最大累乘积是 max*arr[i]。例如,[3, 4, 5] 在算到 5 的时候。
* (2)可能是 min*arr[i]。min 既然表示以 arr[i-1] 结尾的最小累乘积,当然有可能 min 是负数,
* 而如果 arr[i] 也是负数,两个负数相乘的结果也可能很大。例如,[-2, 3, -4] 在算到 -4 的时候。
* (3)可能仅是 arr[i] 的值。以 arr[i] 结尾的最大累乘积并不一定非要包含 arr[i] 之前的数。例如,
* [0.1, 0,1, 100] 在算到 100 的时候。
* 这三种可能的值中最大的那个就作为以 i 位置结尾的最大累乘积,最小的作为最小累乘积,然后继续计算以
* i+1 位置结尾的时候,如此重复,直到计算结束。
*
* @author Jiajing Li
* @date 2019-06-09 21:16:48
*/
public class Main {
public static void main(String[] args) {
double[] arr = {-2.5, 4, 0, 3, 0.5, 8, -1};
System.out.println(Product.maxProduct(arr));
}
}
|
UTF-8
|
Java
| 2,265 |
java
|
Main.java
|
Java
|
[
{
"context": ",然后继续计算以\n * i+1 位置结尾的时候,如此重复,直到计算结束。\n *\n * @author Jiajing Li\n * @date 2019-06-09 21:16:48\n */\npublic class Mai",
"end": 1035,
"score": 0.9996889233589172,
"start": 1025,
"tag": "NAME",
"value": "Jiajing Li"
}
] | null |
[] |
package com.siwuxie095.forme.algorithm.chapter8th.question19th.answer1st;
/**
* 数组中子数组的最大累乘积
*
* 题目:
* 给定一个 double 类型的数组 arr,其中的元素可正、可负、可 0,返回子数组累乘的最大乘积。例如,
* arr = [-2.5, 4, 0, 3, 0.5, 8, -1],子数组 [3, 0.5, 8] 累乘可以获得最大的乘积 12,所
* 以返回 12。
*
* 解答:
* 本题可以做到时间复杂度为 O(N)、额外空间复杂度为 O(1)。所有的子数组都会以某一个位置结束,所以,
* 如果求出以每一个位置结尾的子数组最大的累乘积,在这么多最大累乘积中最大的那个就是最终的结果。也
* 就是说,结果 = Max{以 arr[0] 结尾的所有子数组的最大累乘积,以 arr[1] 结尾的所有子数组的最大
* 累乘积 ... 以 arr[arr.length-1] 结尾的所有子数组的最大累乘积}。
* 如何快速求出所有以 i 位置结尾(arr[i])的子数组的最大乘积呢?假设以 arr[i-1] 结尾的最小累乘
* 积为 min,以 arr[i-1] 结尾的最大累乘积为 max,那么,以 arr[i] 结尾的最大累乘积只有以下三种
* 可能:
* (1)可能是 max*arr[i]。max 既然表示以 arr[i-1] 结尾的最大累乘积,那么当然有可能以 arr[i]
* 结尾的最大累乘积是 max*arr[i]。例如,[3, 4, 5] 在算到 5 的时候。
* (2)可能是 min*arr[i]。min 既然表示以 arr[i-1] 结尾的最小累乘积,当然有可能 min 是负数,
* 而如果 arr[i] 也是负数,两个负数相乘的结果也可能很大。例如,[-2, 3, -4] 在算到 -4 的时候。
* (3)可能仅是 arr[i] 的值。以 arr[i] 结尾的最大累乘积并不一定非要包含 arr[i] 之前的数。例如,
* [0.1, 0,1, 100] 在算到 100 的时候。
* 这三种可能的值中最大的那个就作为以 i 位置结尾的最大累乘积,最小的作为最小累乘积,然后继续计算以
* i+1 位置结尾的时候,如此重复,直到计算结束。
*
* @author <NAME>
* @date 2019-06-09 21:16:48
*/
public class Main {
public static void main(String[] args) {
double[] arr = {-2.5, 4, 0, 3, 0.5, 8, -1};
System.out.println(Product.maxProduct(arr));
}
}
| 2,261 | 0.654924 | 0.592474 | 38 | 31.868422 | 25.381479 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false |
10
|
1f76a94b5d44c5ae8ccd614288c8bb561d08c2ec
| 7,876,970,038,454 |
ef2da4320417113b72d294301c810bfc72637b79
|
/src/main/java/wang/miansen/roothub/modules/tab/service/impl/TabServiceImpl.java
|
1a871a7a93fcf894ca7b75836bb4caacb8d80dd9
|
[
"MIT"
] |
permissive
|
qmx-work/qmx-forum
|
https://github.com/qmx-work/qmx-forum
|
6ff2bbf79d26f8cc0e700fa52c2f5834768d2b22
|
e13aefd411f9cfdef031026136ccc75580241649
|
refs/heads/master
| 2020-12-09T21:08:23.511000 | 2020-08-06T07:53:28 | 2020-08-06T07:53:28 | 233,415,957 | 5 | 0 |
MIT
| false | 2020-10-13T18:48:34 | 2020-01-12T15:43:12 | 2020-08-06T07:53:32 | 2020-10-13T18:48:32 | 64,103 | 3 | 0 | 8 |
Java
| false | false |
package wang.miansen.roothub.modules.tab.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import wang.miansen.roothub.modules.tab.dao.TabDao;
import wang.miansen.roothub.modules.tab.model.Tab;
import wang.miansen.roothub.modules.topic.service.TabService;
@Service
public class TabServiceImpl implements TabService{
@Autowired
private TabDao tabDao;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 查询所有板块
*/
@Override
public List<Tab> selectAll() {
return tabDao.selectAll();
}
}
|
UTF-8
|
Java
| 693 |
java
|
TabServiceImpl.java
|
Java
|
[] | null |
[] |
package wang.miansen.roothub.modules.tab.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import wang.miansen.roothub.modules.tab.dao.TabDao;
import wang.miansen.roothub.modules.tab.model.Tab;
import wang.miansen.roothub.modules.topic.service.TabService;
@Service
public class TabServiceImpl implements TabService{
@Autowired
private TabDao tabDao;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 查询所有板块
*/
@Override
public List<Tab> selectAll() {
return tabDao.selectAll();
}
}
| 693 | 0.800294 | 0.800294 | 29 | 22.482759 | 22.902523 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.827586 | false | false |
10
|
616dba838c0b0646645abc66caa92b5e7cedb48f
| 12,300,786,381,552 |
6bb3ac17eb3f069a75e6a6232f158a14c9f85422
|
/src/main/java/com/graffitab/server/service/user/ExternalProviderService.java
|
07d8aa1a7b43fcf8dbc2b2c4c39a552d8e3727b7
|
[
"Apache-2.0"
] |
permissive
|
GraffiTab/GraffiTab-Backend
|
https://github.com/GraffiTab/GraffiTab-Backend
|
ebfbef4bab2e76fe5524ad4cecfdb0b7d79fdca9
|
5f7eed27e93eb1dda098785be1f30d46342a896c
|
refs/heads/master
| 2022-05-24T12:59:02.152000 | 2019-05-12T22:41:39 | 2019-05-12T22:41:39 | 43,713,233 | 5 | 1 | null | false | 2017-11-21T10:50:47 | 2015-10-05T20:53:39 | 2016-10-23T00:18:09 | 2017-11-21T10:50:46 | 79,639 | 4 | 1 | 39 |
JavaScript
| false | null |
package com.graffitab.server.service.user;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.graffitab.server.api.errors.RestApiException;
import com.graffitab.server.api.errors.ResultCode;
import com.graffitab.server.persistence.dao.HibernateDaoImpl;
import com.graffitab.server.persistence.model.externalprovider.ExternalProvider;
import com.graffitab.server.persistence.model.externalprovider.ExternalProviderType;
import com.graffitab.server.persistence.model.user.User;
import com.graffitab.server.service.social.SocialNetworksService;
@Service
public class ExternalProviderService {
@Resource
private UserService userService;
@Resource
private HibernateDaoImpl<User, Long> userDao;
@Resource
private HibernateDaoImpl<ExternalProvider, Long> externalProviderDao;
@Resource
private SocialNetworksService socialNetworksService;
@Transactional
public User linkExternalProvider(ExternalProviderType externalProviderType, String externalUserId, String accessToken) {
User currentUser = userService.getCurrentUser();
userService.merge(currentUser);
// Check if this user already has this provider linked.
ExternalProvider externalProviderForCurrentUser = findExternalProvider(currentUser, externalProviderType);
if (externalProviderForCurrentUser != null) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_ALREADY_LINKED, "An external provider for user " + currentUser.getUsername() + " with externalUserId " + externalUserId + " already exists for type " + externalProviderType.name());
}
// Check if there exists other user with this external provider.
User otherUserWithExternalProvider = findUserWithExternalProvider(externalProviderType, externalUserId);
if (otherUserWithExternalProvider != null && !currentUser.equals(otherUserWithExternalProvider)) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_ALREADY_LINKED_FOR_OTHER_USER, "This external provider is already linked to a different user account");
}
// Check if access token is valid.
if (socialNetworksService.isValidToken(accessToken, externalProviderType)) {
currentUser.getExternalProviders().add(ExternalProvider.provider(externalProviderType, externalUserId, accessToken));
}
else {
throw new RestApiException(ResultCode.INVALID_TOKEN,
"The provided token is not valid.");
}
return currentUser;
}
@Transactional
public User unlinkExternalProvider(ExternalProviderType externalProviderType) {
User currentUser = userService.getCurrentUser();
userService.merge(currentUser);
ExternalProvider externalProvider = findExternalProvider(currentUser, externalProviderType);
// Check if an external provider of that type exists for the user.
if (externalProvider == null) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_NOT_FOUND, "An external provider with type " + externalProviderType.name() + " does not exist for user " + currentUser.getUsername());
}
currentUser.getExternalProviders().remove(externalProvider);
return currentUser;
}
@Transactional
public void updateToken(User user, ExternalProviderType externalProviderType, String accessToken) {
ExternalProvider externalProvider = findExternalProvider(user, externalProviderType);
externalProvider.setAccessToken(accessToken);
}
public ExternalProvider findExternalProvider(ExternalProviderType externalProviderType, String externalUserId, String accessToken) {
Query query = externalProviderDao.createNamedQuery("ExternalProvider.findExternalProvider");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("externalUserId", externalUserId);
query.setParameter("accessToken", accessToken);
return (ExternalProvider) query.uniqueResult();
}
public ExternalProvider findExternalProvider(User user, ExternalProviderType externalProviderType) {
Query query = userDao.createNamedQuery("User.findExternalProviderForUser");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("currentUser", user);
return (ExternalProvider) query.uniqueResult();
}
public User findUserWithExternalProvider(ExternalProviderType externalProviderType, String externalUserId) {
Query query = userDao.createNamedQuery("User.findUserWithExternalProvider");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("externalUserId", externalUserId);
return (User) query.uniqueResult();
}
}
|
UTF-8
|
Java
| 4,830 |
java
|
ExternalProviderService.java
|
Java
|
[] | null |
[] |
package com.graffitab.server.service.user;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.graffitab.server.api.errors.RestApiException;
import com.graffitab.server.api.errors.ResultCode;
import com.graffitab.server.persistence.dao.HibernateDaoImpl;
import com.graffitab.server.persistence.model.externalprovider.ExternalProvider;
import com.graffitab.server.persistence.model.externalprovider.ExternalProviderType;
import com.graffitab.server.persistence.model.user.User;
import com.graffitab.server.service.social.SocialNetworksService;
@Service
public class ExternalProviderService {
@Resource
private UserService userService;
@Resource
private HibernateDaoImpl<User, Long> userDao;
@Resource
private HibernateDaoImpl<ExternalProvider, Long> externalProviderDao;
@Resource
private SocialNetworksService socialNetworksService;
@Transactional
public User linkExternalProvider(ExternalProviderType externalProviderType, String externalUserId, String accessToken) {
User currentUser = userService.getCurrentUser();
userService.merge(currentUser);
// Check if this user already has this provider linked.
ExternalProvider externalProviderForCurrentUser = findExternalProvider(currentUser, externalProviderType);
if (externalProviderForCurrentUser != null) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_ALREADY_LINKED, "An external provider for user " + currentUser.getUsername() + " with externalUserId " + externalUserId + " already exists for type " + externalProviderType.name());
}
// Check if there exists other user with this external provider.
User otherUserWithExternalProvider = findUserWithExternalProvider(externalProviderType, externalUserId);
if (otherUserWithExternalProvider != null && !currentUser.equals(otherUserWithExternalProvider)) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_ALREADY_LINKED_FOR_OTHER_USER, "This external provider is already linked to a different user account");
}
// Check if access token is valid.
if (socialNetworksService.isValidToken(accessToken, externalProviderType)) {
currentUser.getExternalProviders().add(ExternalProvider.provider(externalProviderType, externalUserId, accessToken));
}
else {
throw new RestApiException(ResultCode.INVALID_TOKEN,
"The provided token is not valid.");
}
return currentUser;
}
@Transactional
public User unlinkExternalProvider(ExternalProviderType externalProviderType) {
User currentUser = userService.getCurrentUser();
userService.merge(currentUser);
ExternalProvider externalProvider = findExternalProvider(currentUser, externalProviderType);
// Check if an external provider of that type exists for the user.
if (externalProvider == null) {
throw new RestApiException(ResultCode.EXTERNAL_PROVIDER_NOT_FOUND, "An external provider with type " + externalProviderType.name() + " does not exist for user " + currentUser.getUsername());
}
currentUser.getExternalProviders().remove(externalProvider);
return currentUser;
}
@Transactional
public void updateToken(User user, ExternalProviderType externalProviderType, String accessToken) {
ExternalProvider externalProvider = findExternalProvider(user, externalProviderType);
externalProvider.setAccessToken(accessToken);
}
public ExternalProvider findExternalProvider(ExternalProviderType externalProviderType, String externalUserId, String accessToken) {
Query query = externalProviderDao.createNamedQuery("ExternalProvider.findExternalProvider");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("externalUserId", externalUserId);
query.setParameter("accessToken", accessToken);
return (ExternalProvider) query.uniqueResult();
}
public ExternalProvider findExternalProvider(User user, ExternalProviderType externalProviderType) {
Query query = userDao.createNamedQuery("User.findExternalProviderForUser");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("currentUser", user);
return (ExternalProvider) query.uniqueResult();
}
public User findUserWithExternalProvider(ExternalProviderType externalProviderType, String externalUserId) {
Query query = userDao.createNamedQuery("User.findUserWithExternalProvider");
query.setParameter("externalProviderType", externalProviderType);
query.setParameter("externalUserId", externalUserId);
return (User) query.uniqueResult();
}
}
| 4,830 | 0.772464 | 0.772464 | 104 | 45.442307 | 46.217884 | 249 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.057692 | false | false |
10
|
4cab2e2ded6ff66ea2449d21c27ee791fa401f62
| 4,956,392,263,473 |
84c6082945f1e9f2798801cf8069868e176eb4f2
|
/src/main/java/org/zada/template/node/NodeType.java
|
626930f070f1a20de71adc02424469a5f861dbe6
|
[] |
no_license
|
codechapin/zada
|
https://github.com/codechapin/zada
|
f9c14730fbc31fc78600f4482c4cfb0b851ea3ef
|
d0529dbea361f5e8994aa9f8736ad8efc06b9442
|
refs/heads/master
| 2018-12-30T00:27:19.840000 | 2013-11-21T02:29:22 | 2013-11-21T02:29:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.zada.template.node;
/**
*
*
*/
public enum NodeType {
ACTION,
IF,
LIST,
RANGE,
TEMPLATE,
TEXT,
WITH,
END,
PIPE,
}
|
UTF-8
|
Java
| 167 |
java
|
NodeType.java
|
Java
|
[] | null |
[] |
package org.zada.template.node;
/**
*
*
*/
public enum NodeType {
ACTION,
IF,
LIST,
RANGE,
TEMPLATE,
TEXT,
WITH,
END,
PIPE,
}
| 167 | 0.502994 | 0.502994 | 18 | 8.277778 | 7.694194 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
10
|
4e39a9e39bc02ac6b5f9a7d78929e993553a8e3b
| 2,680,059,605,075 |
716fd5e4352b3ead73e09c01baa720434fb25198
|
/sayiBulma/src/sayiBulma/Main.java
|
1ff7f57928e126cebb4f72ffbbd5cb92a55046fe
|
[
"MIT"
] |
permissive
|
FikriyeBarut/javaCamp
|
https://github.com/FikriyeBarut/javaCamp
|
1bb67cf5ddad839c2a2ee57c808fbd58262f5e1d
|
742b645b102ca8d93a2d698bc98cd553eec2cd55
|
refs/heads/main
| 2023-04-20T05:18:27.097000 | 2023-02-10T19:28:48 | 2023-02-10T19:28:48 | 364,710,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sayiBulma;
public class Main {
public static void main(String[] args) {
int[] sayilar =new int[] {1,2,3,4,5};
int aranacak=5;
boolean varMę=false;
for(int sayi:sayilar) {
if(sayi==aranacak) {
varMę=true;
break;
}
}
if(varMę==true) {
System.out.println("Bulundu");
}else {
System.out.println("Sayi yok");
}
}
}
|
ISO-8859-16
|
Java
| 366 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package sayiBulma;
public class Main {
public static void main(String[] args) {
int[] sayilar =new int[] {1,2,3,4,5};
int aranacak=5;
boolean varMę=false;
for(int sayi:sayilar) {
if(sayi==aranacak) {
varMę=true;
break;
}
}
if(varMę==true) {
System.out.println("Bulundu");
}else {
System.out.println("Sayi yok");
}
}
}
| 366 | 0.597796 | 0.581267 | 24 | 14.125 | 13.039403 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.166667 | false | false |
10
|
436c70379420572e137494fa288352bccaf9d09e
| 13,735,305,434,140 |
be418c46fe986690090311e545f6f9b3de13898b
|
/StockHandlingSASClient/src/lk/edu/ijse/sas/view/MaterialReportController.java
|
d809f997fb5200a99f3a50e557217f2423aec7e9
|
[] |
no_license
|
DimuthuKasunWP/StockHandlingSystem
|
https://github.com/DimuthuKasunWP/StockHandlingSystem
|
757fa2f8374da1aef77fccaf4c67fd95484c5e06
|
a092e19961b49af188c3cb94eb1bd167adc7f51a
|
refs/heads/master
| 2021-07-11T10:06:20.382000 | 2020-08-30T08:00:28 | 2020-08-30T08:00:28 | 196,627,880 | 4 | 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 lk.edu.ijse.sas.view;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDatePicker;
import lk.edu.ijse.sas.controller.ControllerFactory;
import lk.edu.ijse.sas.controller.custom.Batch_receiveController;
import lk.edu.ijse.sas.controller.custom.MaterialController;
import lk.edu.ijse.sas.controller.custom.Remove_receive_materialController;
import lk.edu.ijse.sas.controller.custom.Remove_return_materialController;
import lk.edu.ijse.sas.controller.custom.Return_batch_receiveController;
import com.sas.kem.edu.ijse.dto.BatchGrnDetailsDTO;
import com.sas.kem.edu.ijse.dto.Batch_receiveDTO;
import com.sas.kem.edu.ijse.dto.MaterialDTO;
import com.sas.kem.edu.ijse.dto.Remove_receive_materialDTO;
import com.sas.kem.edu.ijse.dto.Remove_return_materialDTO;
import com.sas.kem.edu.ijse.dto.Return_batch_receiveDTO;
import lk.edu.ijse.sas.tableModel.MaterialReceiveTableModel;
import lk.edu.ijse.sas.tableModel.MaterialRemoveTableModel;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import lk.edu.ijse.sas.controller.custom.QueryController;
/**
* FXML Controller class
*
* @author dimuthu
*/
public class MaterialReportController implements Initializable {
@FXML
private JFXComboBox cmbMaterial;
@FXML
private Label lblRecMat;
@FXML
private Label lblRemMat;
@FXML
private JFXDatePicker dtView;
@FXML
private TextField txtDate;
@FXML
private TableView tblReceive;
@FXML
private TableView tblRemove;
@FXML
private TableColumn colRecDisc;
@FXML
private TableColumn colRecBatch;
@FXML
private TableColumn colRecQty;
@FXML
private TableColumn colRecUnitPrice;
@FXML
private TableColumn colRecTotal;
@FXML
private TableColumn colRecTime;
@FXML
private TableColumn colRecDate;
@FXML
private TableColumn colRemDisc;
@FXML
private TableColumn colRemBatch;
@FXML
private TableColumn colRemQty;
@FXML
private TableColumn colRemSecName;
@FXML
private TableColumn colRemTime;
@FXML
private TableColumn colRemDate;
@FXML
private AnchorPane thisPane;
ObservableList<MaterialReceiveTableModel> recList=FXCollections.observableArrayList();
ObservableList<MaterialRemoveTableModel> remList=FXCollections.observableArrayList();
private MaterialController ctrlMat;
private Remove_receive_materialController ctrlRemRecMat;
private Remove_return_materialController ctrlRemRetMat;
private Batch_receiveController ctrlBatchReceive;
private Return_batch_receiveController ctrlReturnReceive;
private QueryController ctrlQuary;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
setUIs();
SetReceiveTableProperty();
SetRemoveTableProperty();
setControllers();
loadCmbMaterial();
setDate();
}
private void setControllers() {
ctrlMat=(MaterialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.MATERIAL);
ctrlRemRecMat=(Remove_receive_materialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.REMOVE_RECEIVE_MATERIAL);
ctrlRemRetMat=(Remove_return_materialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.REMOVE_RETURN_MATERIAL);
ctrlBatchReceive=(Batch_receiveController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.BATCH_RECEIVE);
ctrlReturnReceive=(Return_batch_receiveController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.RETURN_BATCH_RECEIVE);
ctrlQuary=(QueryController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.QUARY);
}
private void SetReceiveTableProperty() {
colRecDisc.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Desc"));
colRecQty.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Qty"));
colRecUnitPrice.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("UnitPrice"));
colRecTotal.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Total"));
colRecTime.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Time"));
colRecDate.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Date"));
colRecBatch.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Batch"));
tblReceive.getItems().clear();
tblReceive.setItems(recList);
tblReceive.refresh();
}
private void SetRemoveTableProperty() {
colRemDisc.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Desc"));
colRemQty.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Qty"));
colRemSecName.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("SecName"));
colRemTime.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Time"));
colRemDate.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Date"));
colRemBatch.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Batch"));
tblRemove.getItems().clear();
tblRemove.setItems(remList);
tblRemove.refresh();
}
@FXML
private void cmbMatOnAction(ActionEvent evt){
tblReceive.getItems().clear();
tblRemove.getItems().clear();
recList.clear();
remList.clear();
String name=cmbMaterial.getSelectionModel().getSelectedItem().toString();
lblRecMat.setVisible(true);
lblRecMat.setText(name);
lblRemMat.setVisible(true);
lblRemMat.setText(name);
DecimalFormat df=new DecimalFormat("#,###.00");
df.setMaximumFractionDigits(2);
try {
ArrayList<Batch_receiveDTO> bRecList=ctrlBatchReceive.getAll();
for (Batch_receiveDTO batch_receiveDTO : bRecList) {
if(ctrlMat.getMaterialId(name).equals(batch_receiveDTO.getMid())){
String desc=name;
String batch=batch_receiveDTO.getBrid();
BigDecimal quantity=batch_receiveDTO.getReceived_qty_kg();
String qty=df.format(quantity);
BigDecimal unitprice=batch_receiveDTO.getUnitPrice_1kg();
String unitPrice=df.format(unitprice);
BigDecimal Total=batch_receiveDTO.getTotal();
String total=df.format(Total);
BatchGrnDetailsDTO b=ctrlQuary.getBatchGrnDetails(batch_receiveDTO.getBrid());
String time=b.getTime();
String date=b.getDate();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Return_batch_receiveDTO>bRetList=ctrlReturnReceive.getAll();
for (Return_batch_receiveDTO return_batch_receiveDTO : bRetList) {
if(ctrlMat.getMaterialId(name).equals(return_batch_receiveDTO.getMid())){
String desc=name;
String batch=return_batch_receiveDTO.getRbrid();
BigDecimal quantity=return_batch_receiveDTO.getReturned_qty();
String qty=df.format(quantity);
BigDecimal unitprice=return_batch_receiveDTO.getUnitPrice();
String unitPrice=df.format(unitprice);
BigDecimal Total=return_batch_receiveDTO.getTotal();
String total=df.format(Total);
BatchGrnDetailsDTO b=ctrlQuary.getReturnBatchGrnDetails(return_batch_receiveDTO.getRbrid());
String time=b.getTime();
String date=b.getDate();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Remove_receive_materialDTO> remRecList=ctrlRemRecMat.getAll();
for (Remove_receive_materialDTO remove_receive_materialDTO : remRecList) {
if(ctrlMat.getMaterialId(name).equals(remove_receive_materialDTO.getMid())){
String desc=name;
String batch=remove_receive_materialDTO.getBrid();
BigDecimal quantity=remove_receive_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_receive_materialDTO.getCarry_sector_name();
String time=remove_receive_materialDTO.getRemove_time();
String date=remove_receive_materialDTO.getRemove_date();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setSecName(secName);
tb.setQty(qty);
tb.setTime(time);
remList.add(tb);
}
}
ArrayList<Remove_return_materialDTO> remRetList=ctrlRemRetMat.getAll();
for (Remove_return_materialDTO remove_return_materialDTO : remRetList) {
if(ctrlMat.getMaterialId(name).equals(remove_return_materialDTO.getMid())){
String desc=name;
String batch=remove_return_materialDTO.getRbrid();
BigDecimal quantity=remove_return_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_return_materialDTO.getCarry_sector_name();
String time=remove_return_materialDTO.getRemove_time();
String date=remove_return_materialDTO.getRemove_date();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setSecName(secName);
tb.setQty(qty);
tb.setTime(time);
remList.add(tb);
}
}
} catch (Exception ex) {
Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadCmbMaterial() {
try {
ctrlMat=(MaterialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.MATERIAL);
ArrayList<MaterialDTO> mlist=ctrlMat.getAll();
for (MaterialDTO materialDTO : mlist) {
cmbMaterial.getItems().add(materialDTO.getMaterialName());
}
} catch (Exception ex) {
//Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setDate() {
Date d=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String date=df.format(d);
txtDate.setText(date);
}
@FXML
private void dateOnAction(ActionEvent evt){
lblRecMat.setVisible(false);
lblRemMat.setVisible(false);
recList.clear();
remList.clear();
tblReceive.getItems().clear();
tblRemove.getItems().clear();
DecimalFormat df=new DecimalFormat("#,###.00");
df.setMaximumFractionDigits(2);
String date=dtView.getValue().toString();
try {
ArrayList<Batch_receiveDTO> bRecList=ctrlBatchReceive.getAll();
for (Batch_receiveDTO batch_receiveDTO : bRecList) {
BatchGrnDetailsDTO b=ctrlQuary.getBatchGrnDetails(batch_receiveDTO.getBrid());
if(date.equals(b.getDate())){
String desc=ctrlMat.getMatName(batch_receiveDTO.getMid());
String batch=batch_receiveDTO.getBrid();
BigDecimal quantity=batch_receiveDTO.getReceived_qty_kg();
String qty=df.format(quantity);
BigDecimal unitprice=batch_receiveDTO.getUnitPrice_1kg();
String unitPrice=df.format(unitprice);
BigDecimal Total=batch_receiveDTO.getTotal();
String total=df.format(Total);
String time=b.getTime();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Return_batch_receiveDTO> bRetList=ctrlReturnReceive.getAll();
for (Return_batch_receiveDTO return_batch_receiveDTO : bRetList) {
BatchGrnDetailsDTO b=ctrlQuary.getReturnBatchGrnDetails(return_batch_receiveDTO.getRbrid());
if(date.equals(b.getDate())){
String desc=ctrlMat.getMatName(return_batch_receiveDTO.getMid());
String batch=return_batch_receiveDTO.getRbrid();
BigDecimal quantity=return_batch_receiveDTO.getReturned_qty();
String qty=df.format(quantity);
BigDecimal unitprice=return_batch_receiveDTO.getUnitPrice();
String unitPrice=df.format(unitprice);
BigDecimal Total=return_batch_receiveDTO.getTotal();
String total=df.format(Total);
String time=b.getTime();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Remove_receive_materialDTO> remRecList=ctrlRemRecMat.getAll();
for (Remove_receive_materialDTO remove_receive_materialDTO : remRecList) {
if(date.equals(remove_receive_materialDTO.getRemove_date())){
String desc=ctrlMat.getMatName(remove_receive_materialDTO.getMid());
String batch=remove_receive_materialDTO.getBrid();
BigDecimal quantity=remove_receive_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_receive_materialDTO.getCarry_sector_name();
String time=remove_receive_materialDTO.getRemove_time();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setSecName(secName);
tb.setTime(time);
remList.add(tb);
}
}
ArrayList<Remove_return_materialDTO> remRetList=ctrlRemRetMat.getAll();
for (Remove_return_materialDTO remove_return_materialDTO : remRetList) {
if(date.equals(remove_return_materialDTO.getRemove_date())){
String desc=ctrlMat.getMatName(remove_return_materialDTO.getMid());
String batch=remove_return_materialDTO.getRbrid();
BigDecimal quantity=remove_return_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_return_materialDTO.getCarry_sector_name();
String time=remove_return_materialDTO.getRemove_time();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setSecName(secName);
tb.setTime(time);
remList.add(tb);
}
}
} catch (Exception ex) {
//Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setUIs() {
thisPane.setOnKeyReleased(e->{
switch(e.getCode()){
case DIGIT1: try{
AnchorPane contain=FXMLLoader.load(getClass().getResource("/com/sas/kem/edu/ijse/view/ProductionReport.fxml"));
DashBoardController.rootPane.getChildren().setAll(contain);
}catch(IOException ex){
}
break;
case DIGIT3: try{
AnchorPane contain=FXMLLoader.load(getClass().getResource("/com/sas/kem/edu/ijse/view/SearchStock.fxml"));
DashBoardController.rootPane.getChildren().setAll(contain);
}catch(IOException ex){
}
break;
case ESCAPE: try{
AnchorPane sidePane = FXMLLoader.load(getClass().getResource(("/com/sas/kem/edu/ijse/view/MainSidePane.fxml")));
DashBoardController.sideP.getChildren().setAll(sidePane);
AnchorPane contentPane = FXMLLoader.load(getClass().getResource(("/com/sas/kem/edu/ijse/view/SelectionPage.fxml")));
DashBoardController.rootPane.getChildren().setAll(contentPane);
}catch(IOException ex){
}
break;
}
});
}
}
|
UTF-8
|
Java
| 21,811 |
java
|
MaterialReportController.java
|
Java
|
[
{
"context": "oller;\n\n/**\n * FXML Controller class\n *\n * @author dimuthu\n */\npublic class MaterialReportController impleme",
"end": 2033,
"score": 0.9969787001609802,
"start": 2026,
"tag": "USERNAME",
"value": "dimuthu"
}
] | 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 lk.edu.ijse.sas.view;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXDatePicker;
import lk.edu.ijse.sas.controller.ControllerFactory;
import lk.edu.ijse.sas.controller.custom.Batch_receiveController;
import lk.edu.ijse.sas.controller.custom.MaterialController;
import lk.edu.ijse.sas.controller.custom.Remove_receive_materialController;
import lk.edu.ijse.sas.controller.custom.Remove_return_materialController;
import lk.edu.ijse.sas.controller.custom.Return_batch_receiveController;
import com.sas.kem.edu.ijse.dto.BatchGrnDetailsDTO;
import com.sas.kem.edu.ijse.dto.Batch_receiveDTO;
import com.sas.kem.edu.ijse.dto.MaterialDTO;
import com.sas.kem.edu.ijse.dto.Remove_receive_materialDTO;
import com.sas.kem.edu.ijse.dto.Remove_return_materialDTO;
import com.sas.kem.edu.ijse.dto.Return_batch_receiveDTO;
import lk.edu.ijse.sas.tableModel.MaterialReceiveTableModel;
import lk.edu.ijse.sas.tableModel.MaterialRemoveTableModel;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import lk.edu.ijse.sas.controller.custom.QueryController;
/**
* FXML Controller class
*
* @author dimuthu
*/
public class MaterialReportController implements Initializable {
@FXML
private JFXComboBox cmbMaterial;
@FXML
private Label lblRecMat;
@FXML
private Label lblRemMat;
@FXML
private JFXDatePicker dtView;
@FXML
private TextField txtDate;
@FXML
private TableView tblReceive;
@FXML
private TableView tblRemove;
@FXML
private TableColumn colRecDisc;
@FXML
private TableColumn colRecBatch;
@FXML
private TableColumn colRecQty;
@FXML
private TableColumn colRecUnitPrice;
@FXML
private TableColumn colRecTotal;
@FXML
private TableColumn colRecTime;
@FXML
private TableColumn colRecDate;
@FXML
private TableColumn colRemDisc;
@FXML
private TableColumn colRemBatch;
@FXML
private TableColumn colRemQty;
@FXML
private TableColumn colRemSecName;
@FXML
private TableColumn colRemTime;
@FXML
private TableColumn colRemDate;
@FXML
private AnchorPane thisPane;
ObservableList<MaterialReceiveTableModel> recList=FXCollections.observableArrayList();
ObservableList<MaterialRemoveTableModel> remList=FXCollections.observableArrayList();
private MaterialController ctrlMat;
private Remove_receive_materialController ctrlRemRecMat;
private Remove_return_materialController ctrlRemRetMat;
private Batch_receiveController ctrlBatchReceive;
private Return_batch_receiveController ctrlReturnReceive;
private QueryController ctrlQuary;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
setUIs();
SetReceiveTableProperty();
SetRemoveTableProperty();
setControllers();
loadCmbMaterial();
setDate();
}
private void setControllers() {
ctrlMat=(MaterialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.MATERIAL);
ctrlRemRecMat=(Remove_receive_materialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.REMOVE_RECEIVE_MATERIAL);
ctrlRemRetMat=(Remove_return_materialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.REMOVE_RETURN_MATERIAL);
ctrlBatchReceive=(Batch_receiveController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.BATCH_RECEIVE);
ctrlReturnReceive=(Return_batch_receiveController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.RETURN_BATCH_RECEIVE);
ctrlQuary=(QueryController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.QUARY);
}
private void SetReceiveTableProperty() {
colRecDisc.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Desc"));
colRecQty.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Qty"));
colRecUnitPrice.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("UnitPrice"));
colRecTotal.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Total"));
colRecTime.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Time"));
colRecDate.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Date"));
colRecBatch.setCellValueFactory(new PropertyValueFactory<MaterialReceiveTableModel,String>("Batch"));
tblReceive.getItems().clear();
tblReceive.setItems(recList);
tblReceive.refresh();
}
private void SetRemoveTableProperty() {
colRemDisc.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Desc"));
colRemQty.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Qty"));
colRemSecName.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("SecName"));
colRemTime.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Time"));
colRemDate.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Date"));
colRemBatch.setCellValueFactory(new PropertyValueFactory<MaterialRemoveTableModel,String>("Batch"));
tblRemove.getItems().clear();
tblRemove.setItems(remList);
tblRemove.refresh();
}
@FXML
private void cmbMatOnAction(ActionEvent evt){
tblReceive.getItems().clear();
tblRemove.getItems().clear();
recList.clear();
remList.clear();
String name=cmbMaterial.getSelectionModel().getSelectedItem().toString();
lblRecMat.setVisible(true);
lblRecMat.setText(name);
lblRemMat.setVisible(true);
lblRemMat.setText(name);
DecimalFormat df=new DecimalFormat("#,###.00");
df.setMaximumFractionDigits(2);
try {
ArrayList<Batch_receiveDTO> bRecList=ctrlBatchReceive.getAll();
for (Batch_receiveDTO batch_receiveDTO : bRecList) {
if(ctrlMat.getMaterialId(name).equals(batch_receiveDTO.getMid())){
String desc=name;
String batch=batch_receiveDTO.getBrid();
BigDecimal quantity=batch_receiveDTO.getReceived_qty_kg();
String qty=df.format(quantity);
BigDecimal unitprice=batch_receiveDTO.getUnitPrice_1kg();
String unitPrice=df.format(unitprice);
BigDecimal Total=batch_receiveDTO.getTotal();
String total=df.format(Total);
BatchGrnDetailsDTO b=ctrlQuary.getBatchGrnDetails(batch_receiveDTO.getBrid());
String time=b.getTime();
String date=b.getDate();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Return_batch_receiveDTO>bRetList=ctrlReturnReceive.getAll();
for (Return_batch_receiveDTO return_batch_receiveDTO : bRetList) {
if(ctrlMat.getMaterialId(name).equals(return_batch_receiveDTO.getMid())){
String desc=name;
String batch=return_batch_receiveDTO.getRbrid();
BigDecimal quantity=return_batch_receiveDTO.getReturned_qty();
String qty=df.format(quantity);
BigDecimal unitprice=return_batch_receiveDTO.getUnitPrice();
String unitPrice=df.format(unitprice);
BigDecimal Total=return_batch_receiveDTO.getTotal();
String total=df.format(Total);
BatchGrnDetailsDTO b=ctrlQuary.getReturnBatchGrnDetails(return_batch_receiveDTO.getRbrid());
String time=b.getTime();
String date=b.getDate();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Remove_receive_materialDTO> remRecList=ctrlRemRecMat.getAll();
for (Remove_receive_materialDTO remove_receive_materialDTO : remRecList) {
if(ctrlMat.getMaterialId(name).equals(remove_receive_materialDTO.getMid())){
String desc=name;
String batch=remove_receive_materialDTO.getBrid();
BigDecimal quantity=remove_receive_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_receive_materialDTO.getCarry_sector_name();
String time=remove_receive_materialDTO.getRemove_time();
String date=remove_receive_materialDTO.getRemove_date();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setSecName(secName);
tb.setQty(qty);
tb.setTime(time);
remList.add(tb);
}
}
ArrayList<Remove_return_materialDTO> remRetList=ctrlRemRetMat.getAll();
for (Remove_return_materialDTO remove_return_materialDTO : remRetList) {
if(ctrlMat.getMaterialId(name).equals(remove_return_materialDTO.getMid())){
String desc=name;
String batch=remove_return_materialDTO.getRbrid();
BigDecimal quantity=remove_return_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_return_materialDTO.getCarry_sector_name();
String time=remove_return_materialDTO.getRemove_time();
String date=remove_return_materialDTO.getRemove_date();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setSecName(secName);
tb.setQty(qty);
tb.setTime(time);
remList.add(tb);
}
}
} catch (Exception ex) {
Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadCmbMaterial() {
try {
ctrlMat=(MaterialController) ControllerFactory.getInstance().getContollerTypes(ControllerFactory.ControllerTypes.MATERIAL);
ArrayList<MaterialDTO> mlist=ctrlMat.getAll();
for (MaterialDTO materialDTO : mlist) {
cmbMaterial.getItems().add(materialDTO.getMaterialName());
}
} catch (Exception ex) {
//Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setDate() {
Date d=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String date=df.format(d);
txtDate.setText(date);
}
@FXML
private void dateOnAction(ActionEvent evt){
lblRecMat.setVisible(false);
lblRemMat.setVisible(false);
recList.clear();
remList.clear();
tblReceive.getItems().clear();
tblRemove.getItems().clear();
DecimalFormat df=new DecimalFormat("#,###.00");
df.setMaximumFractionDigits(2);
String date=dtView.getValue().toString();
try {
ArrayList<Batch_receiveDTO> bRecList=ctrlBatchReceive.getAll();
for (Batch_receiveDTO batch_receiveDTO : bRecList) {
BatchGrnDetailsDTO b=ctrlQuary.getBatchGrnDetails(batch_receiveDTO.getBrid());
if(date.equals(b.getDate())){
String desc=ctrlMat.getMatName(batch_receiveDTO.getMid());
String batch=batch_receiveDTO.getBrid();
BigDecimal quantity=batch_receiveDTO.getReceived_qty_kg();
String qty=df.format(quantity);
BigDecimal unitprice=batch_receiveDTO.getUnitPrice_1kg();
String unitPrice=df.format(unitprice);
BigDecimal Total=batch_receiveDTO.getTotal();
String total=df.format(Total);
String time=b.getTime();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Return_batch_receiveDTO> bRetList=ctrlReturnReceive.getAll();
for (Return_batch_receiveDTO return_batch_receiveDTO : bRetList) {
BatchGrnDetailsDTO b=ctrlQuary.getReturnBatchGrnDetails(return_batch_receiveDTO.getRbrid());
if(date.equals(b.getDate())){
String desc=ctrlMat.getMatName(return_batch_receiveDTO.getMid());
String batch=return_batch_receiveDTO.getRbrid();
BigDecimal quantity=return_batch_receiveDTO.getReturned_qty();
String qty=df.format(quantity);
BigDecimal unitprice=return_batch_receiveDTO.getUnitPrice();
String unitPrice=df.format(unitprice);
BigDecimal Total=return_batch_receiveDTO.getTotal();
String total=df.format(Total);
String time=b.getTime();
MaterialReceiveTableModel tb=new MaterialReceiveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setTime(time);
tb.setTotal(total);
tb.setUnitPrice(unitPrice);
recList.add(tb);
}
}
ArrayList<Remove_receive_materialDTO> remRecList=ctrlRemRecMat.getAll();
for (Remove_receive_materialDTO remove_receive_materialDTO : remRecList) {
if(date.equals(remove_receive_materialDTO.getRemove_date())){
String desc=ctrlMat.getMatName(remove_receive_materialDTO.getMid());
String batch=remove_receive_materialDTO.getBrid();
BigDecimal quantity=remove_receive_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_receive_materialDTO.getCarry_sector_name();
String time=remove_receive_materialDTO.getRemove_time();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setSecName(secName);
tb.setTime(time);
remList.add(tb);
}
}
ArrayList<Remove_return_materialDTO> remRetList=ctrlRemRetMat.getAll();
for (Remove_return_materialDTO remove_return_materialDTO : remRetList) {
if(date.equals(remove_return_materialDTO.getRemove_date())){
String desc=ctrlMat.getMatName(remove_return_materialDTO.getMid());
String batch=remove_return_materialDTO.getRbrid();
BigDecimal quantity=remove_return_materialDTO.getQty_kg();
String qty=df.format(quantity);
String secName=remove_return_materialDTO.getCarry_sector_name();
String time=remove_return_materialDTO.getRemove_time();
MaterialRemoveTableModel tb=new MaterialRemoveTableModel();
tb.setBatch(batch);
tb.setDate(date);
tb.setDesc(desc);
tb.setQty(qty);
tb.setSecName(secName);
tb.setTime(time);
remList.add(tb);
}
}
} catch (Exception ex) {
//Logger.getLogger(MaterialReportController.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setUIs() {
thisPane.setOnKeyReleased(e->{
switch(e.getCode()){
case DIGIT1: try{
AnchorPane contain=FXMLLoader.load(getClass().getResource("/com/sas/kem/edu/ijse/view/ProductionReport.fxml"));
DashBoardController.rootPane.getChildren().setAll(contain);
}catch(IOException ex){
}
break;
case DIGIT3: try{
AnchorPane contain=FXMLLoader.load(getClass().getResource("/com/sas/kem/edu/ijse/view/SearchStock.fxml"));
DashBoardController.rootPane.getChildren().setAll(contain);
}catch(IOException ex){
}
break;
case ESCAPE: try{
AnchorPane sidePane = FXMLLoader.load(getClass().getResource(("/com/sas/kem/edu/ijse/view/MainSidePane.fxml")));
DashBoardController.sideP.getChildren().setAll(sidePane);
AnchorPane contentPane = FXMLLoader.load(getClass().getResource(("/com/sas/kem/edu/ijse/view/SelectionPage.fxml")));
DashBoardController.rootPane.getChildren().setAll(contentPane);
}catch(IOException ex){
}
break;
}
});
}
}
| 21,811 | 0.561827 | 0.561368 | 542 | 39.241699 | 31.720858 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575646 | false | false |
10
|
0c84ba1d1368d554a045f4461d38f9c56996c962
| 31,533,649,958,218 |
8ad10270b1e32cfe0cb712a74a93c1243a9be881
|
/emma-controller/src/main/java/io/edgerun/emma/controller/ControllerShell.java
|
54da9ba7c80b523e53366245d937e53d223014d5
|
[] |
no_license
|
edgerun/emma-master
|
https://github.com/edgerun/emma-master
|
d4e02f27a112da2ab0c3a576d4e648252d8adba1
|
5bf350659ec05fbd4380df5afc233507c53aa26d
|
refs/heads/master
| 2022-08-16T15:20:46.071000 | 2020-05-26T22:33:54 | 2020-05-26T22:33:54 | 267,140,729 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.edgerun.emma.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.edgerun.emma.controller.model.Broker;
import io.edgerun.emma.controller.model.BrokerRepository;
import io.edgerun.emma.controller.model.Client;
import io.edgerun.emma.controller.model.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import io.edgerun.emma.controller.network.NetworkManager;
import io.edgerun.emma.controller.service.MonitoringService;
import io.edgerun.emma.controller.service.sub.Subscription;
import io.edgerun.emma.controller.service.sub.SubscriptionTable;
import io.edgerun.emma.util.NetUtils;
import at.ac.tuwien.dsg.orvell.Context;
import at.ac.tuwien.dsg.orvell.annotation.Command;
import at.ac.tuwien.dsg.orvell.annotation.CommandGroup;
@CommandGroup("emma")
@Component
public class ControllerShell {
@Autowired
private Environment environment;
@Autowired
private SubscriptionTable subscriptions;
@Autowired
private MonitoringService monitoringService;
@Autowired
private NetworkManager networkManager;
@Autowired
private ClientRepository clientRepository;
@Autowired
private BrokerRepository brokerRepository;
@Command(name = "sub-list")
public void listSubscriptions(Context ctx) {
for (Subscription sub : subscriptions.getSubscriptions()) {
ctx.out().printf("%-16s : %s%n", sub.getBroker().getId(), sub.getFilter());
}
}
@Command(name = "broker-list")
public void listBrokers(Context ctx) {
for (Broker broker : brokerRepository.getHosts().values()) {
ctx.out().println(broker);
}
}
@Command(name = "network")
public void network(Context ctx) {
ctx.out().println(networkManager.getNetwork());
}
@Command
public void reconnect(String clientId, String brokerId) {
Client client = clientRepository.getById(clientId);
if (client == null) {
throw new IllegalArgumentException("No such client " + clientId);
}
Broker broker = brokerRepository.getById(brokerId);
if (broker == null) {
throw new IllegalArgumentException("No such broker " + brokerId);
}
monitoringService.reconnect(client, broker);
}
@Command
public void env(Context ctx) {
Map<String, Object> properties = getAllProperties();
List<String> keys = new ArrayList<>(properties.keySet());
keys.removeIf(key -> !key.startsWith("emma."));
keys.sort(String::compareTo);
for (String key : keys) {
ctx.out().printf("%-30s %s%n", key, properties.get(key));
}
ctx.out().flush();
}
@Command
public void pingreq(Context ctx, String source, String target) {
monitoringService.pingRequest(
NetUtils.parseSocketAddress(source),
NetUtils.parseSocketAddress(target)
);
}
private Map<String, Object> getAllProperties() {
Map<String, Object> map = new HashMap<>();
for (PropertySource<?> propertySource : ((AbstractEnvironment) environment).getPropertySources()) {
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
return map;
}
}
|
UTF-8
|
Java
| 3,686 |
java
|
ControllerShell.java
|
Java
|
[
{
"context": "));\n keys.removeIf(key -> !key.startsWith(\"emma.\"));\n keys.sort(String::compareTo);\n\n ",
"end": 2843,
"score": 0.8904590606689453,
"start": 2839,
"tag": "KEY",
"value": "emma"
}
] | null |
[] |
package io.edgerun.emma.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.edgerun.emma.controller.model.Broker;
import io.edgerun.emma.controller.model.BrokerRepository;
import io.edgerun.emma.controller.model.Client;
import io.edgerun.emma.controller.model.ClientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import io.edgerun.emma.controller.network.NetworkManager;
import io.edgerun.emma.controller.service.MonitoringService;
import io.edgerun.emma.controller.service.sub.Subscription;
import io.edgerun.emma.controller.service.sub.SubscriptionTable;
import io.edgerun.emma.util.NetUtils;
import at.ac.tuwien.dsg.orvell.Context;
import at.ac.tuwien.dsg.orvell.annotation.Command;
import at.ac.tuwien.dsg.orvell.annotation.CommandGroup;
@CommandGroup("emma")
@Component
public class ControllerShell {
@Autowired
private Environment environment;
@Autowired
private SubscriptionTable subscriptions;
@Autowired
private MonitoringService monitoringService;
@Autowired
private NetworkManager networkManager;
@Autowired
private ClientRepository clientRepository;
@Autowired
private BrokerRepository brokerRepository;
@Command(name = "sub-list")
public void listSubscriptions(Context ctx) {
for (Subscription sub : subscriptions.getSubscriptions()) {
ctx.out().printf("%-16s : %s%n", sub.getBroker().getId(), sub.getFilter());
}
}
@Command(name = "broker-list")
public void listBrokers(Context ctx) {
for (Broker broker : brokerRepository.getHosts().values()) {
ctx.out().println(broker);
}
}
@Command(name = "network")
public void network(Context ctx) {
ctx.out().println(networkManager.getNetwork());
}
@Command
public void reconnect(String clientId, String brokerId) {
Client client = clientRepository.getById(clientId);
if (client == null) {
throw new IllegalArgumentException("No such client " + clientId);
}
Broker broker = brokerRepository.getById(brokerId);
if (broker == null) {
throw new IllegalArgumentException("No such broker " + brokerId);
}
monitoringService.reconnect(client, broker);
}
@Command
public void env(Context ctx) {
Map<String, Object> properties = getAllProperties();
List<String> keys = new ArrayList<>(properties.keySet());
keys.removeIf(key -> !key.startsWith("emma."));
keys.sort(String::compareTo);
for (String key : keys) {
ctx.out().printf("%-30s %s%n", key, properties.get(key));
}
ctx.out().flush();
}
@Command
public void pingreq(Context ctx, String source, String target) {
monitoringService.pingRequest(
NetUtils.parseSocketAddress(source),
NetUtils.parseSocketAddress(target)
);
}
private Map<String, Object> getAllProperties() {
Map<String, Object> map = new HashMap<>();
for (PropertySource<?> propertySource : ((AbstractEnvironment) environment).getPropertySources()) {
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
return map;
}
}
| 3,686 | 0.688551 | 0.687466 | 116 | 30.775862 | 25.372429 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508621 | false | false |
10
|
8d8f5d57bd6141c21ffb7ddb0f292d045b6c5798
| 3,942,779,979,662 |
4c7caa52ed09c88a9f491ebec11a755693d390b5
|
/src/JSONWriter.java
|
3ad134714c863b4ee75295ad159be49144d9ce63
|
[] |
no_license
|
mbmcpartland/multithreadedSearchEngine
|
https://github.com/mbmcpartland/multithreadedSearchEngine
|
096f05aa8107bbdab6115ee771185f9fce06ed6b
|
7766649365a5473d3d8a34f2f8114b9377c570aa
|
refs/heads/master
| 2020-03-18T10:49:36.837000 | 2017-05-17T02:12:55 | 2017-05-17T02:12:55 | 134,635,421 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Map.Entry;
/**
* This class is used to write to the JSON
* file. I also put Sophie's indent function
* in this class.
* @author mitchellmcpartland
*/
public class JSONWriter {
/**
* Used to write to the output JSON file.
*
* @param InvertedIndex to read
* @param output Path to write the JSON file to
*/
public static void writeJSON(TreeMap<String, TreeMap<String, TreeSet<Integer>>> index, Path path) throws IOException {
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write("{");
writer.write(System.lineSeparator());
Iterator<Entry<String, TreeMap<String, TreeSet<Integer>>>> it = index.entrySet().iterator();
while(it.hasNext()) {
Entry<String, TreeMap<String, TreeSet<Integer>>> entry = (Entry<String, TreeMap<String, TreeSet<Integer>>>) it.next();
String word = (String) entry.getKey();
writer.write(indent(1));
writer.write("\"" + word + "\": {");
writer.write(System.lineSeparator());
TreeMap<String, TreeSet<Integer>> nestedMap = (TreeMap<String, TreeSet<Integer>>) entry.getValue();
nestedMapWriter(nestedMap, writer);
writer.write(System.lineSeparator());
writer.write(indent(1));
writer.write("}");
if(it.hasNext()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
writer.write("}");
writer.flush();
}
}
/**
* Used to write information from the nested map
* to the output JSON file.
*
* @param TreeMap that maps a String to a TreeSet
* of Integers; the nested map in my
* InvertedIndex
* @param BufferedWriter to write to the output file
*/
public static void nestedMapWriter(TreeMap<String, TreeSet<Integer>> nestedMap, BufferedWriter writer) throws IOException {
Iterator<Entry<String, TreeSet<Integer>>> it = nestedMap.entrySet().iterator();
while(it.hasNext()) {
Entry<String, TreeSet<Integer>> entry2 = it.next();
String file = entry2.getKey().toString();
TreeSet<Integer> positions = entry2.getValue();
writer.write(indent(2));
writer.write("\"" + file + "\": [");
writer.write(System.lineSeparator());
writer.write(indent(3));
nestedSetWriter(positions, writer);
writer.write(System.lineSeparator());
writer.write(indent(2));
writer.write("]");
if(it.hasNext()) {
writer.write(",");
writer.write(System.lineSeparator());
}
}
}
/**
* Used to write the positions for a given path.
*
* @param TreeSet of Integers that will be written
* @param BufferedWriter to write to the output file
*/
public static void nestedSetWriter(TreeSet<Integer> positions, BufferedWriter writer) throws IOException {
Iterator<Integer> it = positions.iterator();
while(it.hasNext()) {
writer.write(it.next().toString());
if(it.hasNext()) {
writer.write(",");
writer.write(System.lineSeparator());
}
writer.write(indent(3));
}
}
/**
* Used to write the search results to the
* provided output path.
*
* @param QueryHelper object that contains the
* results of searching for the query
* @param output path to write to
*/
public static void writeResults(TreeMap<String, ArrayList<SearchResult>> results, Path path) throws IOException {
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write("[");
writer.write(System.lineSeparator());
Iterator<Entry<String, ArrayList<SearchResult>>> iterator = results.entrySet().iterator();
while(iterator.hasNext()) {
writer.write(indent(1));
writer.write("{");
writer.write(System.lineSeparator());
writer.write(indent(2));
Entry<String, ArrayList<SearchResult>> entry = iterator.next();
String query = entry.getKey().toString();
writer.write("\"queries\": " + "\"" + query + "\",");
writer.write(System.lineSeparator());
writer.write(indent(2));
writer.write("\"results\": [");
writer.write(System.lineSeparator());
ArrayList<SearchResult> resultObjects = entry.getValue();
writeAdditional(resultObjects, writer);
writer.write(indent(2));
writer.write("]");
writer.write(System.lineSeparator());
writer.write(indent(1));
writer.write("}");
if(iterator.hasNext()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
writer.write("]");
writer.flush();
}
}
/**
* Used to iterate through the ArrayList of
* SearchResults, and then outputting them
* to the JSON file using the BufferedWriter.
*
* @param ArrayList of SearchResults
* @param BufferedWriter for writing results
*/
public static void writeAdditional(ArrayList<SearchResult> resultObjects, BufferedWriter writer) throws IOException {
int i = 0;
for(SearchResult obj : resultObjects) {
i++;
writer.write(indent(3));
writer.write("{");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"where\": \"" + obj.getPath() + "\",");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"count\": " + obj.getCount() + ",");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"index\": " + obj.getIndex());
writer.write(System.lineSeparator());
writer.write(indent(3));
writer.write("}");
if(i < resultObjects.size()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
}
/**
* This function was provided by Sophie
* from the JSONWriter homework assignment.
* It simply returns a String representation
* of a certain number of indents.
* @param int (for the number of indents)
*/
public static String indent(int times) {
char[] tabs = new char[times];
Arrays.fill(tabs, '\t');
return String.valueOf(tabs);
}
}
|
UTF-8
|
Java
| 6,081 |
java
|
JSONWriter.java
|
Java
|
[
{
"context": "hie's indent function\n * in this class.\n * @author mitchellmcpartland\n */\npublic class JSONWriter {\n\n\t/**\n\t * Used to w",
"end": 456,
"score": 0.9988017678260803,
"start": 438,
"tag": "USERNAME",
"value": "mitchellmcpartland"
},
{
"context": ");\n\t\t}\n\t}\n\t\n\t/**\n\t * This function was provided by Sophie\n\t * from the JSONWriter homework assignment.\n\t * ",
"end": 5768,
"score": 0.9958646297454834,
"start": 5762,
"tag": "NAME",
"value": "Sophie"
}
] | null |
[] |
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Map.Entry;
/**
* This class is used to write to the JSON
* file. I also put Sophie's indent function
* in this class.
* @author mitchellmcpartland
*/
public class JSONWriter {
/**
* Used to write to the output JSON file.
*
* @param InvertedIndex to read
* @param output Path to write the JSON file to
*/
public static void writeJSON(TreeMap<String, TreeMap<String, TreeSet<Integer>>> index, Path path) throws IOException {
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write("{");
writer.write(System.lineSeparator());
Iterator<Entry<String, TreeMap<String, TreeSet<Integer>>>> it = index.entrySet().iterator();
while(it.hasNext()) {
Entry<String, TreeMap<String, TreeSet<Integer>>> entry = (Entry<String, TreeMap<String, TreeSet<Integer>>>) it.next();
String word = (String) entry.getKey();
writer.write(indent(1));
writer.write("\"" + word + "\": {");
writer.write(System.lineSeparator());
TreeMap<String, TreeSet<Integer>> nestedMap = (TreeMap<String, TreeSet<Integer>>) entry.getValue();
nestedMapWriter(nestedMap, writer);
writer.write(System.lineSeparator());
writer.write(indent(1));
writer.write("}");
if(it.hasNext()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
writer.write("}");
writer.flush();
}
}
/**
* Used to write information from the nested map
* to the output JSON file.
*
* @param TreeMap that maps a String to a TreeSet
* of Integers; the nested map in my
* InvertedIndex
* @param BufferedWriter to write to the output file
*/
public static void nestedMapWriter(TreeMap<String, TreeSet<Integer>> nestedMap, BufferedWriter writer) throws IOException {
Iterator<Entry<String, TreeSet<Integer>>> it = nestedMap.entrySet().iterator();
while(it.hasNext()) {
Entry<String, TreeSet<Integer>> entry2 = it.next();
String file = entry2.getKey().toString();
TreeSet<Integer> positions = entry2.getValue();
writer.write(indent(2));
writer.write("\"" + file + "\": [");
writer.write(System.lineSeparator());
writer.write(indent(3));
nestedSetWriter(positions, writer);
writer.write(System.lineSeparator());
writer.write(indent(2));
writer.write("]");
if(it.hasNext()) {
writer.write(",");
writer.write(System.lineSeparator());
}
}
}
/**
* Used to write the positions for a given path.
*
* @param TreeSet of Integers that will be written
* @param BufferedWriter to write to the output file
*/
public static void nestedSetWriter(TreeSet<Integer> positions, BufferedWriter writer) throws IOException {
Iterator<Integer> it = positions.iterator();
while(it.hasNext()) {
writer.write(it.next().toString());
if(it.hasNext()) {
writer.write(",");
writer.write(System.lineSeparator());
}
writer.write(indent(3));
}
}
/**
* Used to write the search results to the
* provided output path.
*
* @param QueryHelper object that contains the
* results of searching for the query
* @param output path to write to
*/
public static void writeResults(TreeMap<String, ArrayList<SearchResult>> results, Path path) throws IOException {
try(BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write("[");
writer.write(System.lineSeparator());
Iterator<Entry<String, ArrayList<SearchResult>>> iterator = results.entrySet().iterator();
while(iterator.hasNext()) {
writer.write(indent(1));
writer.write("{");
writer.write(System.lineSeparator());
writer.write(indent(2));
Entry<String, ArrayList<SearchResult>> entry = iterator.next();
String query = entry.getKey().toString();
writer.write("\"queries\": " + "\"" + query + "\",");
writer.write(System.lineSeparator());
writer.write(indent(2));
writer.write("\"results\": [");
writer.write(System.lineSeparator());
ArrayList<SearchResult> resultObjects = entry.getValue();
writeAdditional(resultObjects, writer);
writer.write(indent(2));
writer.write("]");
writer.write(System.lineSeparator());
writer.write(indent(1));
writer.write("}");
if(iterator.hasNext()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
writer.write("]");
writer.flush();
}
}
/**
* Used to iterate through the ArrayList of
* SearchResults, and then outputting them
* to the JSON file using the BufferedWriter.
*
* @param ArrayList of SearchResults
* @param BufferedWriter for writing results
*/
public static void writeAdditional(ArrayList<SearchResult> resultObjects, BufferedWriter writer) throws IOException {
int i = 0;
for(SearchResult obj : resultObjects) {
i++;
writer.write(indent(3));
writer.write("{");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"where\": \"" + obj.getPath() + "\",");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"count\": " + obj.getCount() + ",");
writer.write(System.lineSeparator());
writer.write(indent(4));
writer.write("\"index\": " + obj.getIndex());
writer.write(System.lineSeparator());
writer.write(indent(3));
writer.write("}");
if(i < resultObjects.size()) {
writer.write(",");
}
writer.write(System.lineSeparator());
}
}
/**
* This function was provided by Sophie
* from the JSONWriter homework assignment.
* It simply returns a String representation
* of a certain number of indents.
* @param int (for the number of indents)
*/
public static String indent(int times) {
char[] tabs = new char[times];
Arrays.fill(tabs, '\t');
return String.valueOf(tabs);
}
}
| 6,081 | 0.671436 | 0.667818 | 189 | 31.179893 | 25.208956 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.862434 | false | false |
10
|
ca31fd4e6c86f8d0ad4fe8296247a16bfd6ff256
| 4,303,557,282,155 |
4180f974f68c3a44c957a9c3714b308a80fb7697
|
/nbdemetra-sa/src/main/java/ec/nbdemetra/x13/descriptors/ArimaSpecUI.java
|
7636b0e1f6015071a52b5c89f563d1c7dfa33818
|
[] |
no_license
|
MFatihTuzen/jdemetra-app
|
https://github.com/MFatihTuzen/jdemetra-app
|
7c3594601a33b032416db78e92a8212822d147b8
|
d6304de4c65e77e71195e939e5aceba8f1b42830
|
refs/heads/master
| 2022-09-04T07:53:55.595000 | 2015-01-12T09:01:53 | 2015-01-12T09:01:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ec.nbdemetra.x13.descriptors;
import ec.tstoolkit.Parameter;
import ec.tstoolkit.descriptors.EnhancedPropertyDescriptor;
import ec.tstoolkit.modelling.arima.x13.ArimaSpec;
import ec.tstoolkit.modelling.arima.x13.AutoModelSpec;
import ec.tstoolkit.modelling.arima.x13.RegArimaSpecification;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Kristof Bayens
*/
public class ArimaSpecUI extends BaseRegArimaSpecUI {
ArimaSpecUI(RegArimaSpecification spec, boolean ro) {
super(spec, ro);
}
private ArimaSpec arima() {
return core.getArima();
}
private AutoModelSpec ami() {
return core.getAutoModel();
}
@Override
public String toString() {
if (core == null) {
return "";
}
else {
StringBuilder builder = new StringBuilder();
builder.append('(').append(core.getArima().getP()).append(", ").append(core.getArima().getD()).append(", ").append(core.getArima().getQ()).append(")(").append(core.getArima().getBP()).append(", ").append(core.getArima().getBD()).append(", ").append(core.getArima().getBQ()).append(')');
return builder.toString();
}
}
@Override
public List<EnhancedPropertyDescriptor> getProperties() {
ArrayList<EnhancedPropertyDescriptor> descs = new ArrayList<>();
EnhancedPropertyDescriptor desc = enabledDesc();
if (desc != null) {
descs.add(desc);
}
desc = accdefDesc();
if (desc != null) {
descs.add(desc);
}
// desc = checkmuDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = ljungboxDesc();
if (desc != null) {
descs.add(desc);
}
// desc = mixedDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = armaDesc();
if (desc != null) {
descs.add(desc);
}
desc = balancedDesc();
if (desc != null) {
descs.add(desc);
}
desc = cancelDesc();
if (desc != null) {
descs.add(desc);
}
desc = furlimitDesc();
if (desc != null) {
descs.add(desc);
}
// desc = hrinitialDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = iurlimitDesc();
if (desc != null) {
descs.add(desc);
}
desc = reducecvDesc();
if (desc != null) {
descs.add(desc);
}
// desc = reduceseDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = urlimitDesc();
if (desc != null) {
descs.add(desc);
}
desc = meanDesc();
if (desc != null) {
descs.add(desc);
}
desc = pDesc();
if (desc != null) {
descs.add(desc);
}
desc = phiDesc();
if (desc != null) {
descs.add(desc);
}
desc = dDesc();
if (desc != null) {
descs.add(desc);
}
desc = qDesc();
if (desc != null) {
descs.add(desc);
}
desc = thetaDesc();
if (desc != null) {
descs.add(desc);
}
desc = bpDesc();
if (desc != null) {
descs.add(desc);
}
desc = bphiDesc();
if (desc != null) {
descs.add(desc);
}
desc = bdDesc();
if (desc != null) {
descs.add(desc);
}
desc = bqDesc();
if (desc != null) {
descs.add(desc);
}
desc = bthetaDesc();
if (desc != null) {
descs.add(desc);
}
return descs;
}
@Override
public String getDisplayName() {
return "Arima";
}
public int getP() {
return arima().getP();
}
public void setP(int value) {
arima().setP(value);
}
public int getD() {
return arima().getD();
}
public void setD(int value) {
arima().setD(value);
}
public int getQ() {
return arima().getQ();
}
public void setQ(int value) {
arima().setQ(value);
}
public int getBP() {
ArimaSpec spec = arima();
return arima().getBP();
}
public void setBP(int value) {
arima().setBP(value);
}
public int getBD() {
return arima().getBD();
}
public void setBD(int value) {
arima().setBD(value);
}
public int getBQ() {
return arima().getBQ();
}
public void setBQ(int value) {
arima().setBQ(value);
}
public Parameter[] getPhi() {
return arima().getPhi();
}
public void setPhi(Parameter[] value) {
arima().setPhi(value);
}
public Parameter[] getTheta() {
return arima().getTheta();
}
public void setTheta(Parameter[] value) {
arima().setTheta(value);
}
public Parameter[] getBPhi() {
return arima().getBPhi();
}
public void setBPhi(Parameter[] value) {
arima().setBPhi(value);
}
public Parameter[] getBTheta() {
return arima().getBTheta();
}
public void setBTheta(Parameter[] value) {
arima().setBTheta(value);
}
public boolean isMean() {
return arima().isMean();
}
public void setMean(boolean value) {
arima().setMean(value);
}
private EnhancedPropertyDescriptor pDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("P", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, P_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(P_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor dDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("D", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, D_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(D_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor qDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Q", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, Q_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(Q_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bpDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BP", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BP_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BP_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bdDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BD", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BD_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BD_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bqDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BQ", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BQ_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BQ_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor phiDesc() {
if (core.isUsingAutoModel() || arima().getP() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Phi", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, PHI_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("phi");
desc.setShortDescription(PHI_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor thetaDesc() {
if (core.isUsingAutoModel() || arima().getQ() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Theta", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, THETA_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("theta");
desc.setShortDescription(THETA_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bphiDesc() {
if (core.isUsingAutoModel() || arima().getBP() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BPhi", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BPHI_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("bphi");
desc.setShortDescription(BPHI_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bthetaDesc() {
if (core.isUsingAutoModel() || arima().getBQ() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BTheta", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BTHETA_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("btheta");
desc.setShortDescription(BTHETA_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor meanDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Mean", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, MEAN_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(MEAN_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
public boolean isEnabled() {
return ami().isEnabled();
}
public void setEnabled(boolean value) {
ami().setEnabled(value);
}
public boolean isAcceptDefault() {
return ami().isAcceptDefault();
}
public void setAcceptDefault(boolean value) {
ami().setAcceptDefault(value);
}
public boolean isBalanced() {
return ami().isBalanced();
}
public void setBalanced(boolean value) {
ami().setBalanced(value);
}
public boolean isMixed() {
return ami().isMixed();
}
public void setMixed(boolean value) {
ami().setMixed(value);
}
public boolean isCheckMu() {
return ami().isCheckMu();
}
public void setCheckMu(boolean value) {
ami().setCheckMu(value);
}
public boolean isHannanRissannen() {
return ami().isHannanRissannen();
}
public void setHannanRissannen(boolean value) {
ami().setHannanRissanen(value);
}
public double getUbFinal() {
return ami().getUnitRootLimit();
}
public void setUbFinal(double value) {
ami().setUnitRootLimit(value);
}
public double getUb1() {
return ami().getInitialUnitRootLimit();
}
public void setUb1(double value) {
ami().setInitialUnitRootLimit(value);
}
public double getUb2() {
return ami().getFinalUnitRootLimit();
}
public void setUb2(double value) {
ami().setFinalUnitRootLimit(value);
}
public double getCancel() {
return ami().getCancelationLimit();
}
public void setCancel(double value) {
ami().setCancelationLimit(value);
}
public double getPcr() {
return ami().getLjungBoxLimit();
}
public void setPcr(double value) {
ami().setLjungBoxLimit(value);
}
public double getTsig() {
return ami().getArmaSignificance();
}
public void setTsig(double value) {
ami().setArmaSignificance(value);
}
public double getPredCV() {
return ami().getPercentReductionCV();
}
public void setPredCV(double value) {
ami().setPercentReductionCV(value);
}
public double getPredSE() {
return ami().getPercentRSE();
}
public void setPredSE(double value) {
ami().setPercentRSE(value);
}
private EnhancedPropertyDescriptor enabledDesc() {
try {
PropertyDescriptor desc = new PropertyDescriptor("Enabled", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ENABLED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ENABLED_NAME);
desc.setShortDescription(ENABLED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor accdefDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("AcceptDefault", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ACCDEF_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ACCDEF_NAME);
desc.setShortDescription(ACCDEF_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor balancedDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Balanced", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BALANCED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(BALANCED_NAME);
desc.setShortDescription(BALANCED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor mixedDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Mixed", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, MIXED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(MIXED_NAME);
desc.setShortDescription(MIXED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor checkmuDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("CheckMu", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, CHECKMU_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(CHECKMU_NAME);
desc.setShortDescription(CHECKMU_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor hrinitialDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("HannanRissannen", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, HRINITIAL_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(HRINITIAL_NAME);
desc.setShortDescription(HRINITIAL_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor urlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("UbFinal", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, URLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(URLIMIT_NAME);
desc.setShortDescription(URLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor iurlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Ub1", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, IURLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(IURLIMIT_NAME);
desc.setShortDescription(IURLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor furlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Ub2", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, FURLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(FURLIMIT_NAME);
desc.setShortDescription(FURLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor cancelDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Cancel", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, CANCELLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(CANCELLIMIT_NAME);
desc.setShortDescription(CANCELLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor ljungboxDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Pcr", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, LJUNGBOXLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(LJUNGBOXLIMIT_NAME);
desc.setShortDescription(LJUNGBOXLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor armaDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Tsig", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ARMALIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ARMALIMIT_NAME);
desc.setShortDescription(ARMALIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor reducecvDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("PredCV", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, REDUCECV_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(REDUCECV_NAME);
desc.setShortDescription(REDUCECV_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor reduceseDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("PredSE", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, REDUCESE_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(REDUCESE_NAME);
desc.setShortDescription(REDUCESE_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private static final int P_ID = 20, D_ID = 21, Q_ID = 22, BP_ID = 23, BD_ID = 24, BQ_ID = 25,
PHI_ID = 26, THETA_ID = 27, BPHI_ID = 28, BTHETA_ID = 29, MEAN_ID = 30;
private static final int ENABLED_ID = 0, ACCDEF_ID = 1, BALANCED_ID = 2, MIXED_ID = 3,
CHECKMU_ID = 4, HRINITIAL_ID = 5, URLIMIT_ID = 6, IURLIMIT_ID = 7, FURLIMIT_ID = 8,
CANCELLIMIT_ID = 9, LJUNGBOXLIMIT_ID = 10, ARMALIMIT_ID = 11, REDUCECV_ID = 12,
REDUCESE_ID = 13;
private static final String P_DESC = "[p] Regular auto-regresssive order",
D_DESC = "[d] Regular differencing order",
Q_DESC = "[q] Regular moving average order",
BP_DESC = "[bp] Seasonal auto-regressive order",
BD_DESC = "[bd] Seasonal differencing order",
BQ_DESC = "[bq] Seasonal moving average order",
PHI_DESC = "[phi, jpr] Coefficients of the regular auto-regressive polynomial (true signs)",
THETA_DESC = "[th, jqr] Coefficients of the regular moving average polynomial (true signs)",
BPHI_DESC = "[bphi, jqr] Coefficients of the seasonal auto-regressive polynomial (true signs)",
BTHETA_DESC = "[bth, jqs] Coefficients of the seasonal moving average polynomial (true signs)",
MEAN_DESC = "[imean] Mean correction";
private static final String ENABLED_NAME = "Automatic",
ACCDEF_NAME = "Accept Default",
BALANCED_NAME = "Balanced",
MIXED_NAME = "Mixed",
CHECKMU_NAME = "CheckMu",
HRINITIAL_NAME = "HR initial",
URLIMIT_NAME = "Unit root limit",
IURLIMIT_NAME = "Initial unit root limit",
FURLIMIT_NAME = "Final unit root limit",
CANCELLIMIT_NAME = "Cancelation limit",
LJUNGBOXLIMIT_NAME = "LjungBox limit",
ARMALIMIT_NAME = "ArmaLimit",
REDUCECV_NAME = "Reduce CV",
REDUCESE_NAME = "Reduce SE";
private static final String ENABLED_DESC = "Enables automatic modelling.",
ACCDEF_DESC = "[acceptdefault] Controls whether the default model is acceptable.",
BALANCED_DESC = "[balanced] Controls whether the automatic model procedure will have a preference for balanced models.",
MIXED_DESC = "[mixed] Controls whether ARIMA models with nonseasonal AR and MA terms or seasonal AR and MA terms will be considered in the automatic model identification procedure.",
CHECKMU_DESC = "[checkmu] Controls whether the automatic model selection procedure will check for the significance of a constant term.",
HRINITIAL_DESC = "[hrinitial] Controls whether Hannan-Rissanen estimation is done before exact maximum likelihood estimation to provide initial values.",
URLIMIT_DESC = "[urfinal] Unit root limit for final model. Should be > 1.",
IURLIMIT_DESC = "Initial unit root limit in the automatic differencing procedure.",
FURLIMIT_DESC = "Final unit root limit in the automatic differencing procedure.",
CANCELLIMIT_DESC = "Cancelation limit for AR and MA roots.",
LJUNGBOXLIMIT_DESC = "[ljungboxlimit] Ljung-Box Q statistic limit for the acceptance of a model.",
ARMALIMIT_DESC = "[armalimit] Threshold value for t-statistics of ARMA coefficients used for final test of model parsimony.",
REDUCECV_DESC = "[reducecv] The percentage by which the outlier critical value will be reduced when an identified model is found to have a Ljung-Box Q statistic with an unacceptable confidence coefficient.",
REDUCESE_DESC = "Percent reduction of SE.";
}
|
UTF-8
|
Java
| 28,674 |
java
|
ArimaSpecUI.java
|
Java
|
[
{
"context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author Kristof Bayens\r\n */\r\npublic class ArimaSpecUI extends BaseRegArima",
"end": 581,
"score": 0.9988828301429749,
"start": 567,
"tag": "NAME",
"value": "Kristof Bayens"
},
{
"context": "PropertyDescriptor desc = new PropertyDescriptor(\"HannanRissannen\", this.getClass());\r\n EnhancedProperty",
"end": 19018,
"score": 0.8526147603988647,
"start": 19003,
"tag": "NAME",
"value": "HannanRissannen"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ec.nbdemetra.x13.descriptors;
import ec.tstoolkit.Parameter;
import ec.tstoolkit.descriptors.EnhancedPropertyDescriptor;
import ec.tstoolkit.modelling.arima.x13.ArimaSpec;
import ec.tstoolkit.modelling.arima.x13.AutoModelSpec;
import ec.tstoolkit.modelling.arima.x13.RegArimaSpecification;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author <NAME>
*/
public class ArimaSpecUI extends BaseRegArimaSpecUI {
ArimaSpecUI(RegArimaSpecification spec, boolean ro) {
super(spec, ro);
}
private ArimaSpec arima() {
return core.getArima();
}
private AutoModelSpec ami() {
return core.getAutoModel();
}
@Override
public String toString() {
if (core == null) {
return "";
}
else {
StringBuilder builder = new StringBuilder();
builder.append('(').append(core.getArima().getP()).append(", ").append(core.getArima().getD()).append(", ").append(core.getArima().getQ()).append(")(").append(core.getArima().getBP()).append(", ").append(core.getArima().getBD()).append(", ").append(core.getArima().getBQ()).append(')');
return builder.toString();
}
}
@Override
public List<EnhancedPropertyDescriptor> getProperties() {
ArrayList<EnhancedPropertyDescriptor> descs = new ArrayList<>();
EnhancedPropertyDescriptor desc = enabledDesc();
if (desc != null) {
descs.add(desc);
}
desc = accdefDesc();
if (desc != null) {
descs.add(desc);
}
// desc = checkmuDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = ljungboxDesc();
if (desc != null) {
descs.add(desc);
}
// desc = mixedDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = armaDesc();
if (desc != null) {
descs.add(desc);
}
desc = balancedDesc();
if (desc != null) {
descs.add(desc);
}
desc = cancelDesc();
if (desc != null) {
descs.add(desc);
}
desc = furlimitDesc();
if (desc != null) {
descs.add(desc);
}
// desc = hrinitialDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = iurlimitDesc();
if (desc != null) {
descs.add(desc);
}
desc = reducecvDesc();
if (desc != null) {
descs.add(desc);
}
// desc = reduceseDesc();
// if (desc != null) {
// descs.add(desc);
// }
desc = urlimitDesc();
if (desc != null) {
descs.add(desc);
}
desc = meanDesc();
if (desc != null) {
descs.add(desc);
}
desc = pDesc();
if (desc != null) {
descs.add(desc);
}
desc = phiDesc();
if (desc != null) {
descs.add(desc);
}
desc = dDesc();
if (desc != null) {
descs.add(desc);
}
desc = qDesc();
if (desc != null) {
descs.add(desc);
}
desc = thetaDesc();
if (desc != null) {
descs.add(desc);
}
desc = bpDesc();
if (desc != null) {
descs.add(desc);
}
desc = bphiDesc();
if (desc != null) {
descs.add(desc);
}
desc = bdDesc();
if (desc != null) {
descs.add(desc);
}
desc = bqDesc();
if (desc != null) {
descs.add(desc);
}
desc = bthetaDesc();
if (desc != null) {
descs.add(desc);
}
return descs;
}
@Override
public String getDisplayName() {
return "Arima";
}
public int getP() {
return arima().getP();
}
public void setP(int value) {
arima().setP(value);
}
public int getD() {
return arima().getD();
}
public void setD(int value) {
arima().setD(value);
}
public int getQ() {
return arima().getQ();
}
public void setQ(int value) {
arima().setQ(value);
}
public int getBP() {
ArimaSpec spec = arima();
return arima().getBP();
}
public void setBP(int value) {
arima().setBP(value);
}
public int getBD() {
return arima().getBD();
}
public void setBD(int value) {
arima().setBD(value);
}
public int getBQ() {
return arima().getBQ();
}
public void setBQ(int value) {
arima().setBQ(value);
}
public Parameter[] getPhi() {
return arima().getPhi();
}
public void setPhi(Parameter[] value) {
arima().setPhi(value);
}
public Parameter[] getTheta() {
return arima().getTheta();
}
public void setTheta(Parameter[] value) {
arima().setTheta(value);
}
public Parameter[] getBPhi() {
return arima().getBPhi();
}
public void setBPhi(Parameter[] value) {
arima().setBPhi(value);
}
public Parameter[] getBTheta() {
return arima().getBTheta();
}
public void setBTheta(Parameter[] value) {
arima().setBTheta(value);
}
public boolean isMean() {
return arima().isMean();
}
public void setMean(boolean value) {
arima().setMean(value);
}
private EnhancedPropertyDescriptor pDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("P", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, P_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(P_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor dDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("D", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, D_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(D_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor qDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Q", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, Q_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(Q_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bpDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BP", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BP_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BP_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bdDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BD", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BD_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BD_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bqDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BQ", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BQ_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(BQ_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor phiDesc() {
if (core.isUsingAutoModel() || arima().getP() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Phi", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, PHI_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("phi");
desc.setShortDescription(PHI_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor thetaDesc() {
if (core.isUsingAutoModel() || arima().getQ() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Theta", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, THETA_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("theta");
desc.setShortDescription(THETA_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bphiDesc() {
if (core.isUsingAutoModel() || arima().getBP() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BPhi", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BPHI_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("bphi");
desc.setShortDescription(BPHI_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor bthetaDesc() {
if (core.isUsingAutoModel() || arima().getBQ() == 0) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("BTheta", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BTHETA_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName("btheta");
desc.setShortDescription(BTHETA_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor meanDesc() {
if (core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Mean", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, MEAN_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setShortDescription(MEAN_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
public boolean isEnabled() {
return ami().isEnabled();
}
public void setEnabled(boolean value) {
ami().setEnabled(value);
}
public boolean isAcceptDefault() {
return ami().isAcceptDefault();
}
public void setAcceptDefault(boolean value) {
ami().setAcceptDefault(value);
}
public boolean isBalanced() {
return ami().isBalanced();
}
public void setBalanced(boolean value) {
ami().setBalanced(value);
}
public boolean isMixed() {
return ami().isMixed();
}
public void setMixed(boolean value) {
ami().setMixed(value);
}
public boolean isCheckMu() {
return ami().isCheckMu();
}
public void setCheckMu(boolean value) {
ami().setCheckMu(value);
}
public boolean isHannanRissannen() {
return ami().isHannanRissannen();
}
public void setHannanRissannen(boolean value) {
ami().setHannanRissanen(value);
}
public double getUbFinal() {
return ami().getUnitRootLimit();
}
public void setUbFinal(double value) {
ami().setUnitRootLimit(value);
}
public double getUb1() {
return ami().getInitialUnitRootLimit();
}
public void setUb1(double value) {
ami().setInitialUnitRootLimit(value);
}
public double getUb2() {
return ami().getFinalUnitRootLimit();
}
public void setUb2(double value) {
ami().setFinalUnitRootLimit(value);
}
public double getCancel() {
return ami().getCancelationLimit();
}
public void setCancel(double value) {
ami().setCancelationLimit(value);
}
public double getPcr() {
return ami().getLjungBoxLimit();
}
public void setPcr(double value) {
ami().setLjungBoxLimit(value);
}
public double getTsig() {
return ami().getArmaSignificance();
}
public void setTsig(double value) {
ami().setArmaSignificance(value);
}
public double getPredCV() {
return ami().getPercentReductionCV();
}
public void setPredCV(double value) {
ami().setPercentReductionCV(value);
}
public double getPredSE() {
return ami().getPercentRSE();
}
public void setPredSE(double value) {
ami().setPercentRSE(value);
}
private EnhancedPropertyDescriptor enabledDesc() {
try {
PropertyDescriptor desc = new PropertyDescriptor("Enabled", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ENABLED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ENABLED_NAME);
desc.setShortDescription(ENABLED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor accdefDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("AcceptDefault", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ACCDEF_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ACCDEF_NAME);
desc.setShortDescription(ACCDEF_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor balancedDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Balanced", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, BALANCED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(BALANCED_NAME);
desc.setShortDescription(BALANCED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor mixedDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Mixed", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, MIXED_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(MIXED_NAME);
desc.setShortDescription(MIXED_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor checkmuDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("CheckMu", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, CHECKMU_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(CHECKMU_NAME);
desc.setShortDescription(CHECKMU_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor hrinitialDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("HannanRissannen", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, HRINITIAL_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(HRINITIAL_NAME);
desc.setShortDescription(HRINITIAL_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor urlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("UbFinal", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, URLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(URLIMIT_NAME);
desc.setShortDescription(URLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor iurlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Ub1", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, IURLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(IURLIMIT_NAME);
desc.setShortDescription(IURLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor furlimitDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Ub2", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, FURLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(FURLIMIT_NAME);
desc.setShortDescription(FURLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor cancelDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Cancel", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, CANCELLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(CANCELLIMIT_NAME);
desc.setShortDescription(CANCELLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor ljungboxDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Pcr", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, LJUNGBOXLIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(LJUNGBOXLIMIT_NAME);
desc.setShortDescription(LJUNGBOXLIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor armaDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("Tsig", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, ARMALIMIT_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(ARMALIMIT_NAME);
desc.setShortDescription(ARMALIMIT_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor reducecvDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("PredCV", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, REDUCECV_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(REDUCECV_NAME);
desc.setShortDescription(REDUCECV_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private EnhancedPropertyDescriptor reduceseDesc() {
if (!core.isUsingAutoModel()) {
return null;
}
try {
PropertyDescriptor desc = new PropertyDescriptor("PredSE", this.getClass());
EnhancedPropertyDescriptor edesc = new EnhancedPropertyDescriptor(desc, REDUCESE_ID);
edesc.setRefreshMode(EnhancedPropertyDescriptor.Refresh.All);
desc.setDisplayName(REDUCESE_NAME);
desc.setShortDescription(REDUCESE_DESC);
edesc.setReadOnly(ro_);
return edesc;
}
catch (IntrospectionException ex) {
return null;
}
}
private static final int P_ID = 20, D_ID = 21, Q_ID = 22, BP_ID = 23, BD_ID = 24, BQ_ID = 25,
PHI_ID = 26, THETA_ID = 27, BPHI_ID = 28, BTHETA_ID = 29, MEAN_ID = 30;
private static final int ENABLED_ID = 0, ACCDEF_ID = 1, BALANCED_ID = 2, MIXED_ID = 3,
CHECKMU_ID = 4, HRINITIAL_ID = 5, URLIMIT_ID = 6, IURLIMIT_ID = 7, FURLIMIT_ID = 8,
CANCELLIMIT_ID = 9, LJUNGBOXLIMIT_ID = 10, ARMALIMIT_ID = 11, REDUCECV_ID = 12,
REDUCESE_ID = 13;
private static final String P_DESC = "[p] Regular auto-regresssive order",
D_DESC = "[d] Regular differencing order",
Q_DESC = "[q] Regular moving average order",
BP_DESC = "[bp] Seasonal auto-regressive order",
BD_DESC = "[bd] Seasonal differencing order",
BQ_DESC = "[bq] Seasonal moving average order",
PHI_DESC = "[phi, jpr] Coefficients of the regular auto-regressive polynomial (true signs)",
THETA_DESC = "[th, jqr] Coefficients of the regular moving average polynomial (true signs)",
BPHI_DESC = "[bphi, jqr] Coefficients of the seasonal auto-regressive polynomial (true signs)",
BTHETA_DESC = "[bth, jqs] Coefficients of the seasonal moving average polynomial (true signs)",
MEAN_DESC = "[imean] Mean correction";
private static final String ENABLED_NAME = "Automatic",
ACCDEF_NAME = "Accept Default",
BALANCED_NAME = "Balanced",
MIXED_NAME = "Mixed",
CHECKMU_NAME = "CheckMu",
HRINITIAL_NAME = "HR initial",
URLIMIT_NAME = "Unit root limit",
IURLIMIT_NAME = "Initial unit root limit",
FURLIMIT_NAME = "Final unit root limit",
CANCELLIMIT_NAME = "Cancelation limit",
LJUNGBOXLIMIT_NAME = "LjungBox limit",
ARMALIMIT_NAME = "ArmaLimit",
REDUCECV_NAME = "Reduce CV",
REDUCESE_NAME = "Reduce SE";
private static final String ENABLED_DESC = "Enables automatic modelling.",
ACCDEF_DESC = "[acceptdefault] Controls whether the default model is acceptable.",
BALANCED_DESC = "[balanced] Controls whether the automatic model procedure will have a preference for balanced models.",
MIXED_DESC = "[mixed] Controls whether ARIMA models with nonseasonal AR and MA terms or seasonal AR and MA terms will be considered in the automatic model identification procedure.",
CHECKMU_DESC = "[checkmu] Controls whether the automatic model selection procedure will check for the significance of a constant term.",
HRINITIAL_DESC = "[hrinitial] Controls whether Hannan-Rissanen estimation is done before exact maximum likelihood estimation to provide initial values.",
URLIMIT_DESC = "[urfinal] Unit root limit for final model. Should be > 1.",
IURLIMIT_DESC = "Initial unit root limit in the automatic differencing procedure.",
FURLIMIT_DESC = "Final unit root limit in the automatic differencing procedure.",
CANCELLIMIT_DESC = "Cancelation limit for AR and MA roots.",
LJUNGBOXLIMIT_DESC = "[ljungboxlimit] Ljung-Box Q statistic limit for the acceptance of a model.",
ARMALIMIT_DESC = "[armalimit] Threshold value for t-statistics of ARMA coefficients used for final test of model parsimony.",
REDUCECV_DESC = "[reducecv] The percentage by which the outlier critical value will be reduced when an identified model is found to have a Ljung-Box Q statistic with an unacceptable confidence coefficient.",
REDUCESE_DESC = "Percent reduction of SE.";
}
| 28,666 | 0.567936 | 0.565879 | 843 | 32.014236 | 29.534584 | 298 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.559905 | false | false |
10
|
17c149d2695db4dee9dd6792182c8e0dd28f7bed
| 4,303,557,278,837 |
d83474ecad3d3fa255eaf9e010516b1516d9f5d1
|
/src/com/tech/blog/dao/UserDao.java
|
5aaa1eaa9c9e2d0662c05768a4d8533f6f803f27
|
[] |
no_license
|
vikash1702/Techblog
|
https://github.com/vikash1702/Techblog
|
df8bebb266edde12b74067d8f47c9605a10d7cc3
|
c1909c423579e4027c1eb24e9ef2d42b75b679ac
|
refs/heads/master
| 2023-05-24T09:29:40.988000 | 2021-06-11T14:59:13 | 2021-06-11T14:59:13 | 376,060,072 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tech.blog.dao;
import java.sql.*;
import com.tech.blog.entities.User;
import com.tech.blog.helpers.ConnectionProvider;
public class UserDao {
public static String saveUser(User user) {
try {
Connection conn = ConnectionProvider.getConnection();
String query = "insert into user_(name,email,password,gender,about) values(?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,user.getName());
ps.setString(2,user.getEmail());
ps.setString(3,user.getPassword());
ps.setString(4,user.getGender());
ps.setString(5,user.getAbout());
ps.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return "done";
}
public static int updateUser(User user) {
int reffect =0;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "update user_ set name=?,email=?,password=?,gender=?,about=?,picture=? where userid=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,user.getName());
ps.setString(2,user.getEmail());
ps.setString(3,user.getPassword());
ps.setString(4,user.getGender());
ps.setString(5,user.getAbout());
ps.setString(6,user.getPicture());
ps.setInt(7,user.getId());
reffect = ps.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return reffect;
}
public User getUserbyEmail(String email,String password) {
User user = null;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "select * from user_ where email=? and password=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,email);
ps.setString(2,password);
ResultSet rs= ps.executeQuery();
if(rs.next()) {
user = new User();
user.setId(rs.getInt("userid"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
user.setPassword(rs.getString("password"));
user.setGender(rs.getString("gender"));
user.setPicture(rs.getString("picture"));
user.setAbout(rs.getString("about"));
user.setDate(rs.getTimestamp("register_date"));
}
}catch(Exception e) {
e.printStackTrace();
}
return user;
}
public User getUserbyUserId(int userid) {
User user = null;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "select * from user_ where userid = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1,userid);
ResultSet rs= ps.executeQuery();
if(rs.next()) {
user = new User();
user.setId(rs.getInt("userid"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
user.setPassword(rs.getString("password"));
user.setGender(rs.getString("gender"));
user.setPicture(rs.getString("picture"));
user.setAbout(rs.getString("about"));
user.setDate(rs.getTimestamp("register_date"));
}
}catch(Exception e) {
e.printStackTrace();
}
return user;
}
}
|
UTF-8
|
Java
| 3,063 |
java
|
UserDao.java
|
Java
|
[
{
"context": "ing(\"email\"));\n\t\t\t user.setPassword(rs.getString(\"password\"));\n\t\t\t user.setGender(rs.getString(\"gender\"));\n\t",
"end": 1980,
"score": 0.9137587547302246,
"start": 1972,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "mail(rs.getString(\"email\"));\n\t\t\t user.setPassword(rs.getString(\"password\"));\n\t\t\t user.setGender(rs.getString(\"ge",
"end": 2771,
"score": 0.9955081939697266,
"start": 2759,
"tag": "PASSWORD",
"value": "rs.getString"
},
{
"context": "ing(\"email\"));\n\t\t\t user.setPassword(rs.getString(\"password\"));\n\t\t\t user.setGender(rs.getString(\"gender\"));\n\t",
"end": 2781,
"score": 0.9898694157600403,
"start": 2773,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package com.tech.blog.dao;
import java.sql.*;
import com.tech.blog.entities.User;
import com.tech.blog.helpers.ConnectionProvider;
public class UserDao {
public static String saveUser(User user) {
try {
Connection conn = ConnectionProvider.getConnection();
String query = "insert into user_(name,email,password,gender,about) values(?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,user.getName());
ps.setString(2,user.getEmail());
ps.setString(3,user.getPassword());
ps.setString(4,user.getGender());
ps.setString(5,user.getAbout());
ps.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return "done";
}
public static int updateUser(User user) {
int reffect =0;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "update user_ set name=?,email=?,password=?,gender=?,about=?,picture=? where userid=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,user.getName());
ps.setString(2,user.getEmail());
ps.setString(3,user.getPassword());
ps.setString(4,user.getGender());
ps.setString(5,user.getAbout());
ps.setString(6,user.getPicture());
ps.setInt(7,user.getId());
reffect = ps.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}
return reffect;
}
public User getUserbyEmail(String email,String password) {
User user = null;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "select * from user_ where email=? and password=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1,email);
ps.setString(2,password);
ResultSet rs= ps.executeQuery();
if(rs.next()) {
user = new User();
user.setId(rs.getInt("userid"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
user.setPassword(rs.getString("<PASSWORD>"));
user.setGender(rs.getString("gender"));
user.setPicture(rs.getString("picture"));
user.setAbout(rs.getString("about"));
user.setDate(rs.getTimestamp("register_date"));
}
}catch(Exception e) {
e.printStackTrace();
}
return user;
}
public User getUserbyUserId(int userid) {
User user = null;
try {
Connection conn = ConnectionProvider.getConnection();
String query = "select * from user_ where userid = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1,userid);
ResultSet rs= ps.executeQuery();
if(rs.next()) {
user = new User();
user.setId(rs.getInt("userid"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
user.setPassword(<PASSWORD>("<PASSWORD>"));
user.setGender(rs.getString("gender"));
user.setPicture(rs.getString("picture"));
user.setAbout(rs.getString("about"));
user.setDate(rs.getTimestamp("register_date"));
}
}catch(Exception e) {
e.printStackTrace();
}
return user;
}
}
| 3,065 | 0.651975 | 0.646752 | 110 | 26.809092 | 21.002378 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.281818 | false | false |
10
|
84d4c09cdc3b81f870f2ae2c72ea9c99cc510dd9
| 35,794,257,461,396 |
8706c69aa5c513d4686f03451f7319643848c307
|
/android/kikbak/src/com/referredlabs/kikbak/tasks/Task.java
|
58c8999d3d9e6ce6577363b5ac07f3b5af42d009
|
[] |
no_license
|
jsj2008/kikbak
|
https://github.com/jsj2008/kikbak
|
1c2cd38656f07da89f0f01119b5a7dc94a38fd18
|
bd6ae78d5fb8bd94fce37bd6886e13c96ec533b6
|
refs/heads/master
| 2021-01-18T08:10:45.571000 | 2014-08-28T19:54:14 | 2014-08-28T19:54:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.referredlabs.kikbak.tasks;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import com.referredlabs.kikbak.Kikbak;
public abstract class Task implements Future<Void> {
private final FutureTask<Void> mFuture;
private volatile boolean mSuccessful = false;
private volatile Exception mException = null;
private volatile long mCompletionTimeMillis = 0;
private final AtomicBoolean mCancelled = new AtomicBoolean();
public Task() {
final Callable<Void> call = new Callable<Void>() {
@Override
public Void call() throws Exception {
doInBackground();
return null;
}
};
mFuture = new FutureTask<Void>(call) {
protected void done() {
processDone();
};
};
}
private void processDone() {
try {
get();
mSuccessful = true;
} catch (Exception e) {
mException = e;
}
mCompletionTimeMillis = System.currentTimeMillis();
done();
}
protected void done() {
}
public void execute() {
Kikbak.PARALLEL_EXECUTOR.execute(mFuture);
}
protected abstract void doInBackground() throws Exception;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return mCancelled.get();
}
@Override
public boolean isDone() {
return mFuture.isDone();
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
@Override
public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException,
TimeoutException {
return mFuture.get(timeout, unit);
}
public boolean isSuccessful() {
return mSuccessful;
}
public Exception getException() {
return mException;
}
public long getCompletionTimeMillis() {
return mCompletionTimeMillis;
}
}
|
UTF-8
|
Java
| 2,182 |
java
|
Task.java
|
Java
|
[] | null |
[] |
package com.referredlabs.kikbak.tasks;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import com.referredlabs.kikbak.Kikbak;
public abstract class Task implements Future<Void> {
private final FutureTask<Void> mFuture;
private volatile boolean mSuccessful = false;
private volatile Exception mException = null;
private volatile long mCompletionTimeMillis = 0;
private final AtomicBoolean mCancelled = new AtomicBoolean();
public Task() {
final Callable<Void> call = new Callable<Void>() {
@Override
public Void call() throws Exception {
doInBackground();
return null;
}
};
mFuture = new FutureTask<Void>(call) {
protected void done() {
processDone();
};
};
}
private void processDone() {
try {
get();
mSuccessful = true;
} catch (Exception e) {
mException = e;
}
mCompletionTimeMillis = System.currentTimeMillis();
done();
}
protected void done() {
}
public void execute() {
Kikbak.PARALLEL_EXECUTOR.execute(mFuture);
}
protected abstract void doInBackground() throws Exception;
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return mCancelled.get();
}
@Override
public boolean isDone() {
return mFuture.isDone();
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
@Override
public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException,
TimeoutException {
return mFuture.get(timeout, unit);
}
public boolean isSuccessful() {
return mSuccessful;
}
public Exception getException() {
return mException;
}
public long getCompletionTimeMillis() {
return mCompletionTimeMillis;
}
}
| 2,182 | 0.700733 | 0.700275 | 96 | 21.71875 | 20.502897 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.427083 | false | false |
10
|
2a0dc0cbef2567d5ee6dc304d7b2e81b0932f3a7
| 35,794,257,459,807 |
929b6a1e4abaebc267a660ffbfb407cd49a376b5
|
/src/infinity/level/Solid.java
|
527be5430f82f6707791f413a04a69cd65bae5f9
|
[] |
no_license
|
nimwijetunga/Infinity
|
https://github.com/nimwijetunga/Infinity
|
3de3007a020fade172de1a90b0ef71bfd66af2eb
|
b9583cd872be13911822d49515672bb811bf90ea
|
refs/heads/master
| 2020-12-03T03:46:47.389000 | 2017-12-30T00:48:45 | 2017-12-30T00:48:45 | 79,849,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Used to draw all solid tiles
* Solid.java
* @author Umar Syed
*/
package infinity.level;
import java.awt.Graphics;
import java.awt.Rectangle;
import infinity.main.Main;
public class Solid extends Rectangle{
private static final long serialVersionUID = 1L;
private int aniTime =0;
private int aniSpeed = 35;
private int aniFrame = 0;
public int[] id = { -1, -1 };
Main main;
Solid(Main main, Rectangle rect, int id[]) {
setBounds(rect);
this.main = main;
this.id = id;
}
/**
* Changes the animation frame
*/
public void aniUpdate (){
aniTime++;
if(aniTime >= aniSpeed){
aniFrame++;
aniTime = 0;
if(aniFrame > 2){
aniFrame = 0;
}
}
}
/**
* draws all solid tiles
* @param g
*/
public void render(Graphics g){
aniUpdate();
// if it is a water tile draw it depending on what animation frame its on
if (id[0] == 4 && id[1] == 0){
g.drawImage(Tile.terrain, (int) (x - main.getCamOfSetX()), (int) (y - main.getCamOfSetY()), (int) (x + width - main.getCamOfSetX()), (int) (y + height - main.getCamOfSetY()), (id[0]+aniFrame)*Tile.size, id[1]*Tile.size, (id[0]+aniFrame)*Tile.size + Tile.size,id[1]*Tile.size + Tile.size, null);
}
else
g.drawImage(Tile.terrain, (int) (x - main.getCamOfSetX()), (int) (y - main.getCamOfSetY()), (int) (x + width - main.getCamOfSetX()), (int) (y + height - main.getCamOfSetY()), id[0]*Tile.size, id[1]*Tile.size, id[0]*Tile.size + Tile.size,id[1]*Tile.size + Tile.size, null);
//g.drawRect((int) (x - main.getCamOfSetX()), (int) (y - (int)main.getCamOfSetY()), Tile.size, Tile.size);
}
}
|
UTF-8
|
Java
| 1,601 |
java
|
Solid.java
|
Java
|
[
{
"context": "d to draw all solid tiles\n * Solid.java\n * @author Umar Syed\n */\npackage infinity.level;\n\nimport java.awt.Grap",
"end": 70,
"score": 0.9998161196708679,
"start": 61,
"tag": "NAME",
"value": "Umar Syed"
}
] | null |
[] |
/**
* Used to draw all solid tiles
* Solid.java
* @author <NAME>
*/
package infinity.level;
import java.awt.Graphics;
import java.awt.Rectangle;
import infinity.main.Main;
public class Solid extends Rectangle{
private static final long serialVersionUID = 1L;
private int aniTime =0;
private int aniSpeed = 35;
private int aniFrame = 0;
public int[] id = { -1, -1 };
Main main;
Solid(Main main, Rectangle rect, int id[]) {
setBounds(rect);
this.main = main;
this.id = id;
}
/**
* Changes the animation frame
*/
public void aniUpdate (){
aniTime++;
if(aniTime >= aniSpeed){
aniFrame++;
aniTime = 0;
if(aniFrame > 2){
aniFrame = 0;
}
}
}
/**
* draws all solid tiles
* @param g
*/
public void render(Graphics g){
aniUpdate();
// if it is a water tile draw it depending on what animation frame its on
if (id[0] == 4 && id[1] == 0){
g.drawImage(Tile.terrain, (int) (x - main.getCamOfSetX()), (int) (y - main.getCamOfSetY()), (int) (x + width - main.getCamOfSetX()), (int) (y + height - main.getCamOfSetY()), (id[0]+aniFrame)*Tile.size, id[1]*Tile.size, (id[0]+aniFrame)*Tile.size + Tile.size,id[1]*Tile.size + Tile.size, null);
}
else
g.drawImage(Tile.terrain, (int) (x - main.getCamOfSetX()), (int) (y - main.getCamOfSetY()), (int) (x + width - main.getCamOfSetX()), (int) (y + height - main.getCamOfSetY()), id[0]*Tile.size, id[1]*Tile.size, id[0]*Tile.size + Tile.size,id[1]*Tile.size + Tile.size, null);
//g.drawRect((int) (x - main.getCamOfSetX()), (int) (y - (int)main.getCamOfSetY()), Tile.size, Tile.size);
}
}
| 1,598 | 0.632105 | 0.618363 | 58 | 26.603449 | 52.618977 | 297 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.913793 | false | false |
10
|
57ca4159fb79fee33827134a42a5d86b39e88262
| 21,638,045,293,326 |
5ebab325f25a3080ae58c117715469393a8c902c
|
/netty-learning/src/main/java/com/zouxxyy/nio/zerocopy/OldIOClient.java
|
0750f1e2816afc477ac0363b0196a8716a47858e
|
[] |
no_license
|
tju2015zc/java-learning
|
https://github.com/tju2015zc/java-learning
|
6a4f32276df2fe18f3411991ba23b09d6105cd5f
|
63b83e936b0ec5abbe939e7559009201054691ec
|
refs/heads/master
| 2022-04-08T23:52:05.823000 | 2020-02-27T02:47:31 | 2020-02-27T02:47:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zouxxyy.nio.zerocopy;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
/**
* 传统IO客户端
*/
public class OldIOClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 7001);
FileInputStream fileInputStream = new FileInputStream("data/output/channelTest1.txt");
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
byte[] bytes = new byte[4096];
long readCount;
long total = 0;
long startTime = System.currentTimeMillis();
while ((readCount = fileInputStream.read(bytes)) >= 0){
total += readCount;
dataOutputStream.write(bytes, 0, (int) readCount);
}
long endTime = System.currentTimeMillis();
System.out.println("总字节数:" + total + ",耗时:" + (endTime - startTime) + "ms");
dataOutputStream.close();
socket.close();
fileInputStream.close();
}
}
/*
总字节数:2639076,耗时:62ms
总字节数:134761299,耗时:3073ms
*/
|
UTF-8
|
Java
| 1,174 |
java
|
OldIOClient.java
|
Java
|
[] | null |
[] |
package com.zouxxyy.nio.zerocopy;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
/**
* 传统IO客户端
*/
public class OldIOClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 7001);
FileInputStream fileInputStream = new FileInputStream("data/output/channelTest1.txt");
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
byte[] bytes = new byte[4096];
long readCount;
long total = 0;
long startTime = System.currentTimeMillis();
while ((readCount = fileInputStream.read(bytes)) >= 0){
total += readCount;
dataOutputStream.write(bytes, 0, (int) readCount);
}
long endTime = System.currentTimeMillis();
System.out.println("总字节数:" + total + ",耗时:" + (endTime - startTime) + "ms");
dataOutputStream.close();
socket.close();
fileInputStream.close();
}
}
/*
总字节数:2639076,耗时:62ms
总字节数:134761299,耗时:3073ms
*/
| 1,174 | 0.648649 | 0.618018 | 42 | 25.452381 | 26.421675 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false |
10
|
65b073f73e1032108b94de3b1105da47fad78c01
| 16,844,861,769,783 |
26e5337286ed5bf9cc91d0c57f58fefe0654049a
|
/fhl.informatic.traineeship/src/fhl/informatic/traineeship/_04/_01/common/List.java
|
35943b3fd0f507df7e1c3226f1a549e439f6d41e
|
[] |
no_license
|
desertfox94/de.desertfox.uni
|
https://github.com/desertfox94/de.desertfox.uni
|
ea0cfc4a263ac59f83693ce6fb54167cca45ff00
|
1055feb8cd96e37a181b1dbfacc7eb5f629c61a5
|
refs/heads/master
| 2017-10-31T03:07:40.543000 | 2017-10-26T13:17:48 | 2017-10-26T13:17:48 | 70,475,780 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fhl.informatic.traineeship._04._01.common;
import static fhl.informatic.traineeship._04._01.common.TailCall.ret;
import static fhl.informatic.traineeship._04._01.common.TailCall.sus;
import java.util.function.Consumer;
import java.util.function.Function;
import fhl.informatic.traineeship.map.ListMap;
import fhl.informatic.traineeship.map.Map;
public abstract class List<A> {
public abstract A head();
public abstract List<A> tail();
protected abstract List<A> take(int n);
public abstract boolean isEmpty();
public abstract List<A> setHead(A h);
public abstract List<A> reverse();
public abstract List<A> init();
public abstract int length();
public abstract <B> B foldLeft(B identity, Function<B, Function<A, B>> f);
public abstract <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f);
public abstract <B> B foldRight(B identity, Function<A, Function<B, B>> f);
public abstract <B> List<B> map(Function<A, B> f);
public abstract List<A> filter(Function<A, Boolean> f);
public abstract <B> Map<B, List<A>> groupBy(Function<A, B> f);
public abstract Result<A> headOption();
public boolean elem(A a) {
return exists(x -> x.equals(a));
}
public List<A> cons(A a) {
return new Cons<>(a, this);
}
public boolean forAll(Function<A, Boolean> p) {
Function<Boolean, Function<A, Boolean>> f = x -> y -> x && p.apply(y);
return foldLeft(true, false, f)._1;
}
public boolean exists(Function<A, Boolean> p) {
Function<Boolean, Function<A, Boolean>> f = x -> y -> x || p.apply(y);
return foldLeft(false, true, f)._1;
}
public List<A> concat(List<A> list) {
return concat(this, list);
}
public void forEach(Consumer<A> effect) {
List<A> workList = this;
while (!workList.isEmpty()) {
effect.accept(workList.head());
workList = workList.tail();
}
}
/**
* O(n)
*
* @return
*/
public List<A> distinct() {
List<A> result = list();
if (head() == null) {
return result;
}
List<A> remainingElements = this;
A head;
do {
head = remainingElements.head();
if (!result.elem(head)) {
result = result.cons(head);
}
} while (!(remainingElements = remainingElements.tail()).isEmpty());
return result;
}
@SuppressWarnings("rawtypes")
public static final List NIL = new Nil();
private List() {
}
private static class Nil<A> extends List<A> {
private Nil() {
}
public A head() {
throw new IllegalStateException("head called en empty list");
}
public List<A> tail() {
throw new IllegalStateException("tail called en empty list");
}
public boolean isEmpty() {
return true;
}
@Override
public List<A> setHead(A h) {
throw new IllegalStateException("setHead called en empty list");
}
public String toString() {
return "[]";
}
@Override
public List<A> reverse() {
return this;
}
@Override
public List<A> init() {
throw new IllegalStateException("init called on an empty list");
}
@Override
public int length() {
return 0;
}
@Override
public <B> B foldLeft(B identity, Function<B, Function<A, B>> f) {
return identity;
}
@Override
public <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f) {
return new Tuple<>(identity, list());
}
@Override
public <B> B foldRight(B identity, Function<A, Function<B, B>> f) {
return identity;
}
@Override
public <B> List<B> map(Function<A, B> f) {
return list();
}
@Override
public List<A> filter(Function<A, Boolean> f) {
return this;
}
@Override
public Result<A> headOption() {
return Result.empty();
}
@Override
public boolean equals(Object o) {
return o instanceof Nil;
}
@Override
protected List<A> take(int n) {
throw new IllegalStateException("take called on an empty list");
}
@Override
public <B> Map<B, List<A>> groupBy(Function<A, B> f) {
throw new IllegalStateException("Should not be called!");
}
}
private static class Cons<A> extends List<A> {
private final A head;
private final List<A> tail;
private final int length;
private Cons(A head, List<A> tail) {
this.head = head;
this.tail = tail;
this.length = tail.length() + 1;
}
public A head() {
return head;
}
public List<A> tail() {
return tail;
}
public boolean isEmpty() {
return false;
}
@Override
public List<A> setHead(A h) {
return new Cons<>(h, tail());
}
public String toString() {
StringBuilder builder = new StringBuilder();
toString(builder, this);
return "[" + builder.toString() + "]";
}
private void toString(StringBuilder builder, List<A> list) {
if (list.isEmpty()) {
return;
}
toString(builder, list.tail());
if (builder.length() != 0) {
builder.append(", ");
}
builder.append(list.head());
}
@Override
public List<A> reverse() {
return reverse_(list(), this).eval();
}
private TailCall<List<A>> reverse_(List<A> acc, List<A> list) {
return list.isEmpty() ? ret(acc) : sus(() -> reverse_(new Cons<>(list.head(), acc), list.tail()));
}
@Override
public List<A> init() {
return reverse().tail().reverse();
}
@Override
public int length() {
return length;
}
@Override
public <B> B foldLeft(B identity, Function<B, Function<A, B>> f) {
return foldLeft(identity, this, f).eval();
}
private <B> TailCall<B> foldLeft(B acc, List<A> list, Function<B, Function<A, B>> f) {
return list.isEmpty() ? ret(acc) : sus(() -> foldLeft(f.apply(acc).apply(list.head()), list.tail(), f));
}
@Override
public <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f) {
return foldLeft(identity, zero, this, f).eval();
}
private <B> TailCall<Tuple<B, List<A>>> foldLeft(B acc, B zero, List<A> list, Function<B, Function<A, B>> f) {
return list.isEmpty() || acc.equals(zero) ? ret(new Tuple<>(acc, list)) : sus(() -> foldLeft(f.apply(acc).apply(list.head()), zero, list.tail(), f));
}
@Override
public <B> B foldRight(B identity, Function<A, Function<B, B>> f) {
return reverse().foldLeft(identity, x -> y -> f.apply(y).apply(x));
}
@Override
public <B> List<B> map(Function<A, B> f) {
return foldRight(list(), h -> t -> new Cons<>(f.apply(h), t));
}
@Override
public List<A> filter(Function<A, Boolean> f) {
return foldRight(list(), h -> t -> f.apply(h) ? new Cons<>(h, t) : t);
}
@Override
public Result<A> headOption() {
return Result.success(head);
}
@Override
protected List<A> take(int n) {
return this.isEmpty() ? this : n > 0 ? new Cons<>(head(), tail().take(n - 1)) : list();
}
public <B> Map<B, List<A>> groupBy(Function<A, B> f) {
return foldRight(ListMap.empty(), t -> mt -> {
final B k = f.apply(t);
List<A> val = mt.get(k);
if (val == null) {
val = List.list();
}
return mt.put(k, val.cons(t));
});
}
}
@SuppressWarnings("unchecked")
public static <A> List<A> list() {
return NIL;
}
@SafeVarargs
public static <A> List<A> list(A... a) {
List<A> n = list();
for (int i = a.length - 1; i >= 0; i--) {
n = new Cons<>(a[i], n);
}
return n;
}
public static <A, B> B foldRight(List<A> list, B n, Function<A, Function<B, B>> f) {
return list.foldRight(n, f);
}
public static <T> List<T> cons(T t, List<T> list) {
return list.cons(t);
}
public static <A> List<A> concat(List<A> list1, List<A> list2) {
return foldRight(list1, list2, x -> y -> new Cons<>(x, y));
}
}
|
UTF-8
|
Java
| 7,524 |
java
|
List.java
|
Java
|
[] | null |
[] |
package fhl.informatic.traineeship._04._01.common;
import static fhl.informatic.traineeship._04._01.common.TailCall.ret;
import static fhl.informatic.traineeship._04._01.common.TailCall.sus;
import java.util.function.Consumer;
import java.util.function.Function;
import fhl.informatic.traineeship.map.ListMap;
import fhl.informatic.traineeship.map.Map;
public abstract class List<A> {
public abstract A head();
public abstract List<A> tail();
protected abstract List<A> take(int n);
public abstract boolean isEmpty();
public abstract List<A> setHead(A h);
public abstract List<A> reverse();
public abstract List<A> init();
public abstract int length();
public abstract <B> B foldLeft(B identity, Function<B, Function<A, B>> f);
public abstract <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f);
public abstract <B> B foldRight(B identity, Function<A, Function<B, B>> f);
public abstract <B> List<B> map(Function<A, B> f);
public abstract List<A> filter(Function<A, Boolean> f);
public abstract <B> Map<B, List<A>> groupBy(Function<A, B> f);
public abstract Result<A> headOption();
public boolean elem(A a) {
return exists(x -> x.equals(a));
}
public List<A> cons(A a) {
return new Cons<>(a, this);
}
public boolean forAll(Function<A, Boolean> p) {
Function<Boolean, Function<A, Boolean>> f = x -> y -> x && p.apply(y);
return foldLeft(true, false, f)._1;
}
public boolean exists(Function<A, Boolean> p) {
Function<Boolean, Function<A, Boolean>> f = x -> y -> x || p.apply(y);
return foldLeft(false, true, f)._1;
}
public List<A> concat(List<A> list) {
return concat(this, list);
}
public void forEach(Consumer<A> effect) {
List<A> workList = this;
while (!workList.isEmpty()) {
effect.accept(workList.head());
workList = workList.tail();
}
}
/**
* O(n)
*
* @return
*/
public List<A> distinct() {
List<A> result = list();
if (head() == null) {
return result;
}
List<A> remainingElements = this;
A head;
do {
head = remainingElements.head();
if (!result.elem(head)) {
result = result.cons(head);
}
} while (!(remainingElements = remainingElements.tail()).isEmpty());
return result;
}
@SuppressWarnings("rawtypes")
public static final List NIL = new Nil();
private List() {
}
private static class Nil<A> extends List<A> {
private Nil() {
}
public A head() {
throw new IllegalStateException("head called en empty list");
}
public List<A> tail() {
throw new IllegalStateException("tail called en empty list");
}
public boolean isEmpty() {
return true;
}
@Override
public List<A> setHead(A h) {
throw new IllegalStateException("setHead called en empty list");
}
public String toString() {
return "[]";
}
@Override
public List<A> reverse() {
return this;
}
@Override
public List<A> init() {
throw new IllegalStateException("init called on an empty list");
}
@Override
public int length() {
return 0;
}
@Override
public <B> B foldLeft(B identity, Function<B, Function<A, B>> f) {
return identity;
}
@Override
public <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f) {
return new Tuple<>(identity, list());
}
@Override
public <B> B foldRight(B identity, Function<A, Function<B, B>> f) {
return identity;
}
@Override
public <B> List<B> map(Function<A, B> f) {
return list();
}
@Override
public List<A> filter(Function<A, Boolean> f) {
return this;
}
@Override
public Result<A> headOption() {
return Result.empty();
}
@Override
public boolean equals(Object o) {
return o instanceof Nil;
}
@Override
protected List<A> take(int n) {
throw new IllegalStateException("take called on an empty list");
}
@Override
public <B> Map<B, List<A>> groupBy(Function<A, B> f) {
throw new IllegalStateException("Should not be called!");
}
}
private static class Cons<A> extends List<A> {
private final A head;
private final List<A> tail;
private final int length;
private Cons(A head, List<A> tail) {
this.head = head;
this.tail = tail;
this.length = tail.length() + 1;
}
public A head() {
return head;
}
public List<A> tail() {
return tail;
}
public boolean isEmpty() {
return false;
}
@Override
public List<A> setHead(A h) {
return new Cons<>(h, tail());
}
public String toString() {
StringBuilder builder = new StringBuilder();
toString(builder, this);
return "[" + builder.toString() + "]";
}
private void toString(StringBuilder builder, List<A> list) {
if (list.isEmpty()) {
return;
}
toString(builder, list.tail());
if (builder.length() != 0) {
builder.append(", ");
}
builder.append(list.head());
}
@Override
public List<A> reverse() {
return reverse_(list(), this).eval();
}
private TailCall<List<A>> reverse_(List<A> acc, List<A> list) {
return list.isEmpty() ? ret(acc) : sus(() -> reverse_(new Cons<>(list.head(), acc), list.tail()));
}
@Override
public List<A> init() {
return reverse().tail().reverse();
}
@Override
public int length() {
return length;
}
@Override
public <B> B foldLeft(B identity, Function<B, Function<A, B>> f) {
return foldLeft(identity, this, f).eval();
}
private <B> TailCall<B> foldLeft(B acc, List<A> list, Function<B, Function<A, B>> f) {
return list.isEmpty() ? ret(acc) : sus(() -> foldLeft(f.apply(acc).apply(list.head()), list.tail(), f));
}
@Override
public <B> Tuple<B, List<A>> foldLeft(B identity, B zero, Function<B, Function<A, B>> f) {
return foldLeft(identity, zero, this, f).eval();
}
private <B> TailCall<Tuple<B, List<A>>> foldLeft(B acc, B zero, List<A> list, Function<B, Function<A, B>> f) {
return list.isEmpty() || acc.equals(zero) ? ret(new Tuple<>(acc, list)) : sus(() -> foldLeft(f.apply(acc).apply(list.head()), zero, list.tail(), f));
}
@Override
public <B> B foldRight(B identity, Function<A, Function<B, B>> f) {
return reverse().foldLeft(identity, x -> y -> f.apply(y).apply(x));
}
@Override
public <B> List<B> map(Function<A, B> f) {
return foldRight(list(), h -> t -> new Cons<>(f.apply(h), t));
}
@Override
public List<A> filter(Function<A, Boolean> f) {
return foldRight(list(), h -> t -> f.apply(h) ? new Cons<>(h, t) : t);
}
@Override
public Result<A> headOption() {
return Result.success(head);
}
@Override
protected List<A> take(int n) {
return this.isEmpty() ? this : n > 0 ? new Cons<>(head(), tail().take(n - 1)) : list();
}
public <B> Map<B, List<A>> groupBy(Function<A, B> f) {
return foldRight(ListMap.empty(), t -> mt -> {
final B k = f.apply(t);
List<A> val = mt.get(k);
if (val == null) {
val = List.list();
}
return mt.put(k, val.cons(t));
});
}
}
@SuppressWarnings("unchecked")
public static <A> List<A> list() {
return NIL;
}
@SafeVarargs
public static <A> List<A> list(A... a) {
List<A> n = list();
for (int i = a.length - 1; i >= 0; i--) {
n = new Cons<>(a[i], n);
}
return n;
}
public static <A, B> B foldRight(List<A> list, B n, Function<A, Function<B, B>> f) {
return list.foldRight(n, f);
}
public static <T> List<T> cons(T t, List<T> list) {
return list.cons(t);
}
public static <A> List<A> concat(List<A> list1, List<A> list2) {
return foldRight(list1, list2, x -> y -> new Cons<>(x, y));
}
}
| 7,524 | 0.624402 | 0.621079 | 336 | 21.392857 | 24.99596 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.181548 | false | false |
10
|
0bc520d4fb7350f64f40efd86163b4a358a7a533
| 31,430,570,714,794 |
4c4a23b9d50ba77da5f2b48b0b64b9fa1511b37a
|
/studicore/Sebesseg.java
|
a4051c026073c45003e47a11e12d2f118972896b
|
[] |
no_license
|
AronDev/java_gyakorlas
|
https://github.com/AronDev/java_gyakorlas
|
3e86fd48625fdf95dbf794004fecf892bb273eed
|
b4aa05cc3d6e2f954ed099fd279451964adff9a3
|
refs/heads/master
| 2021-08-10T11:50:34.828000 | 2020-05-05T15:35:28 | 2020-05-05T15:35:28 | 173,388,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package java_gyakorlas.studicore;
import java.util.Scanner;
public class Sebesseg {
public static void main(String[] args) {
System.out.print("Hány km/h-val ment? ");
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
if (v < 51) {
System.out.println("Ön szabályosan hajtott.");
} else {
int buntetes;
System.out.print("Az Ön büntetése ");
if (v <= 65) buntetes = 0;
else if (v <= 75) buntetes = 30000;
else if (v <= 85) buntetes = 45000;
else if (v <= 95) buntetes = 60000;
else if (v <= 105) buntetes = 90000;
else if (v <= 115) buntetes = 130000;
else if (v <= 125) buntetes = 200000;
else buntetes = 300000;
System.out.println(buntetes + ",- Ft.");
}
}
}
|
UTF-8
|
Java
| 874 |
java
|
Sebesseg.java
|
Java
|
[] | null |
[] |
package java_gyakorlas.studicore;
import java.util.Scanner;
public class Sebesseg {
public static void main(String[] args) {
System.out.print("Hány km/h-val ment? ");
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
if (v < 51) {
System.out.println("Ön szabályosan hajtott.");
} else {
int buntetes;
System.out.print("Az Ön büntetése ");
if (v <= 65) buntetes = 0;
else if (v <= 75) buntetes = 30000;
else if (v <= 85) buntetes = 45000;
else if (v <= 95) buntetes = 60000;
else if (v <= 105) buntetes = 90000;
else if (v <= 115) buntetes = 130000;
else if (v <= 125) buntetes = 200000;
else buntetes = 300000;
System.out.println(buntetes + ",- Ft.");
}
}
}
| 874 | 0.512673 | 0.445853 | 25 | 33.720001 | 17.007105 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72 | false | false |
10
|
aa2490f8e15bfc4e87823e3c80e45bec91d0f320
| 25,426,206,433,433 |
e37adf9168bb5b9ae79a0e3b753a63b3bbd7c7bc
|
/src/main/java/craicoverflow89/lwjgl/shaders/StaticShader.java
|
35204481d0c6b4a43d4eda61cca9f6153b67c38a
|
[] |
no_license
|
CraicOverflow89/LWJGL
|
https://github.com/CraicOverflow89/LWJGL
|
ce1d5e5e03f738c515a52079a8136e78a1ae8a5b
|
86045d18149bf4bd8df576e1685d3749b921c37f
|
refs/heads/master
| 2020-08-04T07:54:47.240000 | 2019-11-13T09:07:58 | 2019-11-13T09:07:58 | 212,063,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package craicoverflow89.lwjgl.shaders;
import craicoverflow89.lwjgl.entities.camera.Camera;
import craicoverflow89.lwjgl.entities.light.AbstractLight;
import craicoverflow89.lwjgl.helpers.Colour;
import craicoverflow89.lwjgl.helpers.Maths;
import craicoverflow89.lwjgl.helpers.Pair;
import java.util.List;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
public final class StaticShader extends AbstractShader {
public StaticShader() {
super(
"vertexStatic", "fragmentStatic",
List.of("position", "textureCoords", "normal"),
List.of(
"transformationMatrix", "projectionMatrix", "viewMatrix", "shineDamper", "reflectivity", "lightFake",
"skyColour", "textureRows", "textureOffset"
),
List.of(new Pair("lightPosition", 4), new Pair("lightColour", 4), new Pair("attenuation", 4))
);
}
public void loadLights(List<AbstractLight> lightList) {
// Iterate Lights
for(int x = 0; x < LIGHTS_MAX; x ++) {
// Light Supplied
if(x < lightList.size()) {
loadUniform("lightPosition", x, lightList.get(x).getPosition());
loadUniform("lightColour", x, lightList.get(x).getColour().asVector3f());
loadUniform("attenuation", x, lightList.get(x).getAttenuation());
}
// Not Supplied
else {
loadUniform("lightPosition", x, new Vector3f(0f, 0f, 0f));
loadUniform("lightColour", x, new Vector3f(0f, 0f, 0f));
loadUniform("attenuation", x, new Vector3f(1f, 0f, 0f));
}
}
}
public void loadLightFake(Boolean lightFake) {
loadUniform("lightFake", lightFake);
}
public void loadProjectionMatrix(Matrix4f projection) {
loadUniform("projectionMatrix", projection);
}
public void loadShine(float shineDamper, float reflectivity) {
loadUniform("shineDamper", shineDamper);
loadUniform("reflectivity", reflectivity);
}
public void loadSkyColour(Colour skyColour) {
loadUniform("skyColour", skyColour.asVector3f());
}
public void loadTextureOffset(float offsetX, float offsetY) {
loadUniform("textureOffset", new Vector2f(offsetX, offsetY));
}
public void loadTextureRows(int rows) {
loadUniform("textureRows", (float) rows);
}
public final void loadTransformationMatrix(Matrix4f transformation) {
loadUniform("transformationMatrix", transformation);
}
public void loadViewMatrix(Camera camera) {
super.loadUniform("viewMatrix", Maths.createViewMatrix(camera));
}
}
|
UTF-8
|
Java
| 2,768 |
java
|
StaticShader.java
|
Java
|
[] | null |
[] |
package craicoverflow89.lwjgl.shaders;
import craicoverflow89.lwjgl.entities.camera.Camera;
import craicoverflow89.lwjgl.entities.light.AbstractLight;
import craicoverflow89.lwjgl.helpers.Colour;
import craicoverflow89.lwjgl.helpers.Maths;
import craicoverflow89.lwjgl.helpers.Pair;
import java.util.List;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
public final class StaticShader extends AbstractShader {
public StaticShader() {
super(
"vertexStatic", "fragmentStatic",
List.of("position", "textureCoords", "normal"),
List.of(
"transformationMatrix", "projectionMatrix", "viewMatrix", "shineDamper", "reflectivity", "lightFake",
"skyColour", "textureRows", "textureOffset"
),
List.of(new Pair("lightPosition", 4), new Pair("lightColour", 4), new Pair("attenuation", 4))
);
}
public void loadLights(List<AbstractLight> lightList) {
// Iterate Lights
for(int x = 0; x < LIGHTS_MAX; x ++) {
// Light Supplied
if(x < lightList.size()) {
loadUniform("lightPosition", x, lightList.get(x).getPosition());
loadUniform("lightColour", x, lightList.get(x).getColour().asVector3f());
loadUniform("attenuation", x, lightList.get(x).getAttenuation());
}
// Not Supplied
else {
loadUniform("lightPosition", x, new Vector3f(0f, 0f, 0f));
loadUniform("lightColour", x, new Vector3f(0f, 0f, 0f));
loadUniform("attenuation", x, new Vector3f(1f, 0f, 0f));
}
}
}
public void loadLightFake(Boolean lightFake) {
loadUniform("lightFake", lightFake);
}
public void loadProjectionMatrix(Matrix4f projection) {
loadUniform("projectionMatrix", projection);
}
public void loadShine(float shineDamper, float reflectivity) {
loadUniform("shineDamper", shineDamper);
loadUniform("reflectivity", reflectivity);
}
public void loadSkyColour(Colour skyColour) {
loadUniform("skyColour", skyColour.asVector3f());
}
public void loadTextureOffset(float offsetX, float offsetY) {
loadUniform("textureOffset", new Vector2f(offsetX, offsetY));
}
public void loadTextureRows(int rows) {
loadUniform("textureRows", (float) rows);
}
public final void loadTransformationMatrix(Matrix4f transformation) {
loadUniform("transformationMatrix", transformation);
}
public void loadViewMatrix(Camera camera) {
super.loadUniform("viewMatrix", Maths.createViewMatrix(camera));
}
}
| 2,768 | 0.642702 | 0.629697 | 81 | 33.185184 | 29.203041 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.950617 | false | false |
10
|
2b8d1ba9691f8f1162f64375354b55161c98303f
| 18,176,301,630,367 |
5443d9a34eba152e36a089a63cd2958004dac44b
|
/projSimuladorMercado/EuSemFaculdade.java
|
8ad50db9d5871a39dd1e5e8ed5249f2c83365c50
|
[] |
no_license
|
HenriqueVmc/ads-pcd
|
https://github.com/HenriqueVmc/ads-pcd
|
606ae7dd978f38c6bfb1658abda517cdeca81cde
|
cbf27c47b1809084d15a8e8dfd8a2799ae6e70c3
|
refs/heads/master
| 2020-04-23T18:36:57.934000 | 2019-07-02T00:52:14 | 2019-07-02T00:52:14 | 171,373,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pct;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
public class EuSemFaculdade implements Runnable {
private static Random generator = new Random();
private Buffer rampa;
private Sacola sacola;
private String dataFormatada;
private SimpleDateFormat horas;
public EuSemFaculdade(Buffer rampa) {
this.rampa = rampa;
this.sacola = new Sacola();
this.horas = new SimpleDateFormat("HH:mm:ss");
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(generator.nextInt(3000));
ItensMercado item = rampa.getRandom();
sacola.setCompra(item);
dataFormatada = horas.format(Calendar.getInstance().getTime());
System.out.println("Eu sem Facul: [" + dataFormatada + "] Acomodando item " + item.getNome() + " na sacola");
}
} catch (InterruptedException exception) {
exception.printStackTrace();
}
System.out.printf("\n--- Fim do empacotamento ---\n");
String dataFormatada = horas.format(Calendar.getInstance().getTime());
System.out.println("\nFim da simulação: [" + dataFormatada + "]");
}
}
|
UTF-8
|
Java
| 1,342 |
java
|
EuSemFaculdade.java
|
Java
|
[] | null |
[] |
package pct;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
public class EuSemFaculdade implements Runnable {
private static Random generator = new Random();
private Buffer rampa;
private Sacola sacola;
private String dataFormatada;
private SimpleDateFormat horas;
public EuSemFaculdade(Buffer rampa) {
this.rampa = rampa;
this.sacola = new Sacola();
this.horas = new SimpleDateFormat("HH:mm:ss");
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(generator.nextInt(3000));
ItensMercado item = rampa.getRandom();
sacola.setCompra(item);
dataFormatada = horas.format(Calendar.getInstance().getTime());
System.out.println("Eu sem Facul: [" + dataFormatada + "] Acomodando item " + item.getNome() + " na sacola");
}
} catch (InterruptedException exception) {
exception.printStackTrace();
}
System.out.printf("\n--- Fim do empacotamento ---\n");
String dataFormatada = horas.format(Calendar.getInstance().getTime());
System.out.println("\nFim da simulação: [" + dataFormatada + "]");
}
}
| 1,342 | 0.577612 | 0.572388 | 42 | 30.928572 | 28.964176 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547619 | false | false |
10
|
82ca2b7010505236a33794128a7ec7b65384912b
| 18,176,301,632,068 |
6f916c4c57a4a790e34523c7b9c1bafdbbadc489
|
/HW6/108590017_HW6_1/app/src/main/java/com/example/a108590017_hw6_1/MainActivity.java
|
64f31c5ac56e8d15bf493567b272d5a3458a9259
|
[] |
no_license
|
t108590017/109-2-Android
|
https://github.com/t108590017/109-2-Android
|
b5610eafe1da5d0d2b2369c9e5448e192f77c3a6
|
e090383f774b548da4dcac4b2e34bbbfd0afd4b1
|
refs/heads/master
| 2023-04-17T14:23:21.033000 | 2021-05-04T15:11:05 | 2021-05-04T15:11:05 | 341,473,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.a108590017_hw6_1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private CheckBox mChocolateCyrup;
private CheckBox mSprinkles;
private CheckBox mCrushedNuts;
private CheckBox mCherries;
private CheckBox mcheckBox5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChocolateCyrup = (CheckBox) findViewById(R.id.ChocolateCyrup);
mSprinkles = (CheckBox) findViewById(R.id.Sprinkles);
mCrushedNuts = (CheckBox) findViewById(R.id.CrushedNuts);
mCherries = (CheckBox) findViewById(R.id.Cherries);
mcheckBox5 = (CheckBox) findViewById(R.id.checkBox5);
}
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,Toast.LENGTH_SHORT).show();
}
public void onButtonClicked(View view) {
String ToastS="Toppings:";
if (mChocolateCyrup.isChecked())
ToastS=ToastS+" Chocolate Cyrup";
if (mSprinkles.isChecked())
ToastS=ToastS+" Sprinkles";
if (mCrushedNuts.isChecked())
ToastS=ToastS+" Crushed Nuts";
if (mCherries.isChecked())
ToastS=ToastS+" Cherries";
if (mcheckBox5.isChecked())
ToastS=ToastS+" Orio Cookie Crumbles";
displayToast(ToastS);
}
}
|
UTF-8
|
Java
| 1,614 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.a108590017_hw6_1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private CheckBox mChocolateCyrup;
private CheckBox mSprinkles;
private CheckBox mCrushedNuts;
private CheckBox mCherries;
private CheckBox mcheckBox5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChocolateCyrup = (CheckBox) findViewById(R.id.ChocolateCyrup);
mSprinkles = (CheckBox) findViewById(R.id.Sprinkles);
mCrushedNuts = (CheckBox) findViewById(R.id.CrushedNuts);
mCherries = (CheckBox) findViewById(R.id.Cherries);
mcheckBox5 = (CheckBox) findViewById(R.id.checkBox5);
}
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,Toast.LENGTH_SHORT).show();
}
public void onButtonClicked(View view) {
String ToastS="Toppings:";
if (mChocolateCyrup.isChecked())
ToastS=ToastS+" Chocolate Cyrup";
if (mSprinkles.isChecked())
ToastS=ToastS+" Sprinkles";
if (mCrushedNuts.isChecked())
ToastS=ToastS+" Crushed Nuts";
if (mCherries.isChecked())
ToastS=ToastS+" Cherries";
if (mcheckBox5.isChecked())
ToastS=ToastS+" Orio Cookie Crumbles";
displayToast(ToastS);
}
}
| 1,614 | 0.687113 | 0.677819 | 48 | 32.645832 | 21.021309 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604167 | false | false |
10
|
1f635f2db7b16a53ae33c7c0439c897295d3f8e6
| 32,358,283,646,357 |
b9465619c81bbc9353272d9203a17b45627fb121
|
/uiac.dal/src/main/java/com/xrk/uiac/dal/dao/UserInfoDAO.java
|
3cb8e6ed41c0ec40a982c7ed69c7067220947361
|
[] |
no_license
|
mendylee/uiso
|
https://github.com/mendylee/uiso
|
4d9b9d6fc4965e6beb5704dea99d55b33d1350fb
|
a594bf59725c1015757fcc5ee3517af31cf744f7
|
refs/heads/master
| 2020-04-07T01:55:02.367000 | 2018-11-17T06:24:59 | 2018-11-17T06:24:59 | 157,957,075 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.xrk.uiac.dal.dao;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.xrk.hws.dal.core.DataSet;
import com.xrk.uiac.dal.Dal;
import com.xrk.uiac.dal.entity.UserInfo;
/**
*
* UserInfo实体类的DAO
*
* <br>==========================
* <br> 公司:广州向日葵信息科技有限公司
* <br> 开发:yexx<yexiaoxiao@xiangrikui.com>
* <br> 版本:1.0
* <br> 创建时间:2015年5月11日
* <br> JDK版本:1.7
* <br>==========================
*/
public class UserInfoDAO
{
private static final String COM_INSERT_USERINFO = "insertUserInfo";
private static final String COM_FIND_WITH_UID = "findWithUid";
private static final String COM_FIND_WITH_MOBILE = "findWithMobile";
private static final String COM_UPDATE_USERINFO = "updateUserInfo";
private static final String COM_UPDATE_TO_BIND_MOBILE = "updateToBindMobile";
private static final String COM_UPDATE_TO_BIND_EMAIL = "updateToBindEmail";
private static final String COM_UPDATE_WITH_MOBILE = "updateWithMobile";
//测试用
private static final String COM_DELETE_WITH_UID = "deleteUser";
private static DataSet dataSet = Dal.getDataSet(UserInfo.class);
public static int insert(UserInfo userInfo)
{
return dataSet.insertOne(COM_INSERT_USERINFO, userInfo, true, null);
}
public static UserInfo findWithUid(long uid)
{
Object[] paras = new Object[1];
paras[0] = new Long(uid);
return dataSet.findOne(COM_FIND_WITH_UID, paras);
}
public static int deleteUser(long uid)
{
Object[] paras = new Object[1];
paras[0] = new Long(uid);
return dataSet.deleteMulti(COM_DELETE_WITH_UID, paras);
}
public static UserInfo findWithMobile(String mobile)
{
Object[] paras = new Object[1];
paras[0] = mobile;
return dataSet.findOne(COM_FIND_WITH_MOBILE, paras);
}
public static int update(long uid, Map<String, Object> srcMap)
{
//将请求参数map转换成适合插入数据库的参数map
Map<String, Object> parasMap = getUpdateMap(srcMap);
Object[] qParas = new Object[1];
qParas[0] = new Long(uid);
return dataSet.updateOne(COM_UPDATE_USERINFO, qParas, parasMap, false, false);
}
public static int updateMobileBindingStatus(long uid, String mobile, int bindingStatus)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[2];
qParas[0] = new Long(uid);
upParas[0] = new Integer(bindingStatus);
upParas[1] = mobile;
return dataSet.updateOne(COM_UPDATE_TO_BIND_MOBILE, qParas, upParas, false, false);
}
public static int updateEmailBindingStatus(long uid, String email, int bindingStatus)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[2];
qParas[0] = new Long(uid);
upParas[0] = new Integer(bindingStatus);
upParas[1] = email;
return dataSet.updateOne(COM_UPDATE_TO_BIND_EMAIL, qParas, upParas, false, false);
}
public static int updateWithMobile(long uid, String mobile)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[1];
qParas[0] = new Long(uid);
upParas[0] = mobile;
return dataSet.updateOne(COM_UPDATE_WITH_MOBILE, qParas, upParas, true, false);
}
//将请求参数map转换成用于记录更新的键值对map
//即,将源map中的key(sex, username..)转换成用于数据库存储的key(sex, user_name...),值不变
public static Map<String, Object> getUpdateMap(Map<String, Object> srcMap)
{
if (srcMap == null)
{
return null;
}
String srcNameKey = "userName";
String destNameKey = "user_name";
String srcDateKey = "editDate";
String destDateKey = "edit_date";
String srcMobileIsVerifyKey = "mobileIsVerify";
String destMobileIsVerifyKey = "mobile_is_verify";
String srcEmailIsVerifyKey = "emailIsVerify";
String destEmailIsVerifyKey = "email_is_verify";
String sexKey = "sex";
Map<String, Object> destMap = new HashMap<String, Object>();
Set<Entry<String, Object>> entries = srcMap.entrySet();
for (Entry<String, Object> entry : entries)
{
String key = entry.getKey();
if (srcNameKey.equals(key))
{
destMap.put(destNameKey, entry.getValue());
}
else if (srcDateKey.equals(key))
{
destMap.put(destDateKey, entry.getValue());
}
else if (srcMobileIsVerifyKey.equals(key))
{
destMap.put(destMobileIsVerifyKey, entry.getValue());
}
else if (srcEmailIsVerifyKey.equals(key))
{
destMap.put(destEmailIsVerifyKey, entry.getValue());
}
else if (sexKey.equals(key))
{
Object value = new Integer((int) Math.round((Double) entry.getValue()));
destMap.put(sexKey, value);
}
else
{
destMap.put(entry.getKey(), entry.getValue());
}
}
return destMap;
}
}
|
UTF-8
|
Java
| 4,694 |
java
|
UserInfoDAO.java
|
Java
|
[
{
"context": "========\n * <br> 公司:广州向日葵信息科技有限公司\n * <br> 开发:yexx<yexiaoxiao@xiangrikui.com>\n * <br> 版本:1.0\n * <br> 创建时间:2015年5月11日\n * <br> J",
"end": 368,
"score": 0.9999236464500427,
"start": 343,
"tag": "EMAIL",
"value": "yexiaoxiao@xiangrikui.com"
}
] | null |
[] |
package com.xrk.uiac.dal.dao;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.xrk.hws.dal.core.DataSet;
import com.xrk.uiac.dal.Dal;
import com.xrk.uiac.dal.entity.UserInfo;
/**
*
* UserInfo实体类的DAO
*
* <br>==========================
* <br> 公司:广州向日葵信息科技有限公司
* <br> 开发:yexx<<EMAIL>>
* <br> 版本:1.0
* <br> 创建时间:2015年5月11日
* <br> JDK版本:1.7
* <br>==========================
*/
public class UserInfoDAO
{
private static final String COM_INSERT_USERINFO = "insertUserInfo";
private static final String COM_FIND_WITH_UID = "findWithUid";
private static final String COM_FIND_WITH_MOBILE = "findWithMobile";
private static final String COM_UPDATE_USERINFO = "updateUserInfo";
private static final String COM_UPDATE_TO_BIND_MOBILE = "updateToBindMobile";
private static final String COM_UPDATE_TO_BIND_EMAIL = "updateToBindEmail";
private static final String COM_UPDATE_WITH_MOBILE = "updateWithMobile";
//测试用
private static final String COM_DELETE_WITH_UID = "deleteUser";
private static DataSet dataSet = Dal.getDataSet(UserInfo.class);
public static int insert(UserInfo userInfo)
{
return dataSet.insertOne(COM_INSERT_USERINFO, userInfo, true, null);
}
public static UserInfo findWithUid(long uid)
{
Object[] paras = new Object[1];
paras[0] = new Long(uid);
return dataSet.findOne(COM_FIND_WITH_UID, paras);
}
public static int deleteUser(long uid)
{
Object[] paras = new Object[1];
paras[0] = new Long(uid);
return dataSet.deleteMulti(COM_DELETE_WITH_UID, paras);
}
public static UserInfo findWithMobile(String mobile)
{
Object[] paras = new Object[1];
paras[0] = mobile;
return dataSet.findOne(COM_FIND_WITH_MOBILE, paras);
}
public static int update(long uid, Map<String, Object> srcMap)
{
//将请求参数map转换成适合插入数据库的参数map
Map<String, Object> parasMap = getUpdateMap(srcMap);
Object[] qParas = new Object[1];
qParas[0] = new Long(uid);
return dataSet.updateOne(COM_UPDATE_USERINFO, qParas, parasMap, false, false);
}
public static int updateMobileBindingStatus(long uid, String mobile, int bindingStatus)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[2];
qParas[0] = new Long(uid);
upParas[0] = new Integer(bindingStatus);
upParas[1] = mobile;
return dataSet.updateOne(COM_UPDATE_TO_BIND_MOBILE, qParas, upParas, false, false);
}
public static int updateEmailBindingStatus(long uid, String email, int bindingStatus)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[2];
qParas[0] = new Long(uid);
upParas[0] = new Integer(bindingStatus);
upParas[1] = email;
return dataSet.updateOne(COM_UPDATE_TO_BIND_EMAIL, qParas, upParas, false, false);
}
public static int updateWithMobile(long uid, String mobile)
{
Object[] qParas = new Object[1];
Object[] upParas = new Object[1];
qParas[0] = new Long(uid);
upParas[0] = mobile;
return dataSet.updateOne(COM_UPDATE_WITH_MOBILE, qParas, upParas, true, false);
}
//将请求参数map转换成用于记录更新的键值对map
//即,将源map中的key(sex, username..)转换成用于数据库存储的key(sex, user_name...),值不变
public static Map<String, Object> getUpdateMap(Map<String, Object> srcMap)
{
if (srcMap == null)
{
return null;
}
String srcNameKey = "userName";
String destNameKey = "user_name";
String srcDateKey = "editDate";
String destDateKey = "edit_date";
String srcMobileIsVerifyKey = "mobileIsVerify";
String destMobileIsVerifyKey = "mobile_is_verify";
String srcEmailIsVerifyKey = "emailIsVerify";
String destEmailIsVerifyKey = "email_is_verify";
String sexKey = "sex";
Map<String, Object> destMap = new HashMap<String, Object>();
Set<Entry<String, Object>> entries = srcMap.entrySet();
for (Entry<String, Object> entry : entries)
{
String key = entry.getKey();
if (srcNameKey.equals(key))
{
destMap.put(destNameKey, entry.getValue());
}
else if (srcDateKey.equals(key))
{
destMap.put(destDateKey, entry.getValue());
}
else if (srcMobileIsVerifyKey.equals(key))
{
destMap.put(destMobileIsVerifyKey, entry.getValue());
}
else if (srcEmailIsVerifyKey.equals(key))
{
destMap.put(destEmailIsVerifyKey, entry.getValue());
}
else if (sexKey.equals(key))
{
Object value = new Integer((int) Math.round((Double) entry.getValue()));
destMap.put(sexKey, value);
}
else
{
destMap.put(entry.getKey(), entry.getValue());
}
}
return destMap;
}
}
| 4,676 | 0.694222 | 0.686889 | 156 | 27.846153 | 25.020288 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.294872 | false | false |
10
|
e89e80bf184b3b134703f580373ac65f6ad58192
| 15,049,565,446,904 |
e632b17643730c2c5f4532ebf8e56b627cd6e06c
|
/src/main/java/nju/citicup/common/jsonobj/GammaVarObj.java
|
1517f324a2f4583b12be4fbbea25ea971e74c034
|
[] |
no_license
|
NJUCitibankCup/NJUCitibankCup
|
https://github.com/NJUCitibankCup/NJUCitibankCup
|
2b0d639b67ebacf6374e62c97bde1d53c0553e3f
|
11b30fc44586374e2b13ffa03ffd401eecaad92f
|
refs/heads/master
| 2020-12-03T15:32:43.948000 | 2016-09-15T17:29:31 | 2016-09-15T17:29:31 | 66,934,122 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package nju.citicup.common.jsonobj;
import java.util.List;
/**
* Created by lenovo on 2016/9/11.
*/
public class GammaVarObj {
List<Integer> lowerGammaList;
List<Double> varList;
public GammaVarObj() {
}
public GammaVarObj(List<Integer> lowerGammaList, List<Double> varList) {
this.lowerGammaList = lowerGammaList;
this.varList = varList;
}
public List<Integer> getLowerGammaList() {
return lowerGammaList;
}
public void setLowerGammaList(List<Integer> lowerGammaList) {
this.lowerGammaList = lowerGammaList;
}
public List<Double> getVarList() {
return varList;
}
public void setVarList(List<Double> varList) {
this.varList = varList;
}
}
|
UTF-8
|
Java
| 754 |
java
|
GammaVarObj.java
|
Java
|
[
{
"context": "sonobj;\n\nimport java.util.List;\n\n/**\n * Created by lenovo on 2016/9/11.\n */\npublic class GammaVarObj {\n ",
"end": 85,
"score": 0.9995360970497131,
"start": 79,
"tag": "USERNAME",
"value": "lenovo"
}
] | null |
[] |
package nju.citicup.common.jsonobj;
import java.util.List;
/**
* Created by lenovo on 2016/9/11.
*/
public class GammaVarObj {
List<Integer> lowerGammaList;
List<Double> varList;
public GammaVarObj() {
}
public GammaVarObj(List<Integer> lowerGammaList, List<Double> varList) {
this.lowerGammaList = lowerGammaList;
this.varList = varList;
}
public List<Integer> getLowerGammaList() {
return lowerGammaList;
}
public void setLowerGammaList(List<Integer> lowerGammaList) {
this.lowerGammaList = lowerGammaList;
}
public List<Double> getVarList() {
return varList;
}
public void setVarList(List<Double> varList) {
this.varList = varList;
}
}
| 754 | 0.655172 | 0.645889 | 36 | 19.944445 | 20.576342 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305556 | false | false |
10
|
00e6c98cd7d2ed7a8ac62d46ba3cd096eced60ec
| 13,889,924,241,830 |
ce15c0e86842af386e3e5bbf312a553c47177184
|
/src/cryptohelper/view/CaricaSoluzioneDialog.java
|
4422ac96d1aa0d631c546b6dd99b004eb34a5296
|
[] |
no_license
|
sowdust/Progetto-Sviluppo
|
https://github.com/sowdust/Progetto-Sviluppo
|
08c51680665eebb9e097a992c1b1cf9d1085b652
|
9eb19d8bfdcb0c280e72b129cd2c7e3efb77b241
|
refs/heads/master
| 2021-01-25T08:48:41.871000 | 2014-06-12T08:38:33 | 2014-06-12T08:38:33 | null | 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 cryptohelper.view;
import cryptohelper.controller.SessionController;
import cryptohelper.model.Sessione;
import cryptohelper.model.Soluzione;
import cryptohelper.model.UserInfo;
import java.sql.SQLException;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
/**
*
* @author Mattia Cerrato, mattia.cerrato[at]studenti.unito[dot]it
*/
public class CaricaSoluzioneDialog extends javax.swing.JDialog {
/**
* A return status code - returned if Cancel button has been pressed
*/
public static final int RET_CANCEL = 0;
/**
* A return status code - returned if OK button has been pressed
*/
public static final int RET_OK = 1;
private static UserInfo proprietario;
private static Sessione sessione;
private static SessioneApertaPanel pannello;
private static UserInfo mittente;
private static UserInfo destinatario;
/**
* Creates new form CaricaSoluzioneDialog
*/
public CaricaSoluzioneDialog(java.awt.Frame parent, boolean modal, UserInfo proprietario, Sessione sessione, SessioneApertaPanel pannello, UserInfo mittente, UserInfo destinatario) {
super(parent, modal);
setLocationRelativeTo(parent);
CaricaSoluzioneDialog.sessione = sessione;
CaricaSoluzioneDialog.proprietario = proprietario;
CaricaSoluzioneDialog.pannello = pannello;
CaricaSoluzioneDialog.mittente = mittente;
CaricaSoluzioneDialog.destinatario = destinatario;
initComponents();
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton2 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
caricaSoluzioneComboBox = new javax.swing.JComboBox();
confermaCaricaButton = new javax.swing.JButton();
annullaCaricaButton = new javax.swing.JButton();
jButton2.setText("jButton2");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Seleziona una Soluzione da caricare");
caricaSoluzioneComboBox.setModel(new javax.swing.DefaultComboBoxModel<Soluzione>());
caricaSoluzioneComboBox.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
caricaSoluzioneComboBoxAncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
}
});
confermaCaricaButton.setText("Conferma");
confermaCaricaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confermaCaricaButtonActionPerformed(evt);
}
});
annullaCaricaButton.setText("Annulla");
annullaCaricaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
annullaCaricaButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(22, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(confermaCaricaButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(annullaCaricaButton))
.addComponent(jLabel1))
.addGap(114, 114, 114))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(caricaSoluzioneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel1)
.addGap(43, 43, 43)
.addComponent(caricaSoluzioneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(confermaCaricaButton)
.addComponent(annullaCaricaButton))
.addGap(50, 50, 50))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void confermaCaricaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confermaCaricaButtonActionPerformed
Soluzione s = (Soluzione) dlm.getSelectedItem();
if (s != null) {
sessionController.caricaSoluzione(sessione, s);
pannello.segnalaSoluzioneCaricata();
}
doClose(RET_OK);
}//GEN-LAST:event_confermaCaricaButtonActionPerformed
private void annullaCaricaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annullaCaricaButtonActionPerformed
doClose(RET_CANCEL);
}//GEN-LAST:event_annullaCaricaButtonActionPerformed
private void caricaSoluzioneComboBoxAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_caricaSoluzioneComboBoxAncestorAdded
try {
List<Soluzione> soluzioni = sessionController.mostraSoluzioni(mittente, destinatario, proprietario);
dlm = (DefaultComboBoxModel<Soluzione>) caricaSoluzioneComboBox.getModel();
for (Soluzione soluzione : soluzioni) {
dlm.addElement(soluzione);
}
caricaSoluzioneComboBox.setSelectedIndex(-1);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}//GEN-LAST:event_caricaSoluzioneComboBoxAncestorAdded
private void doClose(int retStatus) {
setVisible(false);
dispose();
}
SessionController sessionController = SessionController.getInstance();
private DefaultComboBoxModel<Soluzione> dlm;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton annullaCaricaButton;
private javax.swing.JComboBox caricaSoluzioneComboBox;
private javax.swing.JButton confermaCaricaButton;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 8,660 |
java
|
CaricaSoluzioneDialog.java
|
Java
|
[
{
"context": "vax.swing.DefaultComboBoxModel;\n\n/**\n *\n * @author Mattia Cerrato, mattia.cerrato[at]studenti.unito[dot]it\n */\npubl",
"end": 499,
"score": 0.9998853802680969,
"start": 485,
"tag": "NAME",
"value": "Mattia Cerrato"
}
] | 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 cryptohelper.view;
import cryptohelper.controller.SessionController;
import cryptohelper.model.Sessione;
import cryptohelper.model.Soluzione;
import cryptohelper.model.UserInfo;
import java.sql.SQLException;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
/**
*
* @author <NAME>, mattia.cerrato[at]studenti.unito[dot]it
*/
public class CaricaSoluzioneDialog extends javax.swing.JDialog {
/**
* A return status code - returned if Cancel button has been pressed
*/
public static final int RET_CANCEL = 0;
/**
* A return status code - returned if OK button has been pressed
*/
public static final int RET_OK = 1;
private static UserInfo proprietario;
private static Sessione sessione;
private static SessioneApertaPanel pannello;
private static UserInfo mittente;
private static UserInfo destinatario;
/**
* Creates new form CaricaSoluzioneDialog
*/
public CaricaSoluzioneDialog(java.awt.Frame parent, boolean modal, UserInfo proprietario, Sessione sessione, SessioneApertaPanel pannello, UserInfo mittente, UserInfo destinatario) {
super(parent, modal);
setLocationRelativeTo(parent);
CaricaSoluzioneDialog.sessione = sessione;
CaricaSoluzioneDialog.proprietario = proprietario;
CaricaSoluzioneDialog.pannello = pannello;
CaricaSoluzioneDialog.mittente = mittente;
CaricaSoluzioneDialog.destinatario = destinatario;
initComponents();
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton2 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
caricaSoluzioneComboBox = new javax.swing.JComboBox();
confermaCaricaButton = new javax.swing.JButton();
annullaCaricaButton = new javax.swing.JButton();
jButton2.setText("jButton2");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Seleziona una Soluzione da caricare");
caricaSoluzioneComboBox.setModel(new javax.swing.DefaultComboBoxModel<Soluzione>());
caricaSoluzioneComboBox.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
caricaSoluzioneComboBoxAncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
}
});
confermaCaricaButton.setText("Conferma");
confermaCaricaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confermaCaricaButtonActionPerformed(evt);
}
});
annullaCaricaButton.setText("Annulla");
annullaCaricaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
annullaCaricaButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(22, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(confermaCaricaButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(annullaCaricaButton))
.addComponent(jLabel1))
.addGap(114, 114, 114))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(caricaSoluzioneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel1)
.addGap(43, 43, 43)
.addComponent(caricaSoluzioneComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(confermaCaricaButton)
.addComponent(annullaCaricaButton))
.addGap(50, 50, 50))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void confermaCaricaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confermaCaricaButtonActionPerformed
Soluzione s = (Soluzione) dlm.getSelectedItem();
if (s != null) {
sessionController.caricaSoluzione(sessione, s);
pannello.segnalaSoluzioneCaricata();
}
doClose(RET_OK);
}//GEN-LAST:event_confermaCaricaButtonActionPerformed
private void annullaCaricaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_annullaCaricaButtonActionPerformed
doClose(RET_CANCEL);
}//GEN-LAST:event_annullaCaricaButtonActionPerformed
private void caricaSoluzioneComboBoxAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_caricaSoluzioneComboBoxAncestorAdded
try {
List<Soluzione> soluzioni = sessionController.mostraSoluzioni(mittente, destinatario, proprietario);
dlm = (DefaultComboBoxModel<Soluzione>) caricaSoluzioneComboBox.getModel();
for (Soluzione soluzione : soluzioni) {
dlm.addElement(soluzione);
}
caricaSoluzioneComboBox.setSelectedIndex(-1);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}//GEN-LAST:event_caricaSoluzioneComboBoxAncestorAdded
private void doClose(int retStatus) {
setVisible(false);
dispose();
}
SessionController sessionController = SessionController.getInstance();
private DefaultComboBoxModel<Soluzione> dlm;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton annullaCaricaButton;
private javax.swing.JComboBox caricaSoluzioneComboBox;
private javax.swing.JButton confermaCaricaButton;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
| 8,652 | 0.684873 | 0.67679 | 187 | 45.310162 | 37.127762 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604278 | false | false |
10
|
79f8459578ef0156dae47b3384625159db5e4fdb
| 22,608,707,870,282 |
dc829b6ec2fca1df862226712d5f2906d6ddc623
|
/CoreJava/src/com/covalense/javaapp/inheritance/Test4.java
|
1364408454fb8ab0e4de003c32b761fa06b383f8
|
[] |
no_license
|
manoj-git-eng/ELF-06June19-Covalense-ManojKumarBehera
|
https://github.com/manoj-git-eng/ELF-06June19-Covalense-ManojKumarBehera
|
eb214118f58b0d3ed5062c4d0da97b6b71724705
|
5ea6f4a2833a6fd9c6a74c981bbb95af8c528967
|
refs/heads/master
| 2023-01-11T22:19:04.480000 | 2019-08-24T12:13:11 | 2019-08-24T12:13:11 | 192,527,009 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.covalense.javaapp.inheritance;
public class Test4
{
public static void main(String[] args) {
Pen p=new Marker();
p.write();
p.cost=10;
}
}
|
UTF-8
|
Java
| 164 |
java
|
Test4.java
|
Java
|
[] | null |
[] |
package com.covalense.javaapp.inheritance;
public class Test4
{
public static void main(String[] args) {
Pen p=new Marker();
p.write();
p.cost=10;
}
}
| 164 | 0.664634 | 0.646341 | 11 | 13.818182 | 14.794459 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false |
10
|
a5e6c3b6b5ada0cbb099217879ddf098c702828d
| 23,587,960,393,157 |
9af1eda507fb5da2a8ed97db5f2f8f2bd08afc19
|
/src/main/java/com/ecsail/pdf/directory/PDF_BoardOfDirectors.java
|
d57fd8e3544681fdeb81613cb2b545b3e84a7054
|
[] |
no_license
|
PerryCameron/ECSC
|
https://github.com/PerryCameron/ECSC
|
02db844fdb9651f19cc5c25b1c039d79054e4679
|
bee2034512d41e54d6ac50257fbdb5158e66df5b
|
refs/heads/master
| 2023-06-21T01:35:08.233000 | 2022-10-01T20:36:21 | 2022-10-01T20:36:21 | 253,672,895 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ecsail.pdf.directory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.ecsail.enums.Officer;
import com.ecsail.sql.select.SqlOfficer;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
public class PDF_BoardOfDirectors extends Table {
PDF_Object_Settings set;
ArrayList<PDF_Object_Officer> officers;
public PDF_BoardOfDirectors(int numColumns, PDF_Object_Settings set) {
super(numColumns);
this.set = set;
officers= SqlOfficer.getOfficersByYear(set.getSelectedYear());
Collections.sort(officers , Comparator.comparing(PDF_Object_Officer::getLname));
setWidth(set.getPageSize().getWidth() * 0.9f); // makes table 90% of page width
setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell = new Cell();
cell.setBorder(Border.NO_BORDER);
//cell.add(new Paragraph("\n"));
cell.add(createOfficersTable());
//cell.add(new Paragraph("\n"));
cell.add(createChairmenTable());
//cell.add(new Paragraph("\n"));
cell.add(createBODTable());
addCell(cell);
cell = new Cell();
cell.add(new Paragraph("\n\n\n"));
cell.setBorder(Border.NO_BORDER);
addCell(cell);
cell = new Cell();
cell.setBorder(Border.NO_BORDER);
Paragraph p = new Paragraph("\u00a9Eagle Creek Sailing club 1969-"+set.getSelectedYear()+" - This directory may not be used for commercial purposes");
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
addCell(cell);
}
public Table createOfficersTable() {
Table officerTable = new Table(2);
officerTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
officerTable.setWidth(this.getWidth().getValue() * 0.6f);
//mainTable.setWidth(590);
Cell cell;
Paragraph p;
cell = new Cell(1,2);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("\n" + set.getSelectedYear() + " Officers");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setTextAlignment(TextAlignment.CENTER);
p.setFontColor(set.getMainColor());
cell.add(p);
officerTable.addCell(cell);
//cell = new Cell(1,2);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//officerTable.addCell(cell);
addOfficerToTable(officerTable, "CO");
addOfficerToTable(officerTable, "VC");
addOfficerToTable(officerTable, "PC");
addOfficerToTable(officerTable, "FM");
addOfficerToTable(officerTable, "TR");
addOfficerToTable(officerTable, "SE");
return officerTable;
}
public Table createChairmenTable() {
Table chairTable = new Table(2);
chairTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
chairTable.setWidth(this.getWidth().getValue() * 0.7f);
Cell cell;
Paragraph p;
cell = new Cell(1,2);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("Commitee Chairs");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setFontColor(set.getMainColor());
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
chairTable.addCell(cell);
//cell = new Cell(1,2);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//chairTable.addCell(cell);
addOfficerToTable(chairTable, "HM");
addOfficerToTable(chairTable, "AH");
addOfficerToTable(chairTable, "MS");
addOfficerToTable(chairTable, "AM");
addOfficerToTable(chairTable, "PU");
addOfficerToTable(chairTable, "RA");
addOfficerToTable(chairTable, "AR");
addOfficerToTable(chairTable, "SM");
addOfficerToTable(chairTable, "JP");
addOfficerToTable(chairTable, "AJ");
addOfficerToTable(chairTable, "SO");
addOfficerToTable(chairTable, "SA");
return chairTable;
}
private Table createBODTable() {
Table bodTable = new Table(3);
bodTable.setWidth(this.getWidth().getValue());
bodTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell;
Paragraph p;
cell = new Cell(1,3);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("Current Board Members");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setFontColor(set.getMainColor());
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
bodTable.addCell(cell);
//cell = new Cell(1,3);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//bodTable.addCell(cell);
createBoardMemberTables(bodTable); // will create 3 more cells and put a table in each
return bodTable;
}
private void createBoardMemberTables(Table bodTable) {
ArrayList<String> currentYearList = new ArrayList<String>();
ArrayList<String> nextYearList = new ArrayList<String>();
ArrayList<String> afterNextYearList = new ArrayList<String>();
int thisYear = Integer.parseInt(set.getSelectedYear());
int nextYear = thisYear + 1;
int afterNextYear = thisYear + 2;
for (PDF_Object_Officer o : officers) {
if (Integer.parseInt(o.getBoardTermEndYear()) == thisYear)
currentYearList.add(o.fname + " " + o.lname);
if (Integer.parseInt(o.getBoardTermEndYear()) == nextYear)
nextYearList.add(o.fname + " " + o.lname);
if (Integer.parseInt(o.getBoardTermEndYear()) == afterNextYear)
afterNextYearList.add(o.fname + " " + o.lname);
}
Cell cell;
cell = new Cell(); // make a big cell in previous table to put 3 tables in
cell.add(createBoardMemberColumn(currentYearList, thisYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
cell = new Cell();
cell.add(createBoardMemberColumn(nextYearList, nextYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
cell = new Cell();
cell.add(createBoardMemberColumn(afterNextYearList, afterNextYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
}
private Table createBoardMemberColumn(ArrayList<String> yearList, String year) {
Table columnTable = new Table(1);
Cell cell;
Paragraph p;
cell = new Cell();
p = new Paragraph(year);
p.setFontSize(12);
p.setFont(set.getColumnHead());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
p.setTextAlignment(TextAlignment.LEFT);
cell.setBorder(Border.NO_BORDER).add(p);
columnTable.addCell(cell);
for(String name: yearList) {
cell = new Cell();
p = new Paragraph(name);
p.setFontSize(set.getNormalFontSize());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p);
columnTable.addCell(cell);
}
return columnTable;
}
private void addOfficerToTable(Table mainTable, String type) {
if(!getOfficer(type).equals("")) { // if it doesn't exist don't print it
Cell cell;
Paragraph p;
cell = new Cell();
p = new Paragraph(Officer.getNameByCode(type) + ":");
p.setFontSize(set.getNormalFontSize());
p.setFont(set.getColumnHead());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p).setHorizontalAlignment(HorizontalAlignment.CENTER);
mainTable.addCell(cell);
cell = new Cell();
p = new Paragraph(getOfficer(type));
p.setFontSize(set.getNormalFontSize());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p).setHorizontalAlignment(HorizontalAlignment.CENTER);
mainTable.addCell(cell);
}
}
public String getOfficer(String type) {
String officer = "";
for(PDF_Object_Officer o: officers) {
if(o.getOfficerType().equals(type))
officer = o.getFname() + " " + o.getLname();
}
return officer;
}
}
|
UTF-8
|
Java
| 7,779 |
java
|
PDF_BoardOfDirectors.java
|
Java
|
[] | null |
[] |
package com.ecsail.pdf.directory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.ecsail.enums.Officer;
import com.ecsail.sql.select.SqlOfficer;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
public class PDF_BoardOfDirectors extends Table {
PDF_Object_Settings set;
ArrayList<PDF_Object_Officer> officers;
public PDF_BoardOfDirectors(int numColumns, PDF_Object_Settings set) {
super(numColumns);
this.set = set;
officers= SqlOfficer.getOfficersByYear(set.getSelectedYear());
Collections.sort(officers , Comparator.comparing(PDF_Object_Officer::getLname));
setWidth(set.getPageSize().getWidth() * 0.9f); // makes table 90% of page width
setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell = new Cell();
cell.setBorder(Border.NO_BORDER);
//cell.add(new Paragraph("\n"));
cell.add(createOfficersTable());
//cell.add(new Paragraph("\n"));
cell.add(createChairmenTable());
//cell.add(new Paragraph("\n"));
cell.add(createBODTable());
addCell(cell);
cell = new Cell();
cell.add(new Paragraph("\n\n\n"));
cell.setBorder(Border.NO_BORDER);
addCell(cell);
cell = new Cell();
cell.setBorder(Border.NO_BORDER);
Paragraph p = new Paragraph("\u00a9Eagle Creek Sailing club 1969-"+set.getSelectedYear()+" - This directory may not be used for commercial purposes");
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
addCell(cell);
}
public Table createOfficersTable() {
Table officerTable = new Table(2);
officerTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
officerTable.setWidth(this.getWidth().getValue() * 0.6f);
//mainTable.setWidth(590);
Cell cell;
Paragraph p;
cell = new Cell(1,2);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("\n" + set.getSelectedYear() + " Officers");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setTextAlignment(TextAlignment.CENTER);
p.setFontColor(set.getMainColor());
cell.add(p);
officerTable.addCell(cell);
//cell = new Cell(1,2);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//officerTable.addCell(cell);
addOfficerToTable(officerTable, "CO");
addOfficerToTable(officerTable, "VC");
addOfficerToTable(officerTable, "PC");
addOfficerToTable(officerTable, "FM");
addOfficerToTable(officerTable, "TR");
addOfficerToTable(officerTable, "SE");
return officerTable;
}
public Table createChairmenTable() {
Table chairTable = new Table(2);
chairTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
chairTable.setWidth(this.getWidth().getValue() * 0.7f);
Cell cell;
Paragraph p;
cell = new Cell(1,2);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("Commitee Chairs");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setFontColor(set.getMainColor());
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
chairTable.addCell(cell);
//cell = new Cell(1,2);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//chairTable.addCell(cell);
addOfficerToTable(chairTable, "HM");
addOfficerToTable(chairTable, "AH");
addOfficerToTable(chairTable, "MS");
addOfficerToTable(chairTable, "AM");
addOfficerToTable(chairTable, "PU");
addOfficerToTable(chairTable, "RA");
addOfficerToTable(chairTable, "AR");
addOfficerToTable(chairTable, "SM");
addOfficerToTable(chairTable, "JP");
addOfficerToTable(chairTable, "AJ");
addOfficerToTable(chairTable, "SO");
addOfficerToTable(chairTable, "SA");
return chairTable;
}
private Table createBODTable() {
Table bodTable = new Table(3);
bodTable.setWidth(this.getWidth().getValue());
bodTable.setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell;
Paragraph p;
cell = new Cell(1,3);
cell.setBorder(Border.NO_BORDER);
p = new Paragraph("Current Board Members");
p.setFontSize(set.getNormalFontSize() + 4);
p.setFont(set.getColumnHead());
p.setFontColor(set.getMainColor());
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
bodTable.addCell(cell);
//cell = new Cell(1,3);
//cell.add(new Paragraph("\n"));
//cell.setBorder(Border.NO_BORDER);
//bodTable.addCell(cell);
createBoardMemberTables(bodTable); // will create 3 more cells and put a table in each
return bodTable;
}
private void createBoardMemberTables(Table bodTable) {
ArrayList<String> currentYearList = new ArrayList<String>();
ArrayList<String> nextYearList = new ArrayList<String>();
ArrayList<String> afterNextYearList = new ArrayList<String>();
int thisYear = Integer.parseInt(set.getSelectedYear());
int nextYear = thisYear + 1;
int afterNextYear = thisYear + 2;
for (PDF_Object_Officer o : officers) {
if (Integer.parseInt(o.getBoardTermEndYear()) == thisYear)
currentYearList.add(o.fname + " " + o.lname);
if (Integer.parseInt(o.getBoardTermEndYear()) == nextYear)
nextYearList.add(o.fname + " " + o.lname);
if (Integer.parseInt(o.getBoardTermEndYear()) == afterNextYear)
afterNextYearList.add(o.fname + " " + o.lname);
}
Cell cell;
cell = new Cell(); // make a big cell in previous table to put 3 tables in
cell.add(createBoardMemberColumn(currentYearList, thisYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
cell = new Cell();
cell.add(createBoardMemberColumn(nextYearList, nextYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
cell = new Cell();
cell.add(createBoardMemberColumn(afterNextYearList, afterNextYear + ""));
cell.setBorder(Border.NO_BORDER);
bodTable.addCell(cell);
}
private Table createBoardMemberColumn(ArrayList<String> yearList, String year) {
Table columnTable = new Table(1);
Cell cell;
Paragraph p;
cell = new Cell();
p = new Paragraph(year);
p.setFontSize(12);
p.setFont(set.getColumnHead());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
p.setTextAlignment(TextAlignment.LEFT);
cell.setBorder(Border.NO_BORDER).add(p);
columnTable.addCell(cell);
for(String name: yearList) {
cell = new Cell();
p = new Paragraph(name);
p.setFontSize(set.getNormalFontSize());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p);
columnTable.addCell(cell);
}
return columnTable;
}
private void addOfficerToTable(Table mainTable, String type) {
if(!getOfficer(type).equals("")) { // if it doesn't exist don't print it
Cell cell;
Paragraph p;
cell = new Cell();
p = new Paragraph(Officer.getNameByCode(type) + ":");
p.setFontSize(set.getNormalFontSize());
p.setFont(set.getColumnHead());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p).setHorizontalAlignment(HorizontalAlignment.CENTER);
mainTable.addCell(cell);
cell = new Cell();
p = new Paragraph(getOfficer(type));
p.setFontSize(set.getNormalFontSize());
p.setFixedLeading(set.getFixedLeading() - 15); // sets spacing between lines of text
cell.setBorder(Border.NO_BORDER).add(p).setHorizontalAlignment(HorizontalAlignment.CENTER);
mainTable.addCell(cell);
}
}
public String getOfficer(String type) {
String officer = "";
for(PDF_Object_Officer o: officers) {
if(o.getOfficerType().equals(type))
officer = o.getFname() + " " + o.getLname();
}
return officer;
}
}
| 7,779 | 0.716673 | 0.710117 | 238 | 31.684874 | 23.340319 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.663866 | false | false |
10
|
e3dce0fbe2b9352cc6a54555db400c1188309499
| 32,349,693,692,208 |
d374e3ac82ad3aa41a12883c36aef5ebde08b43a
|
/JokeAssignment/src/main/java/io/neuraljam/services/JokeService.java
|
41e71a463b6aeb5a85581cf14410074d3b11379d
|
[] |
no_license
|
brigero97/JokeAssignment
|
https://github.com/brigero97/JokeAssignment
|
7d85539bee1f70b3e7f60010979ea82c85683f7e
|
664858b59e682974c045f66ee7f6eba1b572859c
|
refs/heads/master
| 2023-03-17T10:03:15.081000 | 2021-03-15T11:37:39 | 2021-03-15T11:37:39 | 347,940,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.neuraljam.services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.neuraljam.entities.Joke;
import io.neuraljam.repositories.JokeRepository;
@Service("jokeService")
public class JokeService {
@Autowired
private JokeRepository jokeRepository;
public Joke findById(int id) {
return jokeRepository.findById(id);
}
public void saveJoke(Joke joke) {
jokeRepository.save(joke);
}
public ArrayList<Joke> findByBody(String body) {
return jokeRepository.findByBodyLike("%"+body+"%");
}
public void deleteJoke(int id) {
jokeRepository.deleteById(id);
}
}
|
UTF-8
|
Java
| 765 |
java
|
JokeService.java
|
Java
|
[] | null |
[] |
package io.neuraljam.services;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.neuraljam.entities.Joke;
import io.neuraljam.repositories.JokeRepository;
@Service("jokeService")
public class JokeService {
@Autowired
private JokeRepository jokeRepository;
public Joke findById(int id) {
return jokeRepository.findById(id);
}
public void saveJoke(Joke joke) {
jokeRepository.save(joke);
}
public ArrayList<Joke> findByBody(String body) {
return jokeRepository.findByBodyLike("%"+body+"%");
}
public void deleteJoke(int id) {
jokeRepository.deleteById(id);
}
}
| 765 | 0.69281 | 0.69281 | 34 | 20.5 | 19.711523 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false |
10
|
a04d611af4790182478383c05322bd876de1948a
| 33,449,205,304,143 |
cdb855181fcc6802937e1faf8a723039b93c3e80
|
/TP4-POO/src/ChambreInternet.java
|
3936d5cdf911bdb07bcc1228fd6d3b8ecf528e5e
|
[] |
no_license
|
Mapsred/Montmorency_TP-Java-POO
|
https://github.com/Mapsred/Montmorency_TP-Java-POO
|
5d7f4045ee9e0c7f61f85a85c30f79216f883426
|
100fdc5ec5902eb9c59f4e5f2fa81abf3c3c31e7
|
refs/heads/master
| 2021-05-30T16:39:08.283000 | 2015-12-23T23:05:54 | 2015-12-23T23:05:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Auteurs : François MATHIEU et Soti
* Fichier : ChambreInternet.java
* Cours : 420-165-MO (TP4, Hôtel)
* Date : 15 avril 2015
*/
// Package du programmeur.
import outilsjava.*;
/**
* La classe ChambreInternet hérite de la classe ChambreStandard.
*
* La classe ChambreInternet contient les informations et les méthodes
* supplémentaires pour une chambre de l'hôtel qui a un accès à Internet.
*/
public class ChambreInternet extends ChambreStandard {
// Constantes de la classe ChambreInternet.
// Peut accéder à Internet entre 0 et 744 heures (31 jours * 24 heures).
public static final double MIN_HEURES = 0;
public static final double MAX_HEURES = ChambreStandard.MAX_JOURS * 24;
// L'accès Internet coûte 0.50 $ de l'heure.
public static final double PRIX_INTERNET = 0.50;
// Champ d'instance privé de la classe ChambreInternet.
private double nbHeures; // Nombre d'heures pour l'accès Internet.
/**
* Constructeur de la classe ChambreInternet pour construire une chambre à
* accès Internet de base. Au début, aucun accès à Internet.
*/
public ChambreInternet() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
this.initialiserChambre();
}
/**
* Redéfinition de la méthode qui permet d'initialiser une chambre.
*/
@Override
public void initialiserChambre() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
super.initialiserChambre();
this.setNbHeures(0);
}
/**
* Méthode accesseur qui retourne le nombre d'heures d'accès à Internet.
*
* @return Le nombre d'heures d'accès à Internet.
*/
public double getNbHeures() {
return this.nbHeures;
}
/**
* Méthode mutateur qui modifie le nombre d'heures d'accès à Internet avec
* celui reçu en paramètre.
*
* @param nbHeures
* Le nombre d'heures d'accès à Internet.
*/
public void setNbHeures(double nbHeures) {
if (this.nbHeures >= ChambreInternet.MIN_HEURES
&& this.nbHeures <= ChambreInternet.MAX_HEURES) {
this.nbHeures = nbHeures;
}
}
/**
* Redéfinition de la méthode qui lit les informations de départ pour la
* chambre (lorsque le client quitte).
*/
@Override
public void lireInfosDepart() {
final String QUEST_NB_HEURES = "\nEntrez le nombre d'heures d'accès"
+ " à Internet (entre " + ChambreInternet.MIN_HEURES + " et "
+ ChambreInternet.MAX_HEURES + ") : ";
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
super.lireInfosDepart();
double NbHeuresInternet = OutilsLecture.lireReelValide(QUEST_NB_HEURES,
MIN_HEURES, MAX_HEURES);
this.setNbHeures(NbHeuresInternet);
}
/**
* Redéfinition de la méthode qui calcule et retourne le prix total de la
* chambre.
*/
@Override
public double calculerPrixTotal() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
return (this.getNbHeures() * PRIX_INTERNET) + super.calculerPrixTotal();
}
/**
* Méthode statique qui affiche les tarifs de base de la chambre.
*/
public static void afficherTarifsBase() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
System.out.println("Prix pour l'accès à Internet : \t"
+ OutilsAffichage.formaterMonetaire(PRIX_INTERNET, 2)
+ " de l'heure");
}
}
|
ISO-8859-1
|
Java
| 3,472 |
java
|
ChambreInternet.java
|
Java
|
[
{
"context": "/**\r\n * Auteurs : François MATHIEU et Soti\r\n * Fichier : ChambreInternet.java\r\n * Co",
"end": 34,
"score": 0.9998756647109985,
"start": 18,
"tag": "NAME",
"value": "François MATHIEU"
},
{
"context": "/**\r\n * Auteurs : François MATHIEU et Soti\r\n * Fichier : ChambreInternet.java\r\n * Cours : ",
"end": 42,
"score": 0.9998010396957397,
"start": 38,
"tag": "NAME",
"value": "Soti"
}
] | null |
[] |
/**
* Auteurs : <NAME> et Soti
* Fichier : ChambreInternet.java
* Cours : 420-165-MO (TP4, Hôtel)
* Date : 15 avril 2015
*/
// Package du programmeur.
import outilsjava.*;
/**
* La classe ChambreInternet hérite de la classe ChambreStandard.
*
* La classe ChambreInternet contient les informations et les méthodes
* supplémentaires pour une chambre de l'hôtel qui a un accès à Internet.
*/
public class ChambreInternet extends ChambreStandard {
// Constantes de la classe ChambreInternet.
// Peut accéder à Internet entre 0 et 744 heures (31 jours * 24 heures).
public static final double MIN_HEURES = 0;
public static final double MAX_HEURES = ChambreStandard.MAX_JOURS * 24;
// L'accès Internet coûte 0.50 $ de l'heure.
public static final double PRIX_INTERNET = 0.50;
// Champ d'instance privé de la classe ChambreInternet.
private double nbHeures; // Nombre d'heures pour l'accès Internet.
/**
* Constructeur de la classe ChambreInternet pour construire une chambre à
* accès Internet de base. Au début, aucun accès à Internet.
*/
public ChambreInternet() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
this.initialiserChambre();
}
/**
* Redéfinition de la méthode qui permet d'initialiser une chambre.
*/
@Override
public void initialiserChambre() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
super.initialiserChambre();
this.setNbHeures(0);
}
/**
* Méthode accesseur qui retourne le nombre d'heures d'accès à Internet.
*
* @return Le nombre d'heures d'accès à Internet.
*/
public double getNbHeures() {
return this.nbHeures;
}
/**
* Méthode mutateur qui modifie le nombre d'heures d'accès à Internet avec
* celui reçu en paramètre.
*
* @param nbHeures
* Le nombre d'heures d'accès à Internet.
*/
public void setNbHeures(double nbHeures) {
if (this.nbHeures >= ChambreInternet.MIN_HEURES
&& this.nbHeures <= ChambreInternet.MAX_HEURES) {
this.nbHeures = nbHeures;
}
}
/**
* Redéfinition de la méthode qui lit les informations de départ pour la
* chambre (lorsque le client quitte).
*/
@Override
public void lireInfosDepart() {
final String QUEST_NB_HEURES = "\nEntrez le nombre d'heures d'accès"
+ " à Internet (entre " + ChambreInternet.MIN_HEURES + " et "
+ ChambreInternet.MAX_HEURES + ") : ";
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
super.lireInfosDepart();
double NbHeuresInternet = OutilsLecture.lireReelValide(QUEST_NB_HEURES,
MIN_HEURES, MAX_HEURES);
this.setNbHeures(NbHeuresInternet);
}
/**
* Redéfinition de la méthode qui calcule et retourne le prix total de la
* chambre.
*/
@Override
public double calculerPrixTotal() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
return (this.getNbHeures() * PRIX_INTERNET) + super.calculerPrixTotal();
}
/**
* Méthode statique qui affiche les tarifs de base de la chambre.
*/
public static void afficherTarifsBase() {
/*
* TODO (À COMPLÉTER). Voir page 7 de l'énoncé du TP4.
*/
System.out.println("Prix pour l'accès à Internet : \t"
+ OutilsAffichage.formaterMonetaire(PRIX_INTERNET, 2)
+ " de l'heure");
}
}
| 3,461 | 0.655617 | 0.643297 | 139 | 22.539568 | 25.741455 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.129496 | false | false |
10
|
0aa5c292a93d1481b7c93be9c0f239d1f6c92c03
| 17,145,509,474,209 |
d249386128e8958e8773610b2e3e7a03397b62e4
|
/playgrounds/jbischoff/src/main/java/playground/jbischoff/taxi/optimizer/rank/IdleRankVehicleFinder.java
|
26c9805bca0987aa1f884e277982ba4fc96443d0
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
lizethheredia/matsim_paralelos
|
https://github.com/lizethheredia/matsim_paralelos
|
5899c909525b7bfad3abf2194b358625a37706fd
|
aa52f41d4fe923066ac01707443604ebacdfd19a
|
refs/heads/master
| 2018-01-10T03:31:06.003000 | 2015-11-20T16:08:20 | 2015-11-20T16:10:46 | 46,580,756 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/* *********************************************************************** *
* project: org.matsim.*
* *
* *********************************************************************** *
* *
* copyright : (C) 2012 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package playground.jbischoff.taxi.optimizer.rank;
import java.util.*;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.network.Link;
import org.matsim.contrib.dvrp.MatsimVrpContext;
import org.matsim.contrib.dvrp.data.Vehicle;
import org.matsim.contrib.dvrp.util.*;
import org.matsim.contrib.util.DistanceUtils;
import playground.jbischoff.energy.charging.taxi.ElectricTaxiChargingHandler;
import playground.jbischoff.taxi.vehicles.ElectricTaxi;
import playground.michalm.taxi.data.TaxiRequest;
import playground.michalm.taxi.optimizer.filter.VehicleFilter;
import playground.michalm.taxi.scheduler.*;
import com.google.common.collect.*;
/**
* @author jbischoff
*/
public class IdleRankVehicleFinder
implements VehicleFilter
{
private final MatsimVrpContext context;
private final TaxiScheduler scheduler;
private ElectricTaxiChargingHandler ecabHandler;
private boolean IsElectric;
private boolean useChargeOverTime;
private boolean includeDriversWill = false;
Random rnd;
private static double MINIMUM_SOC_FOR_DISPATCH = 0.25;
public IdleRankVehicleFinder(MatsimVrpContext context, TaxiScheduler scheduler)
{
this.context = context;
this.scheduler = scheduler;
this.IsElectric = false;
this.useChargeOverTime = false;
this.rnd = new Random(7);
System.out.println("Using distance measure: Straight line");
}
public void addEcabHandler(ElectricTaxiChargingHandler ecabHandler)
{
this.ecabHandler = ecabHandler;
this.IsElectric = true;
}
public void setUseChargeOverTime(boolean useChargeOverDistance)
{
this.useChargeOverTime = useChargeOverDistance;
}
private boolean hasEnoughCapacityForTask(Vehicle veh)
{
return (getVehicleSoc(veh) > MINIMUM_SOC_FOR_DISPATCH);
}
private double getVehicleSoc(Vehicle veh)
{
return this.ecabHandler.getRelativeTaxiSoC(Id.create(veh.getId(), ElectricTaxi.class));
}
public Vehicle findVehicleForRequest(Iterable<Vehicle> vehicles, TaxiRequest request)
{
if (this.useChargeOverTime) {
// return findHighestChargedIdleVehicleDistanceSort(request);
return findBestChargedVehicle(request);
// return findHighestChargedIdleVehicle(request);
}
else
return findClosestFIFOVehicle(request);
}
@Override
public Iterable<Vehicle> filterVehiclesForRequest(Iterable<Vehicle> vehicles,
TaxiRequest request)
{
return Lists.newArrayList(findVehicleForRequest(vehicles, request));
}
private Vehicle findBestChargedVehicle(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestDistance = 1e9;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : vehicles) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (this.IsElectric) {
if (this.getVehicleSoc(veh) > this.getVehicleSoc(bestVeh)) {
bestVeh = veh;
}
}
//higher charge, if distance is equal
}
}
return bestVeh;
}
private Vehicle findHighestChargedIdleVehicle(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestSoc = 0;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double soc = this.getVehicleSoc(veh);
if (soc > bestSoc) {
bestSoc = soc;
bestVeh = veh;
}
}
return bestVeh;
}
private Vehicle findHighestChargedIdleVehicleDistanceSort(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestSoc = 0;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double soc = this.getVehicleSoc(veh);
if (soc > bestSoc) {
bestSoc = soc;
bestVeh = veh;
}
else if (soc == bestSoc) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (this.calculateSquaredDistance(req, veh) < this.calculateSquaredDistance(req,
bestVeh)) {
bestVeh = veh;
}
}
}
return bestVeh;
}
private Vehicle findClosestFIFOVehicle(TaxiRequest req)
{
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
Vehicle bestVeh = null;
// double bestDistance = Double.MAX_VALUE;
double bestDistance = Double.MAX_VALUE / 2;
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (veh.getSchedule().getCurrentTask().getBeginTime() < bestVeh.getSchedule()
.getCurrentTask().getBeginTime())
bestVeh = veh;
//FIFO, if distance is equal
}
}
return bestVeh;
}
private Vehicle findClosestWillingVehicle(TaxiRequest req)
{
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
Vehicle bestVeh = null;
// double bestDistance = Double.MAX_VALUE;
double bestDistance = Double.MAX_VALUE / 2;
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
if (!vehicleWillingToServeRequest(veh, req))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (veh.getSchedule().getCurrentTask().getBeginTime() < bestVeh.getSchedule()
.getCurrentTask().getBeginTime())
bestVeh = veh;
//FIFO, if distance is equal
}
}
return bestVeh;
}
/**
*
*/
private boolean vehicleWillingToServeRequest(Vehicle veh, TaxiRequest req)
{
return true;
}
private double calculateSquaredDistance(TaxiRequest req, Vehicle veh)
{
LinkTimePair departure = scheduler.getEarliestIdleness(veh);
Link fromLink;
if (departure == null) {
return Double.MAX_VALUE;
}
fromLink = departure.link;
// from means here the request's from, to is therefore the taxis destination to pick up customer (just a reminder for myself)
Link toLink = req.getFromLink();
return DistanceUtils.calculateSquaredDistance(fromLink, toLink);
}
}
|
UTF-8
|
Java
| 10,457 |
java
|
IdleRankVehicleFinder.java
|
Java
|
[
{
"context": " com.google.common.collect.*;\r\n\r\n\r\n/**\r\n * @author jbischoff\r\n */\r\n\r\npublic class IdleRankVehicleFinder\r\n i",
"end": 2061,
"score": 0.9994698166847229,
"start": 2052,
"tag": "USERNAME",
"value": "jbischoff"
}
] | null |
[] |
/* *********************************************************************** *
* project: org.matsim.*
* *
* *********************************************************************** *
* *
* copyright : (C) 2012 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package playground.jbischoff.taxi.optimizer.rank;
import java.util.*;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.network.Link;
import org.matsim.contrib.dvrp.MatsimVrpContext;
import org.matsim.contrib.dvrp.data.Vehicle;
import org.matsim.contrib.dvrp.util.*;
import org.matsim.contrib.util.DistanceUtils;
import playground.jbischoff.energy.charging.taxi.ElectricTaxiChargingHandler;
import playground.jbischoff.taxi.vehicles.ElectricTaxi;
import playground.michalm.taxi.data.TaxiRequest;
import playground.michalm.taxi.optimizer.filter.VehicleFilter;
import playground.michalm.taxi.scheduler.*;
import com.google.common.collect.*;
/**
* @author jbischoff
*/
public class IdleRankVehicleFinder
implements VehicleFilter
{
private final MatsimVrpContext context;
private final TaxiScheduler scheduler;
private ElectricTaxiChargingHandler ecabHandler;
private boolean IsElectric;
private boolean useChargeOverTime;
private boolean includeDriversWill = false;
Random rnd;
private static double MINIMUM_SOC_FOR_DISPATCH = 0.25;
public IdleRankVehicleFinder(MatsimVrpContext context, TaxiScheduler scheduler)
{
this.context = context;
this.scheduler = scheduler;
this.IsElectric = false;
this.useChargeOverTime = false;
this.rnd = new Random(7);
System.out.println("Using distance measure: Straight line");
}
public void addEcabHandler(ElectricTaxiChargingHandler ecabHandler)
{
this.ecabHandler = ecabHandler;
this.IsElectric = true;
}
public void setUseChargeOverTime(boolean useChargeOverDistance)
{
this.useChargeOverTime = useChargeOverDistance;
}
private boolean hasEnoughCapacityForTask(Vehicle veh)
{
return (getVehicleSoc(veh) > MINIMUM_SOC_FOR_DISPATCH);
}
private double getVehicleSoc(Vehicle veh)
{
return this.ecabHandler.getRelativeTaxiSoC(Id.create(veh.getId(), ElectricTaxi.class));
}
public Vehicle findVehicleForRequest(Iterable<Vehicle> vehicles, TaxiRequest request)
{
if (this.useChargeOverTime) {
// return findHighestChargedIdleVehicleDistanceSort(request);
return findBestChargedVehicle(request);
// return findHighestChargedIdleVehicle(request);
}
else
return findClosestFIFOVehicle(request);
}
@Override
public Iterable<Vehicle> filterVehiclesForRequest(Iterable<Vehicle> vehicles,
TaxiRequest request)
{
return Lists.newArrayList(findVehicleForRequest(vehicles, request));
}
private Vehicle findBestChargedVehicle(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestDistance = 1e9;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : vehicles) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (this.IsElectric) {
if (this.getVehicleSoc(veh) > this.getVehicleSoc(bestVeh)) {
bestVeh = veh;
}
}
//higher charge, if distance is equal
}
}
return bestVeh;
}
private Vehicle findHighestChargedIdleVehicle(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestSoc = 0;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double soc = this.getVehicleSoc(veh);
if (soc > bestSoc) {
bestSoc = soc;
bestVeh = veh;
}
}
return bestVeh;
}
private Vehicle findHighestChargedIdleVehicleDistanceSort(TaxiRequest req)
{
Vehicle bestVeh = null;
double bestSoc = 0;
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double soc = this.getVehicleSoc(veh);
if (soc > bestSoc) {
bestSoc = soc;
bestVeh = veh;
}
else if (soc == bestSoc) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (this.calculateSquaredDistance(req, veh) < this.calculateSquaredDistance(req,
bestVeh)) {
bestVeh = veh;
}
}
}
return bestVeh;
}
private Vehicle findClosestFIFOVehicle(TaxiRequest req)
{
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
Vehicle bestVeh = null;
// double bestDistance = Double.MAX_VALUE;
double bestDistance = Double.MAX_VALUE / 2;
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (veh.getSchedule().getCurrentTask().getBeginTime() < bestVeh.getSchedule()
.getCurrentTask().getBeginTime())
bestVeh = veh;
//FIFO, if distance is equal
}
}
return bestVeh;
}
private Vehicle findClosestWillingVehicle(TaxiRequest req)
{
List<Vehicle> vehicles = new ArrayList<Vehicle>(context.getVrpData().getVehicles().values());
Collections.shuffle(vehicles, rnd);
Vehicle bestVeh = null;
// double bestDistance = Double.MAX_VALUE;
double bestDistance = Double.MAX_VALUE / 2;
for (Vehicle veh : Iterables.filter(vehicles, TaxiSchedulerUtils.createIsIdle(scheduler))) {
if (this.IsElectric)
if (!this.hasEnoughCapacityForTask(veh))
continue;
if (!vehicleWillingToServeRequest(veh, req))
continue;
double distance = calculateSquaredDistance(req, veh);
if (distance < bestDistance) {
bestDistance = distance;
bestVeh = veh;
}
else if (distance == bestDistance) {
if (bestVeh == null) {
bestVeh = veh;
continue;
}
if (veh.getSchedule().getCurrentTask().getBeginTime() < bestVeh.getSchedule()
.getCurrentTask().getBeginTime())
bestVeh = veh;
//FIFO, if distance is equal
}
}
return bestVeh;
}
/**
*
*/
private boolean vehicleWillingToServeRequest(Vehicle veh, TaxiRequest req)
{
return true;
}
private double calculateSquaredDistance(TaxiRequest req, Vehicle veh)
{
LinkTimePair departure = scheduler.getEarliestIdleness(veh);
Link fromLink;
if (departure == null) {
return Double.MAX_VALUE;
}
fromLink = departure.link;
// from means here the request's from, to is therefore the taxis destination to pick up customer (just a reminder for myself)
Link toLink = req.getFromLink();
return DistanceUtils.calculateSquaredDistance(fromLink, toLink);
}
}
| 10,457 | 0.526729 | 0.524912 | 310 | 31.732258 | 29.006271 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46129 | false | false |
10
|
a99ac8e3e3bd2c3d58104c8c96aca63359d4afcf
| 20,684,562,545,789 |
f216f7da5a0a4f4f1ade45bb7811576037210162
|
/src/main/java/cw_03/ScannerTest.java
|
5097b6f238dd33b8f60126e2c938e2a9c3c492f7
|
[] |
no_license
|
Eugene1992/java-starter-19
|
https://github.com/Eugene1992/java-starter-19
|
440f7cb867ebfededb8715389e3dcb0f910a4b7f
|
8ffa6f0bfc077b1dece1116acd5d0d048a836fa0
|
refs/heads/master
| 2020-12-30T15:08:30.043000 | 2017-07-06T17:24:25 | 2017-07-06T17:24:25 | 91,109,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cw_03;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
String s = scan.next();
System.out.println(i);
System.out.println(s);
}
}
|
UTF-8
|
Java
| 298 |
java
|
ScannerTest.java
|
Java
|
[] | null |
[] |
package cw_03;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
String s = scan.next();
System.out.println(i);
System.out.println(s);
}
}
| 298 | 0.59396 | 0.587248 | 15 | 18.866667 | 16.243425 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false |
10
|
df7ddd057205370f50881788b499ff3dea9f350a
| 26,405,458,939,822 |
1792068ab7478b0cf793b78a80f454114e86cdf9
|
/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/connect/mirror/ReferenceNodeStore.java
|
485051e8aa068345de822f960a0e330dda87b950
|
[
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"MIT",
"OFL-1.1"
] |
permissive
|
apache/activemq-artemis
|
https://github.com/apache/activemq-artemis
|
caf9a87a245e0e20e24a981b030e55a81583c421
|
98710fe0320c391631626736291962df3639de7f
|
refs/heads/main
| 2023-09-01T20:39:35.019000 | 2023-09-01T19:26:12 | 2023-09-01T19:26:28 | 36,057,260 | 969 | 1,097 |
Apache-2.0
| false | 2023-09-14T16:42:37 | 2015-05-22T07:00:05 | 2023-09-09T07:43:52 | 2023-09-14T16:42:37 | 91,487 | 878 | 887 | 10 |
Java
| false | false |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.protocol.amqp.connect.mirror;
import java.util.HashMap;
import io.netty.util.collection.LongObjectHashMap;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.utils.collections.NodeStore;
import org.apache.activemq.artemis.utils.collections.LinkedListImpl;
public class ReferenceNodeStore implements NodeStore<MessageReference> {
private final ReferenceIDSupplier idSupplier;
public ReferenceNodeStore(ReferenceIDSupplier idSupplier) {
this.idSupplier = idSupplier;
}
// This is where the messages are stored by server id...
HashMap<String, LongObjectHashMap<LinkedListImpl.Node<MessageReference>>> lists;
String lruListID;
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> lruMap;
@Override
public void storeNode(MessageReference element, LinkedListImpl.Node<MessageReference> node) {
String list = getServerID(element);
long id = getID(element);
storeNode(list, id, node);
}
private void storeNode(String serverID, long id, LinkedListImpl.Node<MessageReference> node) {
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodesMap = getMap(serverID);
if (nodesMap != null) {
synchronized (nodesMap) {
nodesMap.put(id, node);
}
}
}
@Override
public void removeNode(MessageReference element, LinkedListImpl.Node<MessageReference> node) {
long id = getID(element);
String serverID = getServerID(element);
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodeMap = getMap(serverID);
if (nodeMap != null) {
synchronized (nodeMap) {
nodeMap.remove(id);
}
}
}
@Override
public LinkedListImpl.Node<MessageReference> getNode(String serverID, long id) {
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodeMap = getMap(serverID);
assert nodeMap != null;
synchronized (nodeMap) {
return nodeMap.get(id);
}
}
/** notice getMap should always return an instance. It should never return null. */
private synchronized LongObjectHashMap<LinkedListImpl.Node<MessageReference>> getMap(String serverID) {
if (serverID == null) {
serverID = idSupplier.getDefaultNodeID();
}
if (lruListID != null && lruListID.equals(serverID)) {
return lruMap;
}
if (lists == null) {
lists = new HashMap<>();
}
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> theList = lists.get(serverID);
if (theList == null) {
theList = new LongObjectHashMap<>();
lists.put(serverID, theList);
}
lruMap = theList; // cached result
lruListID = serverID;
return theList;
}
public String getServerID(MessageReference element) {
return idSupplier.getServerID(element);
}
public String getServerID(Message message) {
return idSupplier.getServerID(message);
}
public long getID(MessageReference element) {
return idSupplier.getID(element);
}
@Override
public synchronized void clear() {
lists.forEach((k, v) -> v.clear());
lists.clear();
lruListID = null;
lruMap = null;
}
@Override
public int size() {
int size = 0;
for (LongObjectHashMap mapValue : lists.values()) {
size += mapValue.size();
}
return size;
}
}
|
UTF-8
|
Java
| 4,314 |
java
|
ReferenceNodeStore.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.protocol.amqp.connect.mirror;
import java.util.HashMap;
import io.netty.util.collection.LongObjectHashMap;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.utils.collections.NodeStore;
import org.apache.activemq.artemis.utils.collections.LinkedListImpl;
public class ReferenceNodeStore implements NodeStore<MessageReference> {
private final ReferenceIDSupplier idSupplier;
public ReferenceNodeStore(ReferenceIDSupplier idSupplier) {
this.idSupplier = idSupplier;
}
// This is where the messages are stored by server id...
HashMap<String, LongObjectHashMap<LinkedListImpl.Node<MessageReference>>> lists;
String lruListID;
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> lruMap;
@Override
public void storeNode(MessageReference element, LinkedListImpl.Node<MessageReference> node) {
String list = getServerID(element);
long id = getID(element);
storeNode(list, id, node);
}
private void storeNode(String serverID, long id, LinkedListImpl.Node<MessageReference> node) {
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodesMap = getMap(serverID);
if (nodesMap != null) {
synchronized (nodesMap) {
nodesMap.put(id, node);
}
}
}
@Override
public void removeNode(MessageReference element, LinkedListImpl.Node<MessageReference> node) {
long id = getID(element);
String serverID = getServerID(element);
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodeMap = getMap(serverID);
if (nodeMap != null) {
synchronized (nodeMap) {
nodeMap.remove(id);
}
}
}
@Override
public LinkedListImpl.Node<MessageReference> getNode(String serverID, long id) {
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> nodeMap = getMap(serverID);
assert nodeMap != null;
synchronized (nodeMap) {
return nodeMap.get(id);
}
}
/** notice getMap should always return an instance. It should never return null. */
private synchronized LongObjectHashMap<LinkedListImpl.Node<MessageReference>> getMap(String serverID) {
if (serverID == null) {
serverID = idSupplier.getDefaultNodeID();
}
if (lruListID != null && lruListID.equals(serverID)) {
return lruMap;
}
if (lists == null) {
lists = new HashMap<>();
}
LongObjectHashMap<LinkedListImpl.Node<MessageReference>> theList = lists.get(serverID);
if (theList == null) {
theList = new LongObjectHashMap<>();
lists.put(serverID, theList);
}
lruMap = theList; // cached result
lruListID = serverID;
return theList;
}
public String getServerID(MessageReference element) {
return idSupplier.getServerID(element);
}
public String getServerID(Message message) {
return idSupplier.getServerID(message);
}
public long getID(MessageReference element) {
return idSupplier.getID(element);
}
@Override
public synchronized void clear() {
lists.forEach((k, v) -> v.clear());
lists.clear();
lruListID = null;
lruMap = null;
}
@Override
public int size() {
int size = 0;
for (LongObjectHashMap mapValue : lists.values()) {
size += mapValue.size();
}
return size;
}
}
| 4,314 | 0.69286 | 0.691701 | 134 | 31.201492 | 29.330027 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440298 | false | false |
10
|
8c588aa3cd6c686e430de6efff3c958f7fd021f6
| 29,420,526,028,171 |
ffab3edaf2717c75bde658dc2079edaa92452ebf
|
/bhmc-dms/bhmc-dms-mob/src/main/java/chn/bhmc/dms/mob/api/sales/service/SalesViewMappingService.java
|
b05b04cabe8a5d7d2ef5fd349f39cce03b6b8a63
|
[] |
no_license
|
wangchen910312/test1
|
https://github.com/wangchen910312/test1
|
8a7a391179c5ac130f123861fd19d8997fc064ab
|
1fefce87165b58bd16938927a1ae5c1cc256c175
|
refs/heads/master
| 2022-07-29T06:57:49.950000 | 2021-05-20T08:29:49 | 2021-05-20T08:29:49 | 224,800,223 | 0 | 2 | null | false | 2022-07-15T21:05:20 | 2019-11-29T07:29:01 | 2021-05-20T08:29:55 | 2022-07-15T21:05:18 | 292,303 | 0 | 1 | 3 |
Java
| false | false |
package chn.bhmc.dms.mob.api.sales.service;
/**
* <pre>
* 화면-사용자/직무/부서 매핑 서비스
* </pre>
*
* @ClassName : ViewMappingService.java
* @Description : 클래스 설명을 기술합니다.
* @author Kang Seok Han
* @since 2016. 8. 9.
* @version 1.0
* @see
* @Modification Information
* <pre>
* since author description
* =========== ============= ===========================
* 2016. 8. 9. Kang Seok Han 최초 생성
* </pre>
*/
public interface SalesViewMappingService {
/**
* 화면-사용자/직무/부서 매핑 목록에서 주어진 조건을 만족하는 권한이 있는지 여부를 조회한다.
* @param sysCd 시스템구분
* @param viewId 화면ID
* @param refTp 참조유형 사용자(U), 직무(T), 부서(D)
* @param refId 참조값 사용자/직무/부서
* @param permissionNames 퍼미션 ex) "READ,SEARCHIND,SEARCHALL"
* @return
* @throws Exception
*/
public boolean hasPermission(String sysCd, String viewId, String refTp, String refId, String permissionNames) throws Exception;
}
|
UTF-8
|
Java
| 1,141 |
java
|
SalesViewMappingService.java
|
Java
|
[
{
"context": "e.java\n * @Description : 클래스 설명을 기술합니다.\n * @author Kang Seok Han\n * @since 2016. 8. 9.\n * @version 1.0\n * @see\n * ",
"end": 193,
"score": 0.9999011158943176,
"start": 180,
"tag": "NAME",
"value": "Kang Seok Han"
},
{
"context": " ===========================\n * 2016. 8. 9. Kang Seok Han 최초 생성\n * </pre>\n */\n\npublic interface SalesVi",
"end": 429,
"score": 0.9998882412910461,
"start": 416,
"tag": "NAME",
"value": "Kang Seok Han"
}
] | null |
[] |
package chn.bhmc.dms.mob.api.sales.service;
/**
* <pre>
* 화면-사용자/직무/부서 매핑 서비스
* </pre>
*
* @ClassName : ViewMappingService.java
* @Description : 클래스 설명을 기술합니다.
* @author <NAME>
* @since 2016. 8. 9.
* @version 1.0
* @see
* @Modification Information
* <pre>
* since author description
* =========== ============= ===========================
* 2016. 8. 9. <NAME> 최초 생성
* </pre>
*/
public interface SalesViewMappingService {
/**
* 화면-사용자/직무/부서 매핑 목록에서 주어진 조건을 만족하는 권한이 있는지 여부를 조회한다.
* @param sysCd 시스템구분
* @param viewId 화면ID
* @param refTp 참조유형 사용자(U), 직무(T), 부서(D)
* @param refId 참조값 사용자/직무/부서
* @param permissionNames 퍼미션 ex) "READ,SEARCHIND,SEARCHALL"
* @return
* @throws Exception
*/
public boolean hasPermission(String sysCd, String viewId, String refTp, String refId, String permissionNames) throws Exception;
}
| 1,127 | 0.57672 | 0.561905 | 35 | 26 | 26.192692 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
41ac60241fdbe2ee75c15983e7d182eca325550a
| 21,543,555,967,504 |
9b5605e0694437f5b99692aabce78a55d652c424
|
/src/main/java/com/grey/ssm/wechat/web/LoginController.java
|
cd1b0944598ed3944df2969cef641bb39299d3f5
|
[] |
no_license
|
idejie/we-ssm
|
https://github.com/idejie/we-ssm
|
a39c3b5ec756790bfe3ffc9a8fb651052030b907
|
bda31badaefb58a4d2dc16fbe418ddf897b4c5a2
|
refs/heads/master
| 2022-03-10T12:51:20.714000 | 2019-08-02T07:35:27 | 2019-08-02T07:35:27 | 125,089,234 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.grey.ssm.wechat.web;
import com.grey.ssm.wechat.model.User;
import com.grey.ssm.wechat.service.LoginService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.SoundbankResource;
import javax.xml.bind.SchemaOutputResolver;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping("/")
public class LoginController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private LoginService loginService;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat formatD = new SimpleDateFormat("yyyy-MM-dd");
//首页
@RequestMapping(value = "/home")
private void Home(HttpServletRequest req, HttpServletResponse res)throws Exception{
String s = format.format(new Date()) + ": visit home once";
System.out.println(s);
logger.info(s);
req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req,res);
}
//登录get
@RequestMapping(value = "/login",method = RequestMethod.GET)
private void LoginGetter(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
String s = format.format(new Date()) + ": visit login once";
System.out.println(s);
logger.info(s);
User user = (User) session.getAttribute("user");
req.setAttribute("user",user);
session.setAttribute("re_url",session.getAttribute("re_url"));
req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,res);
}
//error
@RequestMapping(value = "/error",method = RequestMethod.GET)
private void error(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
req.setAttribute("error",session.getAttribute("error"));
session.setAttribute("error",null);
req.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(req,res);
}
//error
@RequestMapping(value = "/success",method = RequestMethod.GET)
private void success(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
req.setAttribute("success",session.getAttribute("success"));
session.setAttribute("success",null);
req.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(req,res);
}
//登录POST
@RequestMapping(value = "/login",method = RequestMethod.POST)
private void LoginPoster(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
int UID = Integer.parseInt(req.getParameter("UID"));
String passWord = req.getParameter("passWord");
User user = loginService.validateUID(UID);
if (user == null){
try {
User addUser = new User();
addUser.setUID(UID);
addUser.setPassWord(passWord);
int code = loginService.SignUp(addUser);
if(code == 0){
session.setAttribute("user",addUser);
req.setAttribute("user", addUser);
res.sendRedirect("/profile");
}else {
logger.error("insert user fail:"+addUser.toString());
}
}catch (Exception e){
logger.error(e.toString());
}
}else {
if (user.getPassWord().equals(passWord)){
logger.info(user.toString());
session.setAttribute("user",user);
req.setAttribute("user",user);
String re_url = (String) session.getAttribute("re_url");
System.out.println("#####"+re_url);
if (re_url == null){
res.sendRedirect("/profile");
}else {
session.setAttribute("re_url",null);
res.sendRedirect(re_url);
}
}else {
req.setAttribute("error","密码错误");
res.sendRedirect("/error");
}
}
}
//profile 页
@RequestMapping(value = "/profile",method = RequestMethod.GET)
private void profilePage(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile");
res.sendRedirect("/login");
}else {
System.out.println("sssssssssssssssssssssssssss");
req.getRequestDispatcher("/WEB-INF/jsp/profile.jsp").forward(req,res);
}
}
//profile_update 页
@RequestMapping(value = "/profile_update",method = RequestMethod.GET)
private void profileUpPage(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile_update");
res.sendRedirect("/login");
}else {
System.out.println("sssssssssssssssssssssssssss");
req.getRequestDispatcher("/WEB-INF/jsp/profile_update.jsp").forward(req,res);
}
}
//profile_update 页
@RequestMapping(value = "/profile_update",method = RequestMethod.POST)
private void profileUp(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile_update");
res.sendRedirect("/login");
}else {
String nickName = req.getParameter("nickName");
String userName = req.getParameter("userName");
int sex = Integer.parseInt(req.getParameter("sex"));
System.out.println("sex" +sex );
int age = Integer.parseInt(req.getParameter("age"));
String email = req.getParameter("email");
String tele = req.getParameter("tele");
String moto = req.getParameter("moto");
System.out.println("seweqweqwex" +moto );
String aboutLove = req.getParameter("aboutLove");
String homeTown = req.getParameter("homeTown");
String profession = req.getParameter("profession");
int zodiac = Integer.parseInt(req.getParameter("zodiacSign"));
String company = req.getParameter("company");
int cons = Integer.parseInt(req.getParameter("constellation"));
Date birth = formatD.parse( req.getParameter("birthday"));
String bloodCate = req.getParameter("bloodCate");
String nowLiveAt = req.getParameter("nowLiveAt");
loginService.updateProfile(user.getUID(),nickName,userName,sex,age,email,tele,moto,aboutLove,homeTown,profession
,zodiac,company,cons,birth,bloodCate,nowLiveAt);
res.sendRedirect("/profile");
}
}
}
|
UTF-8
|
Java
| 7,845 |
java
|
LoginController.java
|
Java
|
[
{
"context": "tribute(\"user\");\n req.setAttribute(\"user\",user);\n session.setAttribute(\"re_url\",session.",
"end": 2102,
"score": 0.9406017661094666,
"start": 2098,
"tag": "USERNAME",
"value": "user"
},
{
"context": "eq.getParameter(\"UID\"));\n String passWord = req.getParameter(\"passWord\");\n User user = log",
"end": 3401,
"score": 0.7935665845870972,
"start": 3398,
"tag": "PASSWORD",
"value": "req"
},
{
"context": "D\"));\n String passWord = req.getParameter(\"passWord\");\n User user = loginService.validateUID(U",
"end": 3424,
"score": 0.6014043092727661,
"start": 3416,
"tag": "PASSWORD",
"value": "passWord"
},
{
"context": ";\n String userName = req.getParameter(\"userName\");\n\n int sex = Integer.parseInt(req.ge",
"end": 6581,
"score": 0.9289183616638184,
"start": 6573,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " loginService.updateProfile(user.getUID(),nickName,userName,sex,age,email,tele,moto,aboutLove,ho",
"end": 7625,
"score": 0.7164629697799683,
"start": 7621,
"tag": "NAME",
"value": "nick"
},
{
"context": " loginService.updateProfile(user.getUID(),nickName,userName,sex,age,email,tele,moto,aboutLove,homeTo",
"end": 7629,
"score": 0.5940861105918884,
"start": 7625,
"tag": "USERNAME",
"value": "Name"
},
{
"context": "loginService.updateProfile(user.getUID(),nickName,userName,sex,age,email,tele,moto,aboutLove,homeTown,profes",
"end": 7638,
"score": 0.9869211316108704,
"start": 7630,
"tag": "USERNAME",
"value": "userName"
}
] | null |
[] |
package com.grey.ssm.wechat.web;
import com.grey.ssm.wechat.model.User;
import com.grey.ssm.wechat.service.LoginService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.SoundbankResource;
import javax.xml.bind.SchemaOutputResolver;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping("/")
public class LoginController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private LoginService loginService;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat formatD = new SimpleDateFormat("yyyy-MM-dd");
//首页
@RequestMapping(value = "/home")
private void Home(HttpServletRequest req, HttpServletResponse res)throws Exception{
String s = format.format(new Date()) + ": visit home once";
System.out.println(s);
logger.info(s);
req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req,res);
}
//登录get
@RequestMapping(value = "/login",method = RequestMethod.GET)
private void LoginGetter(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
String s = format.format(new Date()) + ": visit login once";
System.out.println(s);
logger.info(s);
User user = (User) session.getAttribute("user");
req.setAttribute("user",user);
session.setAttribute("re_url",session.getAttribute("re_url"));
req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,res);
}
//error
@RequestMapping(value = "/error",method = RequestMethod.GET)
private void error(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
req.setAttribute("error",session.getAttribute("error"));
session.setAttribute("error",null);
req.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(req,res);
}
//error
@RequestMapping(value = "/success",method = RequestMethod.GET)
private void success(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
req.setAttribute("success",session.getAttribute("success"));
session.setAttribute("success",null);
req.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(req,res);
}
//登录POST
@RequestMapping(value = "/login",method = RequestMethod.POST)
private void LoginPoster(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
int UID = Integer.parseInt(req.getParameter("UID"));
String passWord = req.getParameter("<PASSWORD>");
User user = loginService.validateUID(UID);
if (user == null){
try {
User addUser = new User();
addUser.setUID(UID);
addUser.setPassWord(passWord);
int code = loginService.SignUp(addUser);
if(code == 0){
session.setAttribute("user",addUser);
req.setAttribute("user", addUser);
res.sendRedirect("/profile");
}else {
logger.error("insert user fail:"+addUser.toString());
}
}catch (Exception e){
logger.error(e.toString());
}
}else {
if (user.getPassWord().equals(passWord)){
logger.info(user.toString());
session.setAttribute("user",user);
req.setAttribute("user",user);
String re_url = (String) session.getAttribute("re_url");
System.out.println("#####"+re_url);
if (re_url == null){
res.sendRedirect("/profile");
}else {
session.setAttribute("re_url",null);
res.sendRedirect(re_url);
}
}else {
req.setAttribute("error","密码错误");
res.sendRedirect("/error");
}
}
}
//profile 页
@RequestMapping(value = "/profile",method = RequestMethod.GET)
private void profilePage(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile");
res.sendRedirect("/login");
}else {
System.out.println("sssssssssssssssssssssssssss");
req.getRequestDispatcher("/WEB-INF/jsp/profile.jsp").forward(req,res);
}
}
//profile_update 页
@RequestMapping(value = "/profile_update",method = RequestMethod.GET)
private void profileUpPage(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile_update");
res.sendRedirect("/login");
}else {
System.out.println("sssssssssssssssssssssssssss");
req.getRequestDispatcher("/WEB-INF/jsp/profile_update.jsp").forward(req,res);
}
}
//profile_update 页
@RequestMapping(value = "/profile_update",method = RequestMethod.POST)
private void profileUp(HttpServletRequest req, HttpServletResponse res) throws Exception{
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
if(user ==null){
session.setAttribute("re_url","/profile_update");
res.sendRedirect("/login");
}else {
String nickName = req.getParameter("nickName");
String userName = req.getParameter("userName");
int sex = Integer.parseInt(req.getParameter("sex"));
System.out.println("sex" +sex );
int age = Integer.parseInt(req.getParameter("age"));
String email = req.getParameter("email");
String tele = req.getParameter("tele");
String moto = req.getParameter("moto");
System.out.println("seweqweqwex" +moto );
String aboutLove = req.getParameter("aboutLove");
String homeTown = req.getParameter("homeTown");
String profession = req.getParameter("profession");
int zodiac = Integer.parseInt(req.getParameter("zodiacSign"));
String company = req.getParameter("company");
int cons = Integer.parseInt(req.getParameter("constellation"));
Date birth = formatD.parse( req.getParameter("birthday"));
String bloodCate = req.getParameter("bloodCate");
String nowLiveAt = req.getParameter("nowLiveAt");
loginService.updateProfile(user.getUID(),nickName,userName,sex,age,email,tele,moto,aboutLove,homeTown,profession
,zodiac,company,cons,birth,bloodCate,nowLiveAt);
res.sendRedirect("/profile");
}
}
}
| 7,847 | 0.636782 | 0.636398 | 177 | 43.17514 | 25.505907 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.892655 | false | false |
10
|
a14e8379ea9d1de89a185a9390d25cf01c759e66
| 21,543,555,969,347 |
4abbf5da7a9e58d34050d0e88ad5f135d3071f44
|
/src/main/java/com/example/demo/dao/OutilRepository.java
|
e247f50e3302058c95af36b7892eb97980e121e3
|
[] |
no_license
|
youssefM95/laboratoire-spring
|
https://github.com/youssefM95/laboratoire-spring
|
c187f89dac70b37dd40988462b4c22cff5563889
|
a3ab078cd2fcca3321862afcf3c75c3b58cff521
|
refs/heads/master
| 2020-09-17T05:04:27.176000 | 2020-01-14T15:24:50 | 2020-01-14T15:24:50 | 223,998,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.demo.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entities.Outil;
public interface OutilRepository extends JpaRepository<Outil, Long> {
List<Outil> findAll();
List<Outil> findByNom(String cin);
List<Outil> findByNomStartingWith(String caractere);
List<Outil> findBySource(String source);
List<Outil> findByDate(Date date);
}
|
UTF-8
|
Java
| 448 |
java
|
OutilRepository.java
|
Java
|
[] | null |
[] |
package com.example.demo.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entities.Outil;
public interface OutilRepository extends JpaRepository<Outil, Long> {
List<Outil> findAll();
List<Outil> findByNom(String cin);
List<Outil> findByNomStartingWith(String caractere);
List<Outil> findBySource(String source);
List<Outil> findByDate(Date date);
}
| 448 | 0.790179 | 0.790179 | 17 | 25.352942 | 22.170307 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
10
|
710dc60d626f655595e7218f3a41b1478e9d3f74
| 9,345,848,894,938 |
945bbcdf4ab9e39880bea817538dcef172f7dfdb
|
/src/main/java/com/zenoc/core/model/AbstractModel.java
|
393464783ecae0144a2bcfcf5e8ce0295abd0d2b
|
[] |
no_license
|
liaostr/JdbcTemplate
|
https://github.com/liaostr/JdbcTemplate
|
d224faa05764ca23ee7eb0dfd67af7480f6470b8
|
321c5d7b3f21869417aaf116d01d05ca72e3b09c
|
refs/heads/master
| 2021-06-20T21:58:06.716000 | 2017-07-21T07:29:44 | 2017-07-21T07:29:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zenoc.core.model;
import com.zenoc.core.interfaces.DbMapper;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class AbstractModel<T> implements RowMapper<T> {
public abstract T getInstance();
public String getSql(){
return getSql("*");
}
public String getSql(String selectors){
return DbMapper.getSql(getClass(), selectors);
}
@Override
public T mapRow(ResultSet rs, int rowIndex) throws SQLException {
T o = getInstance();
try {
return DbMapper.dbToBean(rs, rowIndex, o);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return o;
}
}
|
UTF-8
|
Java
| 796 |
java
|
AbstractModel.java
|
Java
|
[] | null |
[] |
package com.zenoc.core.model;
import com.zenoc.core.interfaces.DbMapper;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class AbstractModel<T> implements RowMapper<T> {
public abstract T getInstance();
public String getSql(){
return getSql("*");
}
public String getSql(String selectors){
return DbMapper.getSql(getClass(), selectors);
}
@Override
public T mapRow(ResultSet rs, int rowIndex) throws SQLException {
T o = getInstance();
try {
return DbMapper.dbToBean(rs, rowIndex, o);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return o;
}
}
| 796 | 0.726131 | 0.726131 | 34 | 22.411764 | 19.246264 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.735294 | false | false |
10
|
d0a55e505a403f42c98f63108f4fb06a36c3af87
| 2,989,297,282,370 |
578fccad24dde0f83efceba226ea06aee2d1479e
|
/src/main/java/presentacion/vista/administrador/LoadingWorker.java
|
6a1c97f7e54710df917b6ddb095c5fb38c5f1022
|
[] |
no_license
|
posadassca/AlPlaneta
|
https://github.com/posadassca/AlPlaneta
|
d0430565f0acdd45265f9d79e241dfbd45a55819
|
4766e02744d30ed72f18e77b7bcbd0b941400b54
|
refs/heads/master
| 2021-07-08T05:27:31.712000 | 2019-08-01T15:57:38 | 2019-08-01T15:57:38 | 200,076,160 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package presentacion.vista.administrador;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Image;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
public class LoadingWorker extends JDialog{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JLabel progressImage;
private JLabel lblPorFavorEspere;
private Thread thread;
private String imgPath;
/**
* @wbp.parser.constructor
*/
public LoadingWorker(Frame parent, String text, Thread thread, String imgPath) {
super(parent, true);
this.thread = thread;
this.imgPath = imgPath;
inicialize();
lblPorFavorEspere.setText(text);
}
private void inicialize() {
setBounds(100, 100, 450, 264);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
URL url = LoadingWorker.class.getResource(imgPath);
ImageIcon imageIcon = new ImageIcon(url);
progressImage = new JLabel();
progressImage.setBounds(26, 64, 380, 139);
Icon icono = new ImageIcon(imageIcon.getImage().getScaledInstance(progressImage.getWidth(), progressImage.getHeight(), Image.SCALE_DEFAULT));
progressImage.setIcon(icono);
contentPanel.setLayout(null);
contentPanel.add(progressImage);
lblPorFavorEspere = new JLabel();
lblPorFavorEspere.setBounds(26, 28, 380, 14);
contentPanel.add(lblPorFavorEspere);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
public void mostrar() {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws InterruptedException {
thread.start();
Thread.sleep(10000);
return null;
}
@Override
protected void done() {
dispose();
}
};
worker.execute();
setVisible(true);
}
}
|
UTF-8
|
Java
| 2,193 |
java
|
LoadingWorker.java
|
Java
|
[] | null |
[] |
package presentacion.vista.administrador;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Image;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
public class LoadingWorker extends JDialog{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JLabel progressImage;
private JLabel lblPorFavorEspere;
private Thread thread;
private String imgPath;
/**
* @wbp.parser.constructor
*/
public LoadingWorker(Frame parent, String text, Thread thread, String imgPath) {
super(parent, true);
this.thread = thread;
this.imgPath = imgPath;
inicialize();
lblPorFavorEspere.setText(text);
}
private void inicialize() {
setBounds(100, 100, 450, 264);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
URL url = LoadingWorker.class.getResource(imgPath);
ImageIcon imageIcon = new ImageIcon(url);
progressImage = new JLabel();
progressImage.setBounds(26, 64, 380, 139);
Icon icono = new ImageIcon(imageIcon.getImage().getScaledInstance(progressImage.getWidth(), progressImage.getHeight(), Image.SCALE_DEFAULT));
progressImage.setIcon(icono);
contentPanel.setLayout(null);
contentPanel.add(progressImage);
lblPorFavorEspere = new JLabel();
lblPorFavorEspere.setBounds(26, 28, 380, 14);
contentPanel.add(lblPorFavorEspere);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
public void mostrar() {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws InterruptedException {
thread.start();
Thread.sleep(10000);
return null;
}
@Override
protected void done() {
dispose();
}
};
worker.execute();
setVisible(true);
}
}
| 2,193 | 0.710442 | 0.691746 | 81 | 25.074074 | 23.147821 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.172839 | false | false |
10
|
1f2e8948f534bfd5b34516c5a22a595e4c028b11
| 1,357,209,669,107 |
b6605bd85638613538500258d34f9882efdb9476
|
/BlueMarble/src/marble02/MarbleFrame01.java
|
b03788c9dd8d2ce931671e7c7a747bbc6375398b
|
[] |
no_license
|
lennysmall/mable0706
|
https://github.com/lennysmall/mable0706
|
210e019c2bee77ae2da00a9d42c751ed6be86716
|
dd5804f634b8267ad8f0c9dd9fe73c7ea2ccfe98
|
refs/heads/master
| 2016-09-05T13:03:14.417000 | 2014-07-06T12:47:16 | 2014-07-06T12:47:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package marble02;
import javax.swing.JInternalFrame;
public class MarbleFrame01 {
JInternalFrame gameFrame = new JInternalFrame("게임 프레임",
false /* 크기변경 가능 */,
false /* 종료 가능 */,
false /* 최대 크기로 가능 */,
false /* 아이콘화 가능 */ );
public void setGameFrame(JInternalFrame gameFrame) { //기능구현을 위해놔둠
this.gameFrame = gameFrame;
}
}
|
UTF-8
|
Java
| 438 |
java
|
MarbleFrame01.java
|
Java
|
[] | null |
[] |
package marble02;
import javax.swing.JInternalFrame;
public class MarbleFrame01 {
JInternalFrame gameFrame = new JInternalFrame("게임 프레임",
false /* 크기변경 가능 */,
false /* 종료 가능 */,
false /* 최대 크기로 가능 */,
false /* 아이콘화 가능 */ );
public void setGameFrame(JInternalFrame gameFrame) { //기능구현을 위해놔둠
this.gameFrame = gameFrame;
}
}
| 438 | 0.64011 | 0.629121 | 17 | 19.411764 | 19.793222 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.529412 | false | false |
10
|
7cbfe6731f47c3b8e4597d6757c753fcb330e930
| 17,635,135,724,541 |
2254496a8995b939384c085b9aaef6e43ff13739
|
/MergeSort.java
|
2b28cb83ad2876c29e43b7745b8480322f4ddef4
|
[] |
no_license
|
knowncodelori/JavaSortMethods5
|
https://github.com/knowncodelori/JavaSortMethods5
|
fd57e4a63929dcb6cc76e81543a36376acf7045e
|
758be990d01786ddc34cd333f3d69685721c7f3c
|
refs/heads/main
| 2023-05-10T04:50:42.359000 | 2021-06-05T13:45:17 | 2021-06-05T13:45:17 | 374,114,781 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class MergeSort {
public static void main(String[] args) {
int[] nums = {2,5,1,5,3,5,7,89,1,5,10,36,7,49,52,123,45,79,132,456,114,514,114514,19,19,810,1919810};
int[] ans = MergeSort(nums);
for (int i : ans) {
System.out.print(i + ",");
}
}
public static int[] MergeSort(int[] nums){
if (nums.length <= 1){
return nums;
}
int[] nums1 = new int[nums.length / 2];
int[] nums2 = new int[nums.length - nums.length / 2];
for (int i = 0; i < nums.length; i++) {
if (i < nums1.length) {
nums1[i] = nums[i];
}else{
nums2[i - nums1.length] = nums[i];
}
}
return Merge(MergeSort(nums1), MergeSort(nums2));
}
public static int[] Merge(int[] nums1, int[] nums2){
int i = 0;
int j = 0;
int[] temp = new int[nums1.length + nums2.length];
while(i < nums1.length && j < nums2.length){
if ( nums1[i] < nums2[j]){
temp[i + j] = nums1[i++];
}else{
temp[i + j] = nums2[j++];
}
}
while (i == nums1.length && j < nums2.length){
temp[i + j] = nums2[j++];
}
while (j == nums2.length && i < nums1.length){
temp[i + j] = nums1[i++];
}
return temp;
}
}
|
UTF-8
|
Java
| 1,456 |
java
|
MergeSort.java
|
Java
|
[] | null |
[] |
public class MergeSort {
public static void main(String[] args) {
int[] nums = {2,5,1,5,3,5,7,89,1,5,10,36,7,49,52,123,45,79,132,456,114,514,114514,19,19,810,1919810};
int[] ans = MergeSort(nums);
for (int i : ans) {
System.out.print(i + ",");
}
}
public static int[] MergeSort(int[] nums){
if (nums.length <= 1){
return nums;
}
int[] nums1 = new int[nums.length / 2];
int[] nums2 = new int[nums.length - nums.length / 2];
for (int i = 0; i < nums.length; i++) {
if (i < nums1.length) {
nums1[i] = nums[i];
}else{
nums2[i - nums1.length] = nums[i];
}
}
return Merge(MergeSort(nums1), MergeSort(nums2));
}
public static int[] Merge(int[] nums1, int[] nums2){
int i = 0;
int j = 0;
int[] temp = new int[nums1.length + nums2.length];
while(i < nums1.length && j < nums2.length){
if ( nums1[i] < nums2[j]){
temp[i + j] = nums1[i++];
}else{
temp[i + j] = nums2[j++];
}
}
while (i == nums1.length && j < nums2.length){
temp[i + j] = nums2[j++];
}
while (j == nums2.length && i < nums1.length){
temp[i + j] = nums1[i++];
}
return temp;
}
}
| 1,456 | 0.431319 | 0.370192 | 45 | 30.355556 | 21.859303 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.066667 | false | false |
10
|
e3e4d71f3c4ef19a1d00f9f081745c3c89355a3b
| 38,431,367,380,677 |
53d758f91288ca2ce225e07fc8d46156b0b691ba
|
/src/main/java/com/chuncongcong/productmgmt/model/dto/AttributeDto.java
|
cef28f71c882fcc192f95a6349ec664a5ccadcf0
|
[] |
no_license
|
yyrely/product_mgmt
|
https://github.com/yyrely/product_mgmt
|
f85268b97f9a667e832573f43fd56d7634fe3140
|
f0b2939a6239f5b32001d758f0df34379897f234
|
refs/heads/master
| 2023-01-20T16:45:42.118000 | 2023-01-09T14:15:21 | 2023-01-09T14:15:21 | 230,718,862 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chuncongcong.productmgmt.model.dto;
import java.util.List;
import com.chuncongcong.productmgmt.model.po.ValuePo;
import lombok.Data;
/**
* @author HU
* @date 2019/12/21 14:58
*/
@Data
public class AttributeDto {
private Long attributeId;
private Long categoryId;
private String attributeName;
private List<ValuePo> valuePos;
}
|
UTF-8
|
Java
| 354 |
java
|
AttributeDto.java
|
Java
|
[
{
"context": "el.po.ValuePo;\nimport lombok.Data;\n\n/**\n * @author HU\n * @date 2019/12/21 14:58\n */\n\n@Data\npublic clas",
"end": 164,
"score": 0.6132541298866272,
"start": 163,
"tag": "NAME",
"value": "H"
},
{
"context": ".po.ValuePo;\nimport lombok.Data;\n\n/**\n * @author HU\n * @date 2019/12/21 14:58\n */\n\n@Data\npublic class",
"end": 165,
"score": 0.5174107551574707,
"start": 164,
"tag": "USERNAME",
"value": "U"
}
] | null |
[] |
package com.chuncongcong.productmgmt.model.dto;
import java.util.List;
import com.chuncongcong.productmgmt.model.po.ValuePo;
import lombok.Data;
/**
* @author HU
* @date 2019/12/21 14:58
*/
@Data
public class AttributeDto {
private Long attributeId;
private Long categoryId;
private String attributeName;
private List<ValuePo> valuePos;
}
| 354 | 0.754237 | 0.720339 | 23 | 14.391304 | 16.004725 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
10
|
0fb6ae8e7dc9f0cccf5f4f4feda0c6d5ac77687a
| 35,785,667,540,486 |
ead73257ab382e01223035550ca0d9f23024f416
|
/Java - Design Patterns/sunnittelumallit-master/VisitorExercise/src/com/state/human/HumanState.java
|
c855917e75a16d1f3713516d189bf3aa5c6285c5
|
[] |
no_license
|
Yooru6/Projects-and-Exercises
|
https://github.com/Yooru6/Projects-and-Exercises
|
2fcd69fe53fc1aaafb87b256bb6fe65d0b899b56
|
4223a08485e657dbd79ea4067d1124267eb9fbfe
|
refs/heads/master
| 2022-06-21T23:38:11.745000 | 2020-02-11T16:21:26 | 2020-02-11T16:21:26 | 236,264,336 | 1 | 0 | null | false | 2022-06-21T02:44:46 | 2020-01-26T03:58:06 | 2020-02-11T16:21:40 | 2022-06-21T02:44:44 | 33,237 | 0 | 0 | 4 |
Jupyter Notebook
| false | false |
package com.state.human;
public abstract class HumanState {
protected int hapinessPts;
protected int anxietyPts;
protected String[] specialEvent;
protected String stateName;
protected int days;
protected int age;
public HumanState(){
this.hapinessPts = 0;
this.anxietyPts = 0;
this.days =0;
this.age=0;
}
public int gethapinessPts() {return this.hapinessPts; }
public int getAnxietyPts() {return this.anxietyPts; }
public int getDays() {return this.days; }
public int getAge() {return this.age; }
}
|
UTF-8
|
Java
| 540 |
java
|
HumanState.java
|
Java
|
[] | null |
[] |
package com.state.human;
public abstract class HumanState {
protected int hapinessPts;
protected int anxietyPts;
protected String[] specialEvent;
protected String stateName;
protected int days;
protected int age;
public HumanState(){
this.hapinessPts = 0;
this.anxietyPts = 0;
this.days =0;
this.age=0;
}
public int gethapinessPts() {return this.hapinessPts; }
public int getAnxietyPts() {return this.anxietyPts; }
public int getDays() {return this.days; }
public int getAge() {return this.age; }
}
| 540 | 0.711111 | 0.703704 | 25 | 20.6 | 16.714066 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
10
|
f9b6522b27d3fb3a968ee8c9030b41634f4502b7
| 5,291,399,775,230 |
3de3dae722829727edfdd6cc3b67443a69043475
|
/tests/unit/com/raytheon/uf/common/time/util/TimeUtilTest.java
|
a3d9121c5a7479a007e5ce76e61cffa8f629dd93
|
[
"LicenseRef-scancode-public-domain",
"Apache-2.0"
] |
permissive
|
Unidata/awips2
|
https://github.com/Unidata/awips2
|
9aee5b7ec42c2c0a2fa4d877cb7e0b399db74acb
|
d76c9f96e6bb06f7239c563203f226e6a6fffeef
|
refs/heads/unidata_18.2.1
| 2023-08-18T13:00:15.110000 | 2023-08-09T06:06:06 | 2023-08-09T06:06:06 | 19,332,079 | 161 | 75 |
NOASSERTION
| false | 2023-09-13T19:06:40 | 2014-05-01T00:59:04 | 2023-09-08T16:47:16 | 2023-09-13T19:06:39 | 3,747,641 | 150 | 66 | 74 |
Java
| false | false |
package com.raytheon.uf.common.time.util;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import com.raytheon.edex.util.Util;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.SimulatedTime;
import com.raytheon.uf.common.util.TestUtil;
/**
*
* Test {@link TimeUtil}. Can also be used to {@link #freezeTime()}. When
* freezing time in a unit test, you should always have an "@After" annotated
* method that will resume time (or you can have the call in a try/finally).
* e.g.:
*
* <pre>
* {@code
*
* "@After" // without quotes
* public void afterTest() {
* // This is the after each test method of resuming time
* TimeUtilTest.resumeTime();
* }
*
* "@Test" // without quotes
* public void testSomethingHappensAtFrozenTime() {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* }
*
* "@Test"
* public void testSomethingHappensAtFrozenTimeTryFinally() {
* try {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* } finally {
* TimeUtilTest.resumeTime();
* }
* }
*
* }
*
* </pre>
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 16, 2012 0743 djohnson Initial creation
* Sep 11, 2012 1154 djohnson Tests for {@link TimeUtil#isNewerDay(Date, Date, TimeZone)}
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TimeUtilTest {
/**
* Allows time to be manipulated so that tests can be run assuming specific
* time frames.
*
* @author djohnson
*
*/
private static class MockTimeStrategy implements ITimeStrategy {
private final long[] times;
private int index;
public MockTimeStrategy(long[] times) {
if (times == null || times.length == 0) {
throw new IllegalArgumentException(
"Must specify at least one time!");
}
this.times = times;
}
@Override
public long currentTimeMillis() {
long value = times[index];
if (index < (times.length - 1)) {
index++;
}
return value;
}
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that each successive call will return the next element in the array,
* remaining at the last element in the array when reached. This is a
* low-level call to setup specific time instances to be returned, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(new long[] 10L, 20L, 30L});
* long time1 = TimeUtil.currentTimeMillis(); // 10L
* long time2 = TimeUtil.currentTimeMillis(); // 20L
* long time3 = TimeUtil.currentTimeMillis(): // 30L
* long time4 = TimeUtil.currentTimeMillis(): // 30L, out of new times
* }
* </pre>
*
* @param times
* the times to return
*/
public static void installMockTimes(long[] times) {
TimeUtil.timeStrategy = new MockTimeStrategy(times);
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that the first call will return the current time, and the second call
* will return the time after the specified duration has elapsed, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(5, TimeUnit.MINUTES);
* long time1 = TimeUtil.currentTimeMillis(); // current time
* long time2 = TimeUtil.currentTimeMillis(); // 5 minutes in the future
* }
* </pre>
*
* @param amount
* the amount for the specified {@link TimeUnit}
* @param unit
* the {@link TimeUnit}
*/
public static void installMockTimes(long amount, TimeUnit unit) {
long start = System.currentTimeMillis();
long end = start + unit.toMillis(amount);
TimeUtilTest.installMockTimes(new long[] { start, end });
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the current time. This
* is useful to remove time sensitive issues from testing, for instance if
* an operation that exceeds 10 seconds in production code should throw an
* exception but is allowable in test code, then time should be frozen.
*
* <pre>
* {@code
* TimeUtilTest.freezeTime();
* long time1 = TimeUtil.currentTimeMillis(); // 20000000L for example
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 20000000L, still
* }
* </pre>
*/
public static void freezeTime() {
freezeTime(System.currentTimeMillis());
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the specified time. This
* is useful to test specific scenarios, such as errors that occur on
* specific dates/times of the year (e.g. the switch to daylight savings
* time).
*
* <pre>
* {@code
* TimeUtilTest.freezeTime(15151515L);
* long time1 = TimeUtil.currentTimeMillis(); // 15151515L
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 15151515L, still
* }
* </pre>
*
* @param timeToFreezeAt
* the time that the system should be frozen to
*/
public static void freezeTime(long timeToFreezeAt) {
SimulatedTime systemTime = SimulatedTime.getSystemTime();
systemTime.setFrozen(true);
systemTime.setTime(timeToFreezeAt);
installMockTimes(new long[] { timeToFreezeAt });
}
/**
* Resumes using the system time, this can be called after time has been
* frozen to resume noticing time differences when
* {@link TimeUtil#currentTimeMillis()} is called.
*/
public static void resumeTime() {
TimeUtil.timeStrategy = TimeUtil.SYSTEM_TIME_STRATEGY;
SimulatedTime.getSystemTime().setRealTime();
}
@After
public void cleanUp() {
TimeUtilTest.resumeTime();
}
@Test
public void testFreezeTimeStopsTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
assertEquals("Time should have been frozen!", firstTime, secondTime);
}
@Test
public void testFreezeTimeStopsSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
assertEquals("SimulatedTime should have been frozen!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameter() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, TimeUtil.currentTimeMillis());
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameterForSimulatedTime() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, SimulatedTime.getSystemTime()
.getMillis());
}
@Test
public void testInstallMockTimesWithTimeUnitSetsUpCorrectTime() {
final long twoHoursInMillis = Util.MILLI_PER_HOUR * 2;
TimeUtilTest.installMockTimes(2, TimeUnit.HOURS);
long time1 = TimeUtil.currentTimeMillis();
long time2 = TimeUtil.currentTimeMillis();
assertEquals(
"Expected the second time to be 2 hours after the first time!",
twoHoursInMillis, time2 - time1);
}
@Test
public void testGetPriorityEnabledClockReturnsNullClockWhenPriorityNotEnabled() {
IUFStatusHandler handler = mock(IUFStatusHandler.class);
when(handler.isPriorityEnabled(Priority.VERBOSE)).thenReturn(false);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.VERBOSE);
assertSame("Expected to receive the null clock!", TimeUtil.NULL_CLOCK,
clock);
}
@Test
public void testGetPriorityEnabledClockReturnsClockImplWhenPriorityEnabled() {
IUFStatusHandler handler = UFStatus.getHandler(TimeUtilTest.class);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.CRITICAL);
assertTrue("Expected to receive a real clock!",
clock instanceof TimerImpl);
}
@Test
public void testNewDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newDate().getTime());
}
@Test
public void testNewImmutableDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newImmutableDate().getTime());
}
@Test
public void testNewCalendarDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newCalendar().getTime().getTime());
}
@Test
public void testIsNewerDayReturnsTrueForOneMillisecondIntoNewDate() {
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY - 1L);
Date later = new ImmutableDate(earlier.getTime() + 2L);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later,
TimeZone.getTimeZone("GMT")));
}
@Test
public void testIsNewerDayReturnsTrueForNewYear() {
// Jan 11, 1970
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 10);
// Jan 01, 1971
Date later = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 366);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later, TimeZone.getTimeZone("GMT")));
}
@Test
public void testMinCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMinimum(cal, Calendar.MONTH);
assertCalendarFieldIsMinimum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMinimum(cal, Calendar.SECOND);
}
@Test
public void testMinCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
@Test
public void testMaxCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.maxCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMaximum(cal, Calendar.MONTH);
assertCalendarFieldIsMaximum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMaximum(cal, Calendar.SECOND);
}
@Test
public void testMaxCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
/**
* Assert a calendar field was set to its minimum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMinimum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMinimum(field))));
}
/**
* Assert a calendar field was set to its maximum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMaximum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMaximum(field))));
}
}
|
UTF-8
|
Java
| 16,245 |
java
|
TimeUtilTest.java
|
Java
|
[
{
"context": "-----------------------\n * Aug 16, 2012 0743 djohnson Initial creation\n * Sep 11, 2012 1154 d",
"end": 1902,
"score": 0.9881240725517273,
"start": 1894,
"tag": "USERNAME",
"value": "djohnson"
},
{
"context": "on Initial creation\n * Sep 11, 2012 1154 djohnson Tests for {@link TimeUtil#isNewerDay(Date, Da",
"end": 1959,
"score": 0.9891511797904968,
"start": 1951,
"tag": "USERNAME",
"value": "djohnson"
},
{
"context": "ate, Date, TimeZone)}\n * \n * </pre>\n * \n * @author djohnson\n * @version 1.0\n */\npublic class TimeUtilTest {\n\n",
"end": 2061,
"score": 0.9267335534095764,
"start": 2053,
"tag": "USERNAME",
"value": "djohnson"
},
{
"context": "pecific\n * time frames.\n * \n * @author djohnson\n * \n */\n private static class MockTime",
"end": 2250,
"score": 0.9611515402793884,
"start": 2242,
"tag": "USERNAME",
"value": "djohnson"
}
] | null |
[] |
package com.raytheon.uf.common.time.util;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import com.raytheon.edex.util.Util;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.SimulatedTime;
import com.raytheon.uf.common.util.TestUtil;
/**
*
* Test {@link TimeUtil}. Can also be used to {@link #freezeTime()}. When
* freezing time in a unit test, you should always have an "@After" annotated
* method that will resume time (or you can have the call in a try/finally).
* e.g.:
*
* <pre>
* {@code
*
* "@After" // without quotes
* public void afterTest() {
* // This is the after each test method of resuming time
* TimeUtilTest.resumeTime();
* }
*
* "@Test" // without quotes
* public void testSomethingHappensAtFrozenTime() {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* }
*
* "@Test"
* public void testSomethingHappensAtFrozenTimeTryFinally() {
* try {
* TimeUtilTest.freezeTime();
* // Perform some testing while time is frozen
* } finally {
* TimeUtilTest.resumeTime();
* }
* }
*
* }
*
* </pre>
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 16, 2012 0743 djohnson Initial creation
* Sep 11, 2012 1154 djohnson Tests for {@link TimeUtil#isNewerDay(Date, Date, TimeZone)}
*
* </pre>
*
* @author djohnson
* @version 1.0
*/
public class TimeUtilTest {
/**
* Allows time to be manipulated so that tests can be run assuming specific
* time frames.
*
* @author djohnson
*
*/
private static class MockTimeStrategy implements ITimeStrategy {
private final long[] times;
private int index;
public MockTimeStrategy(long[] times) {
if (times == null || times.length == 0) {
throw new IllegalArgumentException(
"Must specify at least one time!");
}
this.times = times;
}
@Override
public long currentTimeMillis() {
long value = times[index];
if (index < (times.length - 1)) {
index++;
}
return value;
}
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that each successive call will return the next element in the array,
* remaining at the last element in the array when reached. This is a
* low-level call to setup specific time instances to be returned, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(new long[] 10L, 20L, 30L});
* long time1 = TimeUtil.currentTimeMillis(); // 10L
* long time2 = TimeUtil.currentTimeMillis(); // 20L
* long time3 = TimeUtil.currentTimeMillis(): // 30L
* long time4 = TimeUtil.currentTimeMillis(): // 30L, out of new times
* }
* </pre>
*
* @param times
* the times to return
*/
public static void installMockTimes(long[] times) {
TimeUtil.timeStrategy = new MockTimeStrategy(times);
}
/**
* Mocks the times returned from {@link TimeUtil#currentTimeMillis()} such
* that the first call will return the current time, and the second call
* will return the time after the specified duration has elapsed, e.g.:
*
* <pre>
* {@code
* TimeUtilTest.installMockTimes(5, TimeUnit.MINUTES);
* long time1 = TimeUtil.currentTimeMillis(); // current time
* long time2 = TimeUtil.currentTimeMillis(); // 5 minutes in the future
* }
* </pre>
*
* @param amount
* the amount for the specified {@link TimeUnit}
* @param unit
* the {@link TimeUnit}
*/
public static void installMockTimes(long amount, TimeUnit unit) {
long start = System.currentTimeMillis();
long end = start + unit.toMillis(amount);
TimeUtilTest.installMockTimes(new long[] { start, end });
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the current time. This
* is useful to remove time sensitive issues from testing, for instance if
* an operation that exceeds 10 seconds in production code should throw an
* exception but is allowable in test code, then time should be frozen.
*
* <pre>
* {@code
* TimeUtilTest.freezeTime();
* long time1 = TimeUtil.currentTimeMillis(); // 20000000L for example
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 20000000L, still
* }
* </pre>
*/
public static void freezeTime() {
freezeTime(System.currentTimeMillis());
}
/**
* Freezes time so that all successive calls to
* {@link TimeUtil#currentTimeMillis()} will return the specified time. This
* is useful to test specific scenarios, such as errors that occur on
* specific dates/times of the year (e.g. the switch to daylight savings
* time).
*
* <pre>
* {@code
* TimeUtilTest.freezeTime(15151515L);
* long time1 = TimeUtil.currentTimeMillis(); // 15151515L
*
* Thread.sleep(1000L);
*
* long time2 = TimeUtil.currentTimeMillis(); // 15151515L, still
* }
* </pre>
*
* @param timeToFreezeAt
* the time that the system should be frozen to
*/
public static void freezeTime(long timeToFreezeAt) {
SimulatedTime systemTime = SimulatedTime.getSystemTime();
systemTime.setFrozen(true);
systemTime.setTime(timeToFreezeAt);
installMockTimes(new long[] { timeToFreezeAt });
}
/**
* Resumes using the system time, this can be called after time has been
* frozen to resume noticing time differences when
* {@link TimeUtil#currentTimeMillis()} is called.
*/
public static void resumeTime() {
TimeUtil.timeStrategy = TimeUtil.SYSTEM_TIME_STRATEGY;
SimulatedTime.getSystemTime().setRealTime();
}
@After
public void cleanUp() {
TimeUtilTest.resumeTime();
}
@Test
public void testFreezeTimeStopsTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
assertEquals("Time should have been frozen!", firstTime, secondTime);
}
@Test
public void testFreezeTimeStopsSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
assertEquals("SimulatedTime should have been frozen!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = TimeUtil.currentTimeMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = TimeUtil.currentTimeMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testResumeTimeWillResumeSimulatedTime() throws InterruptedException {
TimeUtilTest.freezeTime();
long firstTime = SimulatedTime.getSystemTime().getMillis();
TimeUtilTest.resumeTime();
Thread.sleep(10L);
long secondTime = SimulatedTime.getSystemTime().getMillis();
TestUtil.assertNotEquals("Time should have resumed!", firstTime,
secondTime);
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameter() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, TimeUtil.currentTimeMillis());
}
@Test
public void testFreezeTimeAtSpecificTimeUsesTheParameterForSimulatedTime() {
final long timeToFreezeAt = System.currentTimeMillis() - 20000L;
TimeUtilTest.freezeTime(timeToFreezeAt);
assertEquals("Expected time to be frozen at the specified time!",
timeToFreezeAt, SimulatedTime.getSystemTime()
.getMillis());
}
@Test
public void testInstallMockTimesWithTimeUnitSetsUpCorrectTime() {
final long twoHoursInMillis = Util.MILLI_PER_HOUR * 2;
TimeUtilTest.installMockTimes(2, TimeUnit.HOURS);
long time1 = TimeUtil.currentTimeMillis();
long time2 = TimeUtil.currentTimeMillis();
assertEquals(
"Expected the second time to be 2 hours after the first time!",
twoHoursInMillis, time2 - time1);
}
@Test
public void testGetPriorityEnabledClockReturnsNullClockWhenPriorityNotEnabled() {
IUFStatusHandler handler = mock(IUFStatusHandler.class);
when(handler.isPriorityEnabled(Priority.VERBOSE)).thenReturn(false);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.VERBOSE);
assertSame("Expected to receive the null clock!", TimeUtil.NULL_CLOCK,
clock);
}
@Test
public void testGetPriorityEnabledClockReturnsClockImplWhenPriorityEnabled() {
IUFStatusHandler handler = UFStatus.getHandler(TimeUtilTest.class);
ITimer clock = TimeUtil.getPriorityEnabledTimer(handler,
Priority.CRITICAL);
assertTrue("Expected to receive a real clock!",
clock instanceof TimerImpl);
}
@Test
public void testNewDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newDate().getTime());
}
@Test
public void testNewImmutableDateDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newImmutableDate().getTime());
}
@Test
public void testNewCalendarDelegatesToSimulatedTime() {
long millis = 100L;
SimulatedTime.getSystemTime().setFrozen(true);
SimulatedTime.getSystemTime().setTime(millis);
assertEquals(
"TimeUtil does not appear to have delegated to SimulatedTime!",
millis, TimeUtil.newCalendar().getTime().getTime());
}
@Test
public void testIsNewerDayReturnsTrueForOneMillisecondIntoNewDate() {
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY - 1L);
Date later = new ImmutableDate(earlier.getTime() + 2L);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later,
TimeZone.getTimeZone("GMT")));
}
@Test
public void testIsNewerDayReturnsTrueForNewYear() {
// Jan 11, 1970
Date earlier = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 10);
// Jan 01, 1971
Date later = new ImmutableDate(TimeUtil.MILLIS_PER_DAY * 366);
assertTrue(
"Expected the second date object to be found to be a newer date!",
TimeUtil.isNewerDay(earlier, later, TimeZone.getTimeZone("GMT")));
}
@Test
public void testMinCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMinimum(cal, Calendar.MONTH);
assertCalendarFieldIsMinimum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMinimum(cal, Calendar.SECOND);
}
@Test
public void testMinCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
@Test
public void testMaxCalendarFieldsChangesRequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.maxCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertCalendarFieldIsMaximum(cal, Calendar.MONTH);
assertCalendarFieldIsMaximum(cal, Calendar.HOUR_OF_DAY);
assertCalendarFieldIsMaximum(cal, Calendar.SECOND);
}
@Test
public void testMaxCalendarFieldsDoesNotChangeUnrequestedFields() {
Calendar cal = TimeUtil.newCalendar();
cal.set(Calendar.YEAR, 2000);
cal.set(Calendar.MONTH, 12);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 12);
cal.set(Calendar.SECOND, 12);
cal.set(Calendar.MILLISECOND, 12);
TimeUtil.minCalendarFields(cal, Calendar.MONTH, Calendar.HOUR_OF_DAY,
Calendar.SECOND);
assertThat(cal.get(Calendar.YEAR), is(equalTo(2000)));
assertThat(cal.get(Calendar.DAY_OF_MONTH), is(equalTo(12)));
assertThat(cal.get(Calendar.MINUTE), is(equalTo(12)));
assertThat(cal.get(Calendar.MILLISECOND), is(equalTo(12)));
}
/**
* Assert a calendar field was set to its minimum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMinimum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMinimum(field))));
}
/**
* Assert a calendar field was set to its maximum allowed value.
*
* @param cal
* the calendar
* @param field
* the calendar field
*/
private static void assertCalendarFieldIsMaximum(Calendar cal, int field) {
assertThat(cal.get(field), is(equalTo(cal.getActualMaximum(field))));
}
}
| 16,245 | 0.63675 | 0.622161 | 483 | 32.633541 | 27.083496 | 99 | false | false | 0 | 0 | 0 | 0 | 65 | 0.004001 | 0.585921 | false | false |
10
|
3f3aa38ec3839c0f8acddad3d7b39b2550dba04b
| 39,006,892,997,247 |
dbd59a5c435e21be64c86b2e47bc1da2a4b08269
|
/编程/设计模式/HeadFirst设计模式/design-pattern/src/main/java/com/can/pattern/proxy/server/service/MyRemote.java
|
c4fe52a95b82de771e41c994f11e0faf291ef021
|
[] |
no_license
|
LCN29/Books
|
https://github.com/LCN29/Books
|
bb1c7d3704dd176e76c86ad9aad1c74117db588c
|
05b3447f4272676affb9767ae9bdb6391687fde3
|
refs/heads/master
| 2020-06-13T02:20:28.218000 | 2019-11-16T06:48:44 | 2019-11-16T06:48:44 | 194,499,466 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.can.pattern.proxy.server.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @description: 远程接口
* @author: LCN
* @date: 2019-07-07 13:52
*/
public interface MyRemote extends Remote {
String sayHello() throws RemoteException;
}
|
UTF-8
|
Java
| 278 |
java
|
MyRemote.java
|
Java
|
[
{
"context": "eException;\n\n/**\n * @description: 远程接口\n * @author: LCN\n * @date: 2019-07-07 13:52\n */\npublic interface M",
"end": 146,
"score": 0.9997084140777588,
"start": 143,
"tag": "USERNAME",
"value": "LCN"
}
] | null |
[] |
package com.can.pattern.proxy.server.service;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @description: 远程接口
* @author: LCN
* @date: 2019-07-07 13:52
*/
public interface MyRemote extends Remote {
String sayHello() throws RemoteException;
}
| 278 | 0.725926 | 0.681481 | 14 | 18.285715 | 17.001801 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
10
|
827b3f3e8b43afff94cc777c8a6d71dd6ee1aa93
| 39,006,892,998,533 |
24462c1246251770b5d75c98da0da51ffc5d9ea8
|
/Java/Tree.java
|
3e7db6126a02a928dd94131a91d338409917a7eb
|
[] |
no_license
|
khanaaziz1/Hacktoberfest_2019
|
https://github.com/khanaaziz1/Hacktoberfest_2019
|
4ec4e1cde93b5dad8245229875ac6508e70cfc33
|
0e8772bc43f0b6f47c9cf1bcad5bc4611143d910
|
refs/heads/master
| 2020-08-10T06:04:11.136000 | 2019-10-28T16:25:49 | 2019-10-28T16:25:49 | 214,277,755 | 3 | 31 | null | false | 2019-10-28T16:25:50 | 2019-10-10T20:18:39 | 2019-10-24T19:50:37 | 2019-10-28T16:25:50 | 67 | 3 | 25 | 1 |
Java
| false | false |
public class Tree {
private Integer value;
private Tree left;
private Tree right;
public Tree(Integer value) {
this.value = value;
}
public void add(Integer newValue) {
if (this.value < newValue) {
if (right == null) {
right = new Tree(newValue);
} else {
right.add(newValue);
}
} else {
if (left == null) {
left = new Tree(newValue);
} else {
left.add(newValue);
}
}
}
public void printPrefixed() {
if (left != null) {
left.printPrefixed();
}
System.out.println(value);
if (right != null) {
right.printPrefixed();
}
}
public void printSuffixed() {
if (right != null) {
right.printSuffixed();
}
System.out.println(value);
if (left != null) {
left.printSuffixed();
}
}
public static void main(String[] args) {
Tree root = new Tree(5);
for(int i = 0 ; i < 15 ; i++){
root.add((int)(Math.random() * 100));
}
root.printPrefixed();
System.out.println("-----");
root.printSuffixed();
}
}
|
UTF-8
|
Java
| 1,297 |
java
|
Tree.java
|
Java
|
[] | null |
[] |
public class Tree {
private Integer value;
private Tree left;
private Tree right;
public Tree(Integer value) {
this.value = value;
}
public void add(Integer newValue) {
if (this.value < newValue) {
if (right == null) {
right = new Tree(newValue);
} else {
right.add(newValue);
}
} else {
if (left == null) {
left = new Tree(newValue);
} else {
left.add(newValue);
}
}
}
public void printPrefixed() {
if (left != null) {
left.printPrefixed();
}
System.out.println(value);
if (right != null) {
right.printPrefixed();
}
}
public void printSuffixed() {
if (right != null) {
right.printSuffixed();
}
System.out.println(value);
if (left != null) {
left.printSuffixed();
}
}
public static void main(String[] args) {
Tree root = new Tree(5);
for(int i = 0 ; i < 15 ; i++){
root.add((int)(Math.random() * 100));
}
root.printPrefixed();
System.out.println("-----");
root.printSuffixed();
}
}
| 1,297 | 0.448728 | 0.443331 | 57 | 21.754387 | 14.240147 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false |
10
|
3f01be17c05d82ee7a42e4238c2061b216279f18
| 39,608,188,421,846 |
17a81aa40b3e74fc735689ab592396d5a4ca74cd
|
/src/project/MagicString.java
|
eedcc9fe2d13682305e49a094270c55b8bd1bbe7
|
[] |
no_license
|
shaundashjian/magic-string
|
https://github.com/shaundashjian/magic-string
|
592394f52aea93148ec83b166d6700e37c02d316
|
f877e3fe09b0c0fcddfb5adf99cb6b1b839ad613
|
refs/heads/master
| 2021-01-09T20:22:46.736000 | 2017-02-07T17:23:52 | 2017-02-07T17:23:52 | 81,168,870 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package project;
import java.util.Scanner;
public class MagicString {
private Scanner kb = new Scanner(System.in);
private String string = "";
public void read(String string){
if (string != null) {
this.string = string;
} else {
System.out.println("Enter a String: ");
string = kb.nextLine();
}
}
public boolean isEveryCharacterUniqueN2(){
for ( int i = 0; i < string.length(); i++) {
for ( int j = i + 1; j < string.length(); j++){
if ( string.charAt(i) == string.charAt(j)) {
return false;
}
}
}
return true;
}
public boolean isEveryCharacterUniqueUsingHistogram(){
int[] asciiCount = new int[128];
for ( int i = 0; i < string.length(); i++) {
asciiCount[string.charAt(i)]++;
}
for (int i = 0; i < asciiCount.length; i++) {
if (asciiCount[i] > 1) {
return false;
}
}
return true;
}
}
|
UTF-8
|
Java
| 867 |
java
|
MagicString.java
|
Java
|
[] | null |
[] |
package project;
import java.util.Scanner;
public class MagicString {
private Scanner kb = new Scanner(System.in);
private String string = "";
public void read(String string){
if (string != null) {
this.string = string;
} else {
System.out.println("Enter a String: ");
string = kb.nextLine();
}
}
public boolean isEveryCharacterUniqueN2(){
for ( int i = 0; i < string.length(); i++) {
for ( int j = i + 1; j < string.length(); j++){
if ( string.charAt(i) == string.charAt(j)) {
return false;
}
}
}
return true;
}
public boolean isEveryCharacterUniqueUsingHistogram(){
int[] asciiCount = new int[128];
for ( int i = 0; i < string.length(); i++) {
asciiCount[string.charAt(i)]++;
}
for (int i = 0; i < asciiCount.length; i++) {
if (asciiCount[i] > 1) {
return false;
}
}
return true;
}
}
| 867 | 0.599769 | 0.589389 | 44 | 18.704546 | 17.823095 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.136364 | false | false |
10
|
e10870db22205de3e531733e3bc556cd3281bd32
| 36,215,164,282,799 |
214686736356b46b8901d0bdee0c4cf0d487e850
|
/src/main/java/com/jmp/test/dto/StockTrade.java
|
9c749a4e756ec803567924d39e393dcb34e721a4
|
[
"Apache-2.0"
] |
permissive
|
neelesh-sawant/jpm-assignment
|
https://github.com/neelesh-sawant/jpm-assignment
|
75231b4a3e81e44819facb8d0d8d015b6271a784
|
3bdef95890b3bf5ab54eb7bcf819570ff63ab50a
|
refs/heads/master
| 2021-01-10T07:01:24.823000 | 2015-10-14T18:39:36 | 2015-10-14T18:39:36 | 44,233,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jmp.test.dto;
import java.util.Date;
public class StockTrade {
public enum TYPE { BUY, SELL};
public StockTrade()
{
}
public StockTrade(Builder builder)
{
this.stock = builder.stock;
this.type = builder.type;
this.timestamp = builder.timestamp;
this.quantity = builder.quantity;
this.tradedPrice = builder.tradedPrice;
}
private Stock stock;
private Date timestamp;
private int quantity;
private TYPE type;
private Double tradedPrice;
public Stock getStock() {
return stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public TYPE getType() {
return type;
}
public void setType(TYPE type) {
this.type = type;
}
public Double getTradedPrice() {
return tradedPrice;
}
public void setTradedPrice(Double tradedPrice) {
this.tradedPrice = tradedPrice;
}
public static class Builder
{
private Stock stock;
private Date timestamp;
private int quantity;
private TYPE type;
private Double tradedPrice;
public Builder stock(Stock stock) {
this.stock = stock;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder quantity(int quantity) {
this.quantity = quantity;
return this;
}
public Builder type(TYPE type) {
this.type = type;
return this;
}
public Builder tradedPrice(Double tradedPrice) {
this.tradedPrice = tradedPrice;
return this;
}
public StockTrade build()
{
return new StockTrade(this);
}
}
}
|
UTF-8
|
Java
| 1,776 |
java
|
StockTrade.java
|
Java
|
[] | null |
[] |
package com.jmp.test.dto;
import java.util.Date;
public class StockTrade {
public enum TYPE { BUY, SELL};
public StockTrade()
{
}
public StockTrade(Builder builder)
{
this.stock = builder.stock;
this.type = builder.type;
this.timestamp = builder.timestamp;
this.quantity = builder.quantity;
this.tradedPrice = builder.tradedPrice;
}
private Stock stock;
private Date timestamp;
private int quantity;
private TYPE type;
private Double tradedPrice;
public Stock getStock() {
return stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public TYPE getType() {
return type;
}
public void setType(TYPE type) {
this.type = type;
}
public Double getTradedPrice() {
return tradedPrice;
}
public void setTradedPrice(Double tradedPrice) {
this.tradedPrice = tradedPrice;
}
public static class Builder
{
private Stock stock;
private Date timestamp;
private int quantity;
private TYPE type;
private Double tradedPrice;
public Builder stock(Stock stock) {
this.stock = stock;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder quantity(int quantity) {
this.quantity = quantity;
return this;
}
public Builder type(TYPE type) {
this.type = type;
return this;
}
public Builder tradedPrice(Double tradedPrice) {
this.tradedPrice = tradedPrice;
return this;
}
public StockTrade build()
{
return new StockTrade(this);
}
}
}
| 1,776 | 0.699324 | 0.699324 | 93 | 18.096775 | 14.105641 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
10
|
32b1fce9d31ef2f4aecbc2d331c365028b0b1363
| 36,215,164,279,567 |
3a17eddcb9bb3c20ecbb44be7193f8f8679fddc0
|
/AppAndroid/app/src/main/java/com/mjimenez/app_android/fragment_list/CanguroFragment.java
|
3d83368555e4e6bc34120e601dd1caa13d5e0789
|
[] |
no_license
|
mariojr2609/Proyecto-final
|
https://github.com/mariojr2609/Proyecto-final
|
95fe6e7d8e5739981d51614bf36e0b23a8eab00e
|
bd7f22924ecbdc39e5cd91c97d9d91ecd918c7a6
|
refs/heads/master
| 2020-04-27T11:35:15.949000 | 2019-03-21T21:49:42 | 2019-03-21T21:49:42 | 174,300,784 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mjimenez.app_android.fragment_list;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.mjimenez.app_android.R;
import com.mjimenez.app_android.adapter.CanguroAdapter;
import com.mjimenez.app_android.interfaces.CanguroListener;
import com.mjimenez.app_android.models.Canguro;
import com.mjimenez.app_android.responses.ContainerResponse;
import com.mjimenez.app_android.retrofit.generator.ServiceGenerator;
import com.mjimenez.app_android.retrofit.services.CanguroService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CanguroFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
private CanguroListener mListener;
private CanguroAdapter adapter;
private Context ctx;
private RecyclerView recyclerView;
private ProgressBar pg;
private String city;
private List<Canguro> canguros = new ArrayList<>();
private boolean isScrolling = false;
private int currentItems, totalItems, scrollOutItems;
private int page = 0;
private boolean setData = false;
public CanguroFragment() {
}
public static CanguroFragment newInstance(int columnCount) {
CanguroFragment fragment = new CanguroFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_canguro_list, container, false);
pg = view.findViewById(R.id.canguro_list_pb);
Bundle bundle = this.getArguments();
if (bundle != null) {
city = bundle.getString("CIUDAD");
}
if (view instanceof ConstraintLayout) {
Context context = view.getContext();
recyclerView = view.findViewById(R.id.canguro_list);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
if (setData == false) {
page = 1;
getDataPerPage();
}
/*Para ir actualizando el RecyclerView cuando se llega al final del scroll */
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
isScrolling = false;
page++;
updateData();
}
}
});
}
return view;
}
public void updateData() {
pg.setVisibility(View.VISIBLE);
Map<String, String> data = new HashMap<>();
data.put("limit", String.valueOf(20));
data.put("page", String.valueOf(page));
CanguroService service = ServiceGenerator.createService(CanguroService.class);
Call<ContainerResponse<Canguro>> call = service.listCanguros(data);
call.enqueue(new Callback<ContainerResponse<Canguro>>() {
@Override
public void onResponse(Call<ContainerResponse<Canguro>> call, final Response<ContainerResponse<Canguro>> response) {
if (response.isSuccessful()) {
pg.setVisibility(View.GONE);
for (int i = 0; i < response.body().getRows().size(); i++) {
canguros.add(response.body().getRows().get(i));
}
adapter.notifyDataSetChanged();
}
else {
Toast.makeText(ctx, "Error al cargar datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ContainerResponse<Canguro>> call, Throwable t) {
Toast.makeText(ctx, "Error conexión", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onAttach(Context context) {
ctx = context;
super.onAttach(context);
if (context instanceof CanguroListener) {
mListener = (CanguroListener) context;
}
else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void getDataPerPage() {
Map<String, String> data = new HashMap<>();
data.put("limit", String.valueOf(20));
data.put("page", String.valueOf(1));
CanguroService service = ServiceGenerator.createService(CanguroService.class);
Call<ContainerResponse<Canguro>> call = service.listCanguros(data);
call.enqueue(new Callback<ContainerResponse<Canguro>>() {
@Override
public void onResponse(Call<ContainerResponse<Canguro>> call, Response<ContainerResponse<Canguro>> response) {
if (response.isSuccessful()) {
pg.setVisibility(View.GONE);
canguros = new ArrayList<>(response.body().getRows());
adapter = new CanguroAdapter(ctx, R.layout.fragment_canguro, canguros, mListener);
recyclerView.setAdapter(adapter);
Toast.makeText(ctx, response.body().getCount() + " resultados", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(ctx, "Error al cargar datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ContainerResponse<Canguro>> call, Throwable t) {
Toast.makeText(ctx, "Error conexión", Toast.LENGTH_SHORT).show();
}
});
setData = true;
}
}
|
UTF-8
|
Java
| 7,739 |
java
|
CanguroFragment.java
|
Java
|
[] | null |
[] |
package com.mjimenez.app_android.fragment_list;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.mjimenez.app_android.R;
import com.mjimenez.app_android.adapter.CanguroAdapter;
import com.mjimenez.app_android.interfaces.CanguroListener;
import com.mjimenez.app_android.models.Canguro;
import com.mjimenez.app_android.responses.ContainerResponse;
import com.mjimenez.app_android.retrofit.generator.ServiceGenerator;
import com.mjimenez.app_android.retrofit.services.CanguroService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CanguroFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
private CanguroListener mListener;
private CanguroAdapter adapter;
private Context ctx;
private RecyclerView recyclerView;
private ProgressBar pg;
private String city;
private List<Canguro> canguros = new ArrayList<>();
private boolean isScrolling = false;
private int currentItems, totalItems, scrollOutItems;
private int page = 0;
private boolean setData = false;
public CanguroFragment() {
}
public static CanguroFragment newInstance(int columnCount) {
CanguroFragment fragment = new CanguroFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_canguro_list, container, false);
pg = view.findViewById(R.id.canguro_list_pb);
Bundle bundle = this.getArguments();
if (bundle != null) {
city = bundle.getString("CIUDAD");
}
if (view instanceof ConstraintLayout) {
Context context = view.getContext();
recyclerView = view.findViewById(R.id.canguro_list);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
if (setData == false) {
page = 1;
getDataPerPage();
}
/*Para ir actualizando el RecyclerView cuando se llega al final del scroll */
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
currentItems = manager.getChildCount();
totalItems = manager.getItemCount();
scrollOutItems = manager.findFirstVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems)) {
isScrolling = false;
page++;
updateData();
}
}
});
}
return view;
}
public void updateData() {
pg.setVisibility(View.VISIBLE);
Map<String, String> data = new HashMap<>();
data.put("limit", String.valueOf(20));
data.put("page", String.valueOf(page));
CanguroService service = ServiceGenerator.createService(CanguroService.class);
Call<ContainerResponse<Canguro>> call = service.listCanguros(data);
call.enqueue(new Callback<ContainerResponse<Canguro>>() {
@Override
public void onResponse(Call<ContainerResponse<Canguro>> call, final Response<ContainerResponse<Canguro>> response) {
if (response.isSuccessful()) {
pg.setVisibility(View.GONE);
for (int i = 0; i < response.body().getRows().size(); i++) {
canguros.add(response.body().getRows().get(i));
}
adapter.notifyDataSetChanged();
}
else {
Toast.makeText(ctx, "Error al cargar datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ContainerResponse<Canguro>> call, Throwable t) {
Toast.makeText(ctx, "Error conexión", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onAttach(Context context) {
ctx = context;
super.onAttach(context);
if (context instanceof CanguroListener) {
mListener = (CanguroListener) context;
}
else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void getDataPerPage() {
Map<String, String> data = new HashMap<>();
data.put("limit", String.valueOf(20));
data.put("page", String.valueOf(1));
CanguroService service = ServiceGenerator.createService(CanguroService.class);
Call<ContainerResponse<Canguro>> call = service.listCanguros(data);
call.enqueue(new Callback<ContainerResponse<Canguro>>() {
@Override
public void onResponse(Call<ContainerResponse<Canguro>> call, Response<ContainerResponse<Canguro>> response) {
if (response.isSuccessful()) {
pg.setVisibility(View.GONE);
canguros = new ArrayList<>(response.body().getRows());
adapter = new CanguroAdapter(ctx, R.layout.fragment_canguro, canguros, mListener);
recyclerView.setAdapter(adapter);
Toast.makeText(ctx, response.body().getCount() + " resultados", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(ctx, "Error al cargar datos", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ContainerResponse<Canguro>> call, Throwable t) {
Toast.makeText(ctx, "Error conexión", Toast.LENGTH_SHORT).show();
}
});
setData = true;
}
}
| 7,739 | 0.619491 | 0.617294 | 190 | 39.721054 | 28.634192 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752632 | false | false |
10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.