blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
257a0ba0f3cc6f36db990ee0dddef643e50e20a9 | 01e9b936a523e2a9ea806488031b4f4f54a12118 | /src/epis/view/components/ExternField.java | c441365789898d6cd4655e06cbb27bbcc1111be1 | [] | no_license | JeanPoffo/epi-controller | 31050b1ff5f9333d70269807ce6b1e0f3099e9dc | 6ec04d00b42841affde53545c2a96383c00257a3 | refs/heads/master | 2022-12-03T21:48:08.493164 | 2020-08-18T18:20:23 | 2020-08-18T18:20:23 | 282,013,491 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 705 | java | package epis.view.components;
import epis.controller.ControllerMaintenance;
import javax.swing.JComboBox;
/**
* Class base for Extern Fields
* @author Jean Poffo
* @since 02/09/2020
*/
abstract public class ExternField extends JComboBox<Object> {
private ControllerMaintenance controller;
public ExternField(ControllerMaintenance controller) {
this.controller = controller;
this.initItems();
}
public ExternField() {}
protected void setController(ControllerMaintenance controller) {
this.controller = controller;
}
public ControllerMaintenance getController() {
return controller;
}
abstract void initItems();
}
| [
"[email protected]"
] | |
5cb6263fed741a3f60882487391fa454598c1bb0 | f77061a51e30fb93484bd34c0fb26d93791c4df1 | /src/main/java/com/alone/game/netty/net/Cmd.java | 1d4344e934f440fd97de079673c3d6ea306eff50 | [] | no_license | zhouxianjun/game-netty | a79ff98b27529ec50f39fc73b831591d56824665 | f3e57798b2267b895a328f6c3163a0ada665a919 | refs/heads/master | 2021-04-30T14:07:40.706585 | 2018-02-12T06:50:09 | 2018-02-12T06:50:09 | 121,210,863 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | package com.alone.game.netty.net;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Cmd {
/**
* 请求消息包ID
* @return
*/
short value();
/**
* 是否异步
* @return
*/
boolean async() default false;
/**
* 是否需要登录
* @return
*/
boolean login() default false;
short GLOBAL_EXCEPTION = 0x0000;
short PING = 0x0001;
}
| [
"[email protected]"
] | |
41acbe1a566ecd31f7b7bcdf0d3b82c7658f40dc | e052d3d97f235d33b69d47090c10c90bb996f413 | /Java/FancyFence.java | c5ab59c23b4b2c34cd17e6837a5a29883e1a2a67 | [
"MIT"
] | permissive | sumitesh9/Competitive-Programming | c684e666eeabfefa5c0740ec0d4d52291ae7f2eb | f7798058c13aa4b9e7ff418d84b55ce54dcb7224 | refs/heads/master | 2021-07-03T13:25:27.334397 | 2020-08-26T16:47:23 | 2020-08-26T16:47:23 | 149,843,354 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,412 | java | /*
* No package must be added here because some Online Judges don't support it
* please remove, if any.
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* Only classes with 'Main' name are accepted in CodeChef and some other online judges
*/
public class FancyFence {
/*
* In a Programming contest, you are expected to print the output at the
* end, so `output` variable will hold all the processed results till the
* end
*/
// Program's starting point
public static void main(String[] args) {
/*
* A Scanner class slows down Input/Output a LOT ,thereby increasing
* your code execution time , Hence for best results that is Fast I/O
* try to use BufferedReader
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
/*
* Generally Code Chef, Hacker Rank gives X number of test cases so we
* process the input for each.
*/
final int cases;
try {
cases = Integer.parseInt(br.readLine().trim());
/*
* Logic of the program must be separated from the meta code to
* increase readability and help debugging easier
* Also note that Solver object is created inside for loop to
* avoid multiple object creation that drastically increases
* execution time and memory usage
*/
Solver solver = new Solver();
for (int i = 0; i < cases; i++) {
solver.solve(br.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* Some basic rules while coding in Programming Contests:
* Try to follow at least 80% of them
Correctness
- final declaration for required data types
- avoid Object creation
- Scanner slows down, use InputReader
- avoid too many static functions
Efficiency
- use library functions as much as possible
- assertEquals("RESULT", functionToCall())
Debugging-ability
- avoid too many global variables
- Separate logic from meta-processing
- variable/function pneumonics must make sense
*
*/
class Solver {
/*
* Logic goes here ...
* Add to the global variables after processing the input
* Maybe reverse a string or parse to an integer or , etc.
*/
public void solve(String input) {
int a=Integer.parseInt(input);
if(360%(180-a)==0)
{
System.out.println("YES");
}
else
System.out.println("NO");
}
} | [
"[email protected]"
] | |
901baaa9aafd43364b3928023fbf8b79af8ade7b | 5cb1a8ffe3ed009c85d534c5ac0b00d3fb447626 | /subprojects/core/src/main/java/org/gradle/api/internal/tasks/properties/CompositeOutputFilePropertySpec.java | ac155be74bf5e1e79d74c518c92c07c838177a6e | [
"BSD-3-Clause",
"LGPL-2.1-or-later",
"MIT",
"CPL-1.0",
"Apache-2.0",
"LGPL-2.1-only",
"LicenseRef-scancode-mit-old-style"
] | permissive | Verdinjoshua26/gradle | f11184f20bf45456d8a903c6677cc29a0ac1117b | cfeeb71d1e3159f5d10856aef854344ba92c4a0f | refs/heads/master | 2023-08-05T20:44:50.692054 | 2019-05-17T13:59:27 | 2019-05-17T13:59:30 | 187,253,049 | 2 | 0 | Apache-2.0 | 2023-07-22T05:59:51 | 2019-05-17T17:00:44 | Groovy | UTF-8 | Java | false | false | 1,266 | java | /*
* Copyright 2019 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 org.gradle.api.internal.tasks.properties;
import org.gradle.api.file.FileCollection;
import org.gradle.internal.file.TreeType;
import org.gradle.internal.fingerprint.OutputNormalizer;
public class CompositeOutputFilePropertySpec extends AbstractFilePropertySpec implements OutputFilePropertySpec {
private final TreeType outputType;
public CompositeOutputFilePropertySpec(String propertyName, FileCollection files, TreeType outputType) {
super(propertyName, OutputNormalizer.class, files);
this.outputType = outputType;
}
@Override
public TreeType getOutputType() {
return outputType;
}
}
| [
"[email protected]"
] | |
bb4a44c5a619d92c6f4195f375f315207e567814 | 6db1da7744f3e0fdd9660dca46348d7fdbe395f7 | /src/main/java/com/example/hotelmanagementsystem/model/UserProfile.java | 64ac00b58e8ec1254c456a3c010d30ac9fd6da2f | [] | no_license | YuMayVel/awshotel | 226497a3614f8cc0ebe63a1aa8b87cde19f27471 | 0337038e66dea4f1a7a1c873853da13a3706f20d | refs/heads/master | 2020-07-23T05:55:49.372079 | 2019-09-18T05:43:33 | 2019-09-18T05:43:33 | 207,464,719 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,964 | java | package com.example.hotelmanagementsystem.model;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Entity
public class UserProfile implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String password;
private String email;
private String phoneNumber;
@Enumerated(EnumType.STRING)
private Gender gender;
public UserProfile() {
}
public UserProfile(String firstName, String lastName, String email, String phoneNumber, Gender gender) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
this.gender = gender;
}
@ManyToMany(fetch = FetchType.EAGER)
private List<Role> roles=new ArrayList<>();
public void addRole(Role role){
roles.add(role);
}
public void addRoles(ArrayList<Role> list){
roles.addAll(list);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles
.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toSet());
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setPassword(String password) {
this.password = password;
}
}
| [
"[email protected]"
] | |
b445dcef9027e7759bb31c299de36493aa5c2ce8 | 25994354b440251084dcb020177b8bbcfa61481c | /Week2/Lab-Stack/src/Stack.java | f7b1693c2b4306d174b74250e47fb48ec836a6ab | [] | no_license | amitchellrevature/RevatureDemos | 62a7ce6df01bc63433af4b13a6e9413423f9f909 | 5a2b100c1e45a569e9c57fae90cbeda20a732cd8 | refs/heads/main | 2023-07-14T01:56:36.666461 | 2021-08-30T21:06:43 | 2021-08-30T21:06:43 | 390,311,848 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 1,410 | java | import java.util.Arrays;
public class Stack {
private int lastItem = 0;
private int[] items = new int[0];
// add items to the stack
public void push(int newItem) {
int index = items.length; // get current length to store as index
System.out.println("The array length is: " + index);
int[] tempItems = new int[items.length + 1]; // increase the array by 1
for(int i = 0; i < items.length; i++)
tempItems[i] = items[i];
System.out.println("items after extending the length by 1: " + Arrays.toString(tempItems));
items = tempItems;
items[index] = newItem; // store the value in the index
System.out.println("items after storing the new value: "+ Arrays.toString(items));
lastItem = newItem; // update lastItem
System.out.println("The last item: " + lastItem);
}
// remove items from the stack
public int pop(){
int tempItem = lastItem; //store the last item into a variable
//copy a new array but remove last item
int[] newArray = new int[items.length-1];
for(int i = 0; i < newArray.length; i++){
newArray[i] = items[i];
}
items = newArray; //update the items array
if(items.length > 0)
lastItem = items[items.length-1]; //update lastItem
else
lastItem = 0;
//return our ‘popped' element
return tempItem;
}
// view last item
public int peek() {
return lastItem;
}
} | [
"[email protected]"
] | |
eab7bd53043b6c205030b8fe78575299920c50a1 | 065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be | /eclipsejdt_cluster/46735/src_1.java | 65540d59d2063ca73cc4762283ecb20022b5c5b2 | [] | no_license | martinezmatias/GenPat-data-C3 | 63cfe27efee2946831139747e6c20cf952f1d6f6 | b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4 | refs/heads/master | 2022-04-25T17:59:03.905613 | 2020-04-15T14:41:34 | 2020-04-15T14:41:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 121,278 | java | /*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This is an implementation of an early-draft specification developed under the Java
* Community Process (JCP) and is made available for testing and evaluation purposes
* only. The code is not compatible with any specification of the JCP.
*
* Contributors:
* IBM Corporation - initial API and implementation
* Stephan Herrmann <[email protected]> - Contributions for
* bug 282152 - [1.5][compiler] Generics code rejected by Eclipse but accepted by javac
* bug 395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
* bug 401456 - Code compiles from javac/intellij, but fails from eclipse
* bug 405706 - Eclipse compiler fails to give compiler error when return type is a inferred generic
* Bug 408441 - Type mismatch using Arrays.asList with 3 or more implementations of an interface with the interface type as the last parameter
* Bug 413958 - Function override returning inherited Generic Type
* Bug 415734 - Eclipse gives compilation error calling method with an inferred generic return type
* Bug 400874 - [1.8][compiler] Inference infrastructure should evolve to meet JLS8 18.x (Part G of JSR335 spec)
*******************************************************************************/
package org.eclipse.jdt.core.tests.compiler.regression;
import java.util.Map;
import junit.framework.Test;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class GenericsRegressionTest extends AbstractComparableTest {
public GenericsRegressionTest(String name) {
super(name);
}
// Static initializer to specify tests subset using TESTS_* static variables
// All specified tests which does not belong to the class are skipped...
static {
// TESTS_NAMES = new String[] { "testBug415734" };
// TESTS_NAMES = new String[] { "testBug413958" };
// TESTS_NUMBERS = new int[] { 1465 };
// TESTS_RANGE = new int[] { 1097, -1 };
}
public static Test suite() {
return buildComparableTestSuite(testClass());
}
public static Class testClass() {
return GenericsRegressionTest.class;
}
protected Map getCompilerOptions() {
Map compilerOptions = super.getCompilerOptions();
compilerOptions.put(CompilerOptions.OPTION_ReportMissingOverrideAnnotationForInterfaceMethodImplementation, CompilerOptions.DISABLED);
compilerOptions.put(CompilerOptions.OPTION_ReportUnusedTypeParameter,CompilerOptions.IGNORE);
return compilerOptions;
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void _test322531a() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public class X {\n" +
" <T extends I> void main(Class<T> clazz) {\n" +
" boolean b = \n" +
" clazz == clazz || \n" +
" X.class == X.class || \n" +
" I.class == I.class || \n" +
" clazz == X.class || \n" +
" X.class == clazz || \n" +
" clazz == I.class || \n" +
" I.class == clazz || \n" +
" I.class == X.class ||\n" +
" X.class == I.class;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 5)\n" +
" clazz == clazz || \n" +
" ^^^^^^^^^^^^^^\n" +
"Comparing identical expressions\n" +
"----------\n" +
"2. ERROR in X.java (at line 8)\n" +
" clazz == X.class || \n" +
" ^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<T> and Class<X>\n" +
"----------\n" +
"3. ERROR in X.java (at line 9)\n" +
" X.class == clazz || \n" +
" ^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<T>\n" +
"----------\n" +
"4. ERROR in X.java (at line 12)\n" +
" I.class == X.class ||\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"5. ERROR in X.java (at line 13)\n" +
" X.class == I.class;\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531b() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public class X implements I {\n" +
" <T extends I> void main(Class<T> clazz) {\n" +
" boolean b = \n" +
" clazz == clazz || \n" +
" X.class == X.class || \n" +
" I.class == I.class || \n" +
" clazz == X.class || \n" +
" X.class == clazz || \n" +
" clazz == I.class || \n" +
" I.class == clazz || \n" +
" I.class == X.class ||\n" +
" X.class == I.class;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 5)\n" +
" clazz == clazz || \n" +
" ^^^^^^^^^^^^^^\n" +
"Comparing identical expressions\n" +
"----------\n" +
"2. ERROR in X.java (at line 12)\n" +
" I.class == X.class ||\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"3. ERROR in X.java (at line 13)\n" +
" X.class == I.class;\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531c() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public class X {\n" +
" <T extends I> void main(Class<T> clazz, X x) {\n" +
" boolean b = \n" +
" x.getClass() == clazz || \n" +
" clazz == x.getClass(); \n" +
" }\n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531d() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public final class X {\n" +
" <T extends I> void main(Class<T> clazz, X x) {\n" +
" boolean b = \n" +
" x.getClass() == clazz || \n" +
" clazz == x.getClass(); \n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" x.getClass() == clazz || \n" +
" ^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<capture#1-of ? extends X> and Class<T>\n" +
"----------\n" +
"2. ERROR in X.java (at line 6)\n" +
" clazz == x.getClass(); \n" +
" ^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<T> and Class<capture#2-of ? extends X>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531e() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public final class X implements I {\n" +
" <T extends I> void main(Class<T> clazz, X x) {\n" +
" boolean b = \n" +
" x.getClass() == clazz || \n" +
" clazz == x.getClass(); \n" +
" }\n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531f() {
this.runNegativeTest(
new String[] {
"X.java",
"class I {}\n" +
"public class X {\n" +
" <T extends I> void main(Class<T> clazz, X x) {\n" +
" boolean b = \n" +
" x.getClass() == clazz || \n" +
" clazz == x.getClass(); \n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" x.getClass() == clazz || \n" +
" ^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<capture#1-of ? extends X> and Class<T>\n" +
"----------\n" +
"2. ERROR in X.java (at line 6)\n" +
" clazz == x.getClass(); \n" +
" ^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<T> and Class<capture#2-of ? extends X>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void _test322531g() {
this.runNegativeTest(
new String[] {
"X.java",
"interface List<E> {}\n" +
"interface I {}\n" +
"public class X implements I {\n" +
" void main(List<I> li, X t) {\n" +
" boolean b = I.class == t.getClass();\n" +
" b = li == t.getList();\n" +
" }\n" +
" \n" +
" List<? extends Object> getList() {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" boolean b = I.class == t.getClass();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<capture#1-of ? extends X>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void _test322531h() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public class X implements I {\n" +
" <T extends I> void main(Class<T> clazz, X t) {\n" +
" boolean b = \n" +
" clazz == t.getClass() || \n" +
" t.getClass() == clazz || \n" +
" I.class == t.getClass() ||\n" +
" t.getClass() == I.class;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 7)\n" +
" I.class == t.getClass() ||\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<capture#3-of ? extends X>\n" +
"----------\n" +
"2. ERROR in X.java (at line 8)\n" +
" t.getClass() == I.class;\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<capture#4-of ? extends X> and Class<I>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void test322531i() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {};\n" +
"public class X {\n" +
" public X() {\n" +
" }\n" +
" public <T extends I> void test(Class<T> clazz) {\n" +
" Class<I> ci = I.class;\n" +
" Class<X> ti = X.class;\n" +
" boolean b = ci == X.class ||\n" +
" X.class == ci ||\n" +
" I.class == X.class ||\n" +
" X.class == I.class ||\n" +
" ti == I.class ||\n" +
" I.class == ti ||\n" +
" ti == ci ||\n" +
" ci == ti;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 8)\n" +
" boolean b = ci == X.class ||\n" +
" ^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"2. ERROR in X.java (at line 9)\n" +
" X.class == ci ||\n" +
" ^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n" +
"3. ERROR in X.java (at line 10)\n" +
" I.class == X.class ||\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"4. ERROR in X.java (at line 11)\n" +
" X.class == I.class ||\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n" +
"5. ERROR in X.java (at line 12)\n" +
" ti == I.class ||\n" +
" ^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n" +
"6. ERROR in X.java (at line 13)\n" +
" I.class == ti ||\n" +
" ^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"7. ERROR in X.java (at line 14)\n" +
" ti == ci ||\n" +
" ^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n" +
"8. ERROR in X.java (at line 15)\n" +
" ci == ti;\n" +
" ^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322531
public void _test322531j() {
this.runNegativeTest(
new String[] {
"X.java",
"interface I {}\n" +
"public class X {\n" +
" <T extends I> void main(Class<T> clazz) {\n" +
" boolean b = \n" +
" clazz != clazz || \n" +
" X.class != X.class || \n" +
" I.class != I.class || \n" +
" clazz != X.class || \n" +
" X.class != clazz || \n" +
" clazz != I.class || \n" +
" I.class != clazz || \n" +
" I.class != X.class ||\n" +
" X.class != I.class;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 5)\n" +
" clazz != clazz || \n" +
" ^^^^^^^^^^^^^^\n" +
"Comparing identical expressions\n" +
"----------\n" +
"2. ERROR in X.java (at line 8)\n" +
" clazz != X.class || \n" +
" ^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<T> and Class<X>\n" +
"----------\n" +
"3. ERROR in X.java (at line 9)\n" +
" X.class != clazz || \n" +
" ^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<T>\n" +
"----------\n" +
"4. ERROR in X.java (at line 12)\n" +
" I.class != X.class ||\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<I> and Class<X>\n" +
"----------\n" +
"5. ERROR in X.java (at line 13)\n" +
" X.class != I.class;\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Incompatible operand types Class<X> and Class<I>\n" +
"----------\n");
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=282152
public void test282152() {
this.runConformTest(
new String[] {
"Test.java",
"public interface Test<T extends Number> {\n" +
" public <U> void test(Test<? super U> t, U value);\n" +
" public void setValue(T v);" +
"}",
"Impl.java",
"public class Impl<T extends Number> implements Test<T>{\n" +
" T val;" +
" public <U> void test(Test<? super U> t, U value) {\n" +
" t.setValue(value);\n" +
" }\n" +
" public void setValue(T v) {\n" +
" this.val = v;\n" +
" }\n" +
"}",
"Client.java",
"public class Client {\n" +
" void test() {\n" +
" Impl<Integer> t1 = new Impl<Integer>();\n" +
" Double n = Double.valueOf(3.14);\n" +
" t1.test(new Impl<Number>(), n);\n" +
" }\n" +
"}\n"
},
""); // no specific success output string
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=282152
// violating lower bound
public void test282152b() {
this.runNegativeTest(
new String[] {
"Test.java",
"public interface Test<T extends Number> {\n" +
" public <U> void test(Test<? super U> t, U value);\n" +
" public void setValue(T v);" +
"}",
"Impl.java",
"public class Impl<T extends Number> implements Test<T>{\n" +
" T val;" +
" public <U> void test(Test<? super U> t, U value) {\n" +
" t.setValue(value);\n" +
" }\n" +
" public void setValue(T v) {\n" +
" this.val = v;\n" +
" }\n" +
"}",
"Client.java",
"public class Client {\n" +
" void test() {\n" +
" Impl<Integer> t1 = new Impl<Integer>();\n" +
" Number n = Double.valueOf(3.14);\n" +
" t1.test(new Impl<Double>(), n);\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in Client.java (at line 5)\n" +
" t1.test(new Impl<Double>(), n);\n" +
" ^^^^\n" +
"The method test(Test<? super U>, U) in the type Impl<Integer> is not applicable for the arguments (Impl<Double>, Number)\n" +
"----------\n");
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=282152
// contradictory bounds
public void test282152c() {
this.runNegativeTest(
new String[] {
"Test.java",
"public interface Test<T extends Number> {\n" +
" public <U extends Exception> void test(Test<? super U> t, U value);\n" +
" public void setValue(T v);" +
"}"
},
"----------\n" +
"1. ERROR in Test.java (at line 2)\n" +
" public <U extends Exception> void test(Test<? super U> t, U value);\n" +
" ^^^^^^^^^\n" +
"Bound mismatch: The type ? super U is not a valid substitute for the bounded parameter <T extends Number> of the type Test<T>\n" +
"----------\n");
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=282152
// compatible constraints
public void test282152d() {
this.runConformTest(
new String[] {
"Test.java",
"public interface Test<T extends Number> {\n" +
" public <U extends Integer> void test(Test<? super U> t, U value);\n" +
" public void setValue(T v);" +
"}",
"Impl.java",
"public class Impl<T extends Number> implements Test<T>{\n" +
" T val;" +
" public <U extends Integer> void test(Test<? super U> t, U value) {\n" +
" t.setValue(value);\n" +
" }\n" +
" public void setValue(T v) {\n" +
" this.val = v;\n" +
" }\n" +
"}",
"Client.java",
"public class Client {\n" +
" void test() {\n" +
" Impl<Integer> t1 = new Impl<Integer>();\n" +
" Integer i = Integer.valueOf(3);\n" +
" t1.test(new Impl<Integer>(), i);\n" +
" }\n" +
"}\n"
},
""); // no specific success output string
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=282152
// direct use of type variable does not involve capture, thus no merging of constraints happens
public void test282152e() {
this.runNegativeTest(
new String[] {
"Test.java",
"public interface Test<T extends Number> {\n" +
" public <U> void test(Test<U> t, U value);\n" +
" public void setValue(T v);" +
"}"
},
"----------\n" +
"1. ERROR in Test.java (at line 2)\n" +
" public <U> void test(Test<U> t, U value);\n" +
" ^\n" +
"Bound mismatch: The type U is not a valid substitute for the bounded parameter <T extends Number> of the type Test<T>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330869
public void test330869() {
this.runConformTest(
new String[] {
"X.java",
"public class X {\n" +
" public <T> T getAdapter(Class<? extends T> adapterType) {\n" +
" T result = null;\n" +
" if (adapterType == Foo.class) {\n" +
" }\n" +
" else if (adapterType == Bar.class) {\n" +
" }\n" +
" return result;\n" +
" }\n" +
" public class Foo {\n" +
" }\n" +
" public interface Bar {\n" +
" }\n" +
"}\n"
},
""); // no specific success output string
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"interface Adaptable {\n" +
" public Object getAdapter(Class clazz); \n" +
"}\n" +
"public class X implements Adaptable {\n" +
" public Object getAdapter(Class clazz) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 2)\n" +
" public Object getAdapter(Class clazz); \n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817b() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"X.java",
"interface Adaptable {\n" +
" public Object getAdapter(Class clazz); \n" +
"}\n" +
"public class X implements Adaptable {\n" +
" public Object getAdapter(Class clazz) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 2)\n" +
" public Object getAdapter(Class clazz); \n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" public Object getAdapter(Class clazz) {\n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817c() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"interface Adaptable {\n" +
" public Object getAdapter(Class<String> clazz); \n" +
"}\n" +
"public class X implements Adaptable {\n" +
" public Object getAdapter(Class clazz) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 5)\n" +
" public Object getAdapter(Class clazz) {\n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817d() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"interface Adaptable {\n" +
" public Object getAdapter(Class<String> clazz); \n" +
"}\n" +
"public class X implements Adaptable {\n" +
" public Object getAdapter(Class clazz) {\n" +
" return null;\n" +
" }\n" +
"}\n" +
"class Y extends X {\n" +
" @Override\n" +
" public Object getAdapter(Class clazz) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 5)\n" +
" public Object getAdapter(Class clazz) {\n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817e() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.List;\n" +
"class Top {\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
"}\n" +
"class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) { // should not warn (overrides)\n" +
" }\n" +
" @Override\n" +
" public List get() { // should not warn (overrides)\n" +
" return super.get();\n" +
" }\n" +
"}\n" +
"public class X {\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 4)\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817
public void test322817f() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.List;\n" +
"class Top {\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" public List<String> get() { return null; }\n" +
"}\n" +
"class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) { // should not warn (overrides)\n" +
" }\n" +
" @Override\n" +
" public List get() { // should warn (super's return type is not raw)\n" +
" return super.get();\n" +
" }\n" +
"}\n" +
"public class X {\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 11)\n" +
" public List get() { // should warn (super\'s return type is not raw)\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 11)\n" +
" public List get() { // should warn (super\'s return type is not raw)\n" +
" ^^^^\n" +
"Type safety: The return type List for get() from the type Sub needs unchecked conversion to conform to List<String> from the type Top\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817 (Disable reporting of unavoidable problems)
public void test322817g() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"Top.java",
"import java.util.List;\n" +
"public class Top {\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
" List list; // OK to warn in 1.5 code\n" +
"}\n",
"Sub.java",
"import java.util.List;\n" +
"public class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) { // should not warn (overrides)\n" +
" super.set(arg);\n" +
" arg.set(0, \"A\"); // should not warn ('arg' is forced raw)\n" +
" }\n" +
" @Override\n" +
" public List get() { // should not warn (overrides)\n" +
" return super.get();\n" +
" }\n" +
"}\n",
"X.java",
"import java.util.List;\n" +
"public class X {\n" +
" void run() {\n" +
" new Top().list.add(\"arg\"); // should not warn (uses raw field declared elsewhere)\n" +
" new Top().get().add(\"arg\"); // should not warn (uses raw API)\n" +
" List raw= new Top().get(); // OK to warn ('raw' declared here)\n" +
" raw.add(\"arg\"); // OK to warn ('raw' declared here)\n" +
" // When Top#get() is generified, both of the following will fail\n" +
" // with a compile error if type arguments don't match:\n" +
" List<String> unchecked= new Top().get(); // should not warn (forced)\n" +
" unchecked.add(\"x\");\n" +
" // Should not warn about unchecked cast, but should warn about\n" +
" // unnecessary cast:\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" cast.add(\"x\");\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in Top.java (at line 3)\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Top.java (at line 4)\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in Top.java (at line 5)\n" +
" List list; // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"----------\n" +
"1. WARNING in X.java (at line 6)\n" +
" List raw= new Top().get(); // OK to warn (\'raw\' declared here)\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 7)\n" +
" raw.add(\"arg\"); // OK to warn (\'raw\' declared here)\n" +
" ^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 14)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Unnecessary cast from List to List<String>\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817 (Enable reporting of unavoidable problems)
public void test322817h() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"Top.java",
"import java.util.List;\n" +
"public class Top {\n" +
" public void set(List arg) { }\n" +
" public List get() { return null; }\n" +
" List list;\n" +
"}\n",
"Sub.java",
"import java.util.List;\n" +
"public class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) {\n" +
" super.set(arg);\n" +
" arg.set(0, \"A\");\n" +
" }\n" +
" @Override\n" +
" public List get() {\n" +
" return super.get();\n" +
" }\n" +
"}\n",
"X.java",
"import java.util.List;\n" +
"public class X {\n" +
" void run() {\n" +
" new Top().list.add(\"arg\");\n" +
" new Top().get().add(\"arg\");\n" +
" List raw= new Top().get();\n" +
" raw.add(\"arg\");\n" +
" List<String> unchecked= new Top().get();\n" +
" unchecked.add(\"x\");\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" cast.add(\"x\");\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in Top.java (at line 3)\n" +
" public void set(List arg) { }\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Top.java (at line 4)\n" +
" public List get() { return null; }\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in Top.java (at line 5)\n" +
" List list;\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"----------\n" +
"1. WARNING in Sub.java (at line 4)\n" +
" public void set(List arg) {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Sub.java (at line 6)\n" +
" arg.set(0, \"A\");\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method set(int, Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in Sub.java (at line 9)\n" +
" public List get() {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"----------\n" +
"1. WARNING in X.java (at line 4)\n" +
" new Top().list.add(\"arg\");\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" new Top().get().add(\"arg\");\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 6)\n" +
" List raw= new Top().get();\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 7)\n" +
" raw.add(\"arg\");\n" +
" ^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"5. WARNING in X.java (at line 8)\n" +
" List<String> unchecked= new Top().get();\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type List needs unchecked conversion to conform to List<String>\n" +
"----------\n" +
"6. WARNING in X.java (at line 10)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from List to List<String>\n" +
"----------\n" +
"7. WARNING in X.java (at line 10)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Unnecessary cast from List to List<String>\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817 (Default options)
public void test322817i() {
Map customOptions = getCompilerOptions();
this.runNegativeTest(
new String[] {
"Top.java",
"import java.util.List;\n" +
"public class Top {\n" +
" public void set(List arg) { }\n" +
" public List get() { return null; }\n" +
" List list;\n" +
"}\n",
"Sub.java",
"import java.util.List;\n" +
"public class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) {\n" +
" super.set(arg);\n" +
" arg.set(0, \"A\");\n" +
" }\n" +
" @Override\n" +
" public List get() {\n" +
" return super.get();\n" +
" }\n" +
"}\n",
"X.java",
"import java.util.List;\n" +
"public class X {\n" +
" void run() {\n" +
" new Top().list.add(\"arg\");\n" +
" new Top().get().add(\"arg\");\n" +
" List raw= new Top().get();\n" +
" raw.add(\"arg\");\n" +
" List<String> unchecked= new Top().get();\n" +
" unchecked.add(\"x\");\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" cast.add(\"x\");\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in Top.java (at line 3)\n" +
" public void set(List arg) { }\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Top.java (at line 4)\n" +
" public List get() { return null; }\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in Top.java (at line 5)\n" +
" List list;\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"----------\n" +
"1. WARNING in Sub.java (at line 4)\n" +
" public void set(List arg) {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Sub.java (at line 6)\n" +
" arg.set(0, \"A\");\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method set(int, Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in Sub.java (at line 9)\n" +
" public List get() {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"----------\n" +
"1. WARNING in X.java (at line 4)\n" +
" new Top().list.add(\"arg\");\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" new Top().get().add(\"arg\");\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 6)\n" +
" List raw= new Top().get();\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 7)\n" +
" raw.add(\"arg\");\n" +
" ^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"5. WARNING in X.java (at line 8)\n" +
" List<String> unchecked= new Top().get();\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type List needs unchecked conversion to conform to List<String>\n" +
"----------\n" +
"6. WARNING in X.java (at line 10)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from List to List<String>\n" +
"----------\n" +
"7. WARNING in X.java (at line 10)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Unnecessary cast from List to List<String>\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817 (all in same file)
public void test322817j() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.List;\n" +
"class Top {\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
"}\n" +
"class Sub extends Top {\n" +
" @Override\n" +
" public void set(List arg) { // should not warn (overrides)\n" +
" super.set(arg);\n" +
" arg.set(0, \"A\"); // should not warn ('arg' is forced raw)\n" +
" }\n" +
" @Override\n" +
" public List get() { // should not warn (overrides)\n" +
" return super.get();\n" +
" }\n" +
"}\n" +
"public class X {\n" +
" void run() {\n" +
" new Top().get().add(\"arg\");\n" +
" List raw= new Top().get(); // OK to warn ('raw' declared here)\n" +
" raw.add(\"arg\"); // OK to warn ('raw' declared here)\n" +
" List<String> unchecked= new Top().get();\n" +
" unchecked.add(\"x\");\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" cast.add(\"x\");\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" public void set(List arg) { } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 4)\n" +
" public List get() { return null; } // OK to warn in 1.5 code\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 19)\n" +
" new Top().get().add(\"arg\");\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 20)\n" +
" List raw= new Top().get(); // OK to warn (\'raw\' declared here)\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"5. WARNING in X.java (at line 21)\n" +
" raw.add(\"arg\"); // OK to warn (\'raw\' declared here)\n" +
" ^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"6. WARNING in X.java (at line 22)\n" +
" List<String> unchecked= new Top().get();\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type List needs unchecked conversion to conform to List<String>\n" +
"----------\n" +
"7. WARNING in X.java (at line 24)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from List to List<String>\n" +
"----------\n" +
"8. WARNING in X.java (at line 24)\n" +
" List<String> cast= (List<String>) new Top().get();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Unnecessary cast from List to List<String>\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=322817 (make sure there is no NPE when receiver is null)
public void test322817k() {
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.Arrays;\n" +
"import java.util.Set;\n" +
"import java.util.HashSet;\n" +
"public class X {\n" +
" public void foo(String[] elements) {\n" +
" Set set= new HashSet(Arrays.asList(elements));\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 6)\n" +
" Set set= new HashSet(Arrays.asList(elements));\n" +
" ^^^\n" +
"Set is a raw type. References to generic type Set<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 6)\n" +
" Set set= new HashSet(Arrays.asList(elements));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The constructor HashSet(Collection) belongs to the raw type HashSet. References to generic type HashSet<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 6)\n" +
" Set set= new HashSet(Arrays.asList(elements));\n" +
" ^^^^^^^\n" +
"HashSet is a raw type. References to generic type HashSet<E> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=338350 (unchecked cast - only unavoidable on raw expression)
public void test338350() {
String[] testFiles = new String[] {
"Try.java",
"import java.lang.reflect.Array;\n" +
"import java.util.ArrayList;\n" +
"import java.util.List;\n" +
"public class Try<E> {\n" +
" void fooObj() {\n" +
" takeObj((E) Bar.getObject());\n" +
" takeObj((E) Bar.getArray());\n" +
" takeObj((E) Array.newInstance(Integer.class, 2));\n" +
" }\n" +
" void takeObj(E obj) { }\n" +
" void fooArray() {\n" +
" takeArray((E[]) Bar.getArray());\n" +
" takeArray((E[]) Array.newInstance(Integer.class, 2));\n" +
" }\n" +
" void takeArray(E[] array) { }\n" +
" <L> void foo(List<L> list) {\n" +
" list.toArray((L[]) Bar.getArray());\n" +
" list.toArray((L[]) Array.newInstance(Integer.class, 2));\n" +
" }\n" +
" void bar() {\n" +
" List<String> l = (List<String>) Bar.getObject();\n" +
" List<String> l2 = Bar.getRawList();\n" +
" ArrayList<String> l3 = (ArrayList<String>) Bar.getRawList();\n" +
" }\n" +
"}\n",
"Bar.java",
"import java.lang.reflect.Array;\n" +
"import java.util.ArrayList;\n" +
"import java.util.List;\n" +
"public class Bar {\n" +
" public static Object getObject() {\n" +
" return new Object();\n" +
" }\n" +
" public static Object[] getArray() {\n" +
" return (Object[]) Array.newInstance(Integer.class, 2);\n" +
" }\n" +
" public static List getRawList() {\n" +
" return new ArrayList();\n" +
" }\n" +
"}\n"
};
Map customOptions = getCompilerOptions();
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
testFiles,
"----------\n" +
"1. WARNING in Try.java (at line 6)\n" +
" takeObj((E) Bar.getObject());\n" +
" ^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E\n" +
"----------\n" +
"2. WARNING in Try.java (at line 7)\n" +
" takeObj((E) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to E\n" +
"----------\n" +
"3. WARNING in Try.java (at line 8)\n" +
" takeObj((E) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E\n" +
"----------\n" +
"4. WARNING in Try.java (at line 12)\n" +
" takeArray((E[]) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to E[]\n" +
"----------\n" +
"5. WARNING in Try.java (at line 13)\n" +
" takeArray((E[]) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E[]\n" +
"----------\n" +
"6. WARNING in Try.java (at line 17)\n" +
" list.toArray((L[]) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to L[]\n" +
"----------\n" +
"7. WARNING in Try.java (at line 18)\n" +
" list.toArray((L[]) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to L[]\n" +
"----------\n" +
"8. WARNING in Try.java (at line 21)\n" +
" List<String> l = (List<String>) Bar.getObject();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to List<String>\n" +
"----------\n" +
"9. WARNING in Try.java (at line 22)\n" +
" List<String> l2 = Bar.getRawList();\n" +
" ^^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type List needs unchecked conversion to conform to List<String>\n" +
"----------\n" +
"10. WARNING in Try.java (at line 23)\n" +
" ArrayList<String> l3 = (ArrayList<String>) Bar.getRawList();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from List to ArrayList<String>\n" +
"----------\n" +
"----------\n" +
"1. WARNING in Bar.java (at line 11)\n" +
" public static List getRawList() {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Bar.java (at line 12)\n" +
" return new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
customOptions.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
testFiles,
"----------\n" +
"1. WARNING in Try.java (at line 6)\n" +
" takeObj((E) Bar.getObject());\n" +
" ^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E\n" +
"----------\n" +
"2. WARNING in Try.java (at line 7)\n" +
" takeObj((E) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to E\n" +
"----------\n" +
"3. WARNING in Try.java (at line 8)\n" +
" takeObj((E) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E\n" +
"----------\n" +
"4. WARNING in Try.java (at line 12)\n" +
" takeArray((E[]) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to E[]\n" +
"----------\n" +
"5. WARNING in Try.java (at line 13)\n" +
" takeArray((E[]) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to E[]\n" +
"----------\n" +
"6. WARNING in Try.java (at line 17)\n" +
" list.toArray((L[]) Bar.getArray());\n" +
" ^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object[] to L[]\n" +
"----------\n" +
"7. WARNING in Try.java (at line 18)\n" +
" list.toArray((L[]) Array.newInstance(Integer.class, 2));\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to L[]\n" +
"----------\n" +
"8. WARNING in Try.java (at line 21)\n" +
" List<String> l = (List<String>) Bar.getObject();\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked cast from Object to List<String>\n" +
"----------\n" +
"----------\n" +
"1. WARNING in Bar.java (at line 11)\n" +
" public static List getRawList() {\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in Bar.java (at line 12)\n" +
" return new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n",
null,
true,
customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622 (private access - different packages)
public void test334622a() {
this.runNegativeTest(
new String[] {
"p/X.java",
"package p;\n" +
"public class X {\n" +
" private Object foo;\n" +
"}\n",
"q/Y.java",
"package q;\n" +
"import p.X;\n" +
"public class Y {\n" +
" public <T extends X> void test(T t) {\n" +
" System.out.println(t.foo);\n" +
" }\n" +
" Zork z;\n" +
"}\n"
},
"----------\n" +
"1. WARNING in p\\X.java (at line 3)\n" +
" private Object foo;\n" +
" ^^^\n" +
"The value of the field X.foo is not used\n" +
"----------\n" +
"----------\n" +
"1. ERROR in q\\Y.java (at line 5)\n" +
" System.out.println(t.foo);\n" +
" ^^^\n" +
"The field X.foo is not visible\n" +
"----------\n" +
"2. ERROR in q\\Y.java (at line 7)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622 (private access - same package)
public void test334622b() {
this.runNegativeTest(
new String[] {
"p/X.java",
"package p;\n" +
"public class X {\n" +
" private Object foo;\n" +
"}\n",
"p/Y.java",
"package p;\n" +
"public class Y {\n" +
" public <T extends X> void test(T t) {\n" +
" System.out.println(t.foo);\n" +
" }\n" +
" Zork z;\n" +
"}\n"
},
"----------\n" +
"1. WARNING in p\\X.java (at line 3)\n" +
" private Object foo;\n" +
" ^^^\n" +
"The value of the field X.foo is not used\n" +
"----------\n" +
"----------\n" +
"1. ERROR in p\\Y.java (at line 4)\n" +
" System.out.println(t.foo);\n" +
" ^^^\n" +
"The field X.foo is not visible\n" +
"----------\n" +
"2. ERROR in p\\Y.java (at line 6)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622 (member of type variable shouldn't contain private members of class constituting intersection type)
public void test334622c() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" private Object foo;\n" +
" public <T extends X> void test(T t) {\n" +
" System.out.println(t.foo);\n" +
" Zork z;\n" +
" }\n" +
"}\n"
},
this.complianceLevel <= ClassFileConstants.JDK1_6 ?
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n" :
// 1.7+ output.
"----------\n" +
"1. WARNING in X.java (at line 2)\n" +
" private Object foo;\n" +
" ^^^\n" +
"The value of the field X.foo is not used\n" +
"----------\n" +
"2. ERROR in X.java (at line 4)\n" +
" System.out.println(t.foo);\n" +
" ^^^\n" +
"The field X.foo is not visible\n" +
"----------\n" +
"3. ERROR in X.java (at line 5)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n");
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=334622 (member of type variable shouldn't contain private members of class constituting intersection type)
public void test334622d() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" private Object foo() { return null; }\n" +
" public <T extends X> void test(T t) {\n" +
" t.foo();\n" +
" Zork z;\n" +
" }\n" +
"}\n"
},
this.complianceLevel <= ClassFileConstants.JDK1_6 ?
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n" :
// 1.7+ output.
"----------\n" +
"1. ERROR in X.java (at line 4)\n" +
" t.foo();\n" +
" ^^^\n" +
"The method foo() from the type X is not visible\n" +
"----------\n" +
"2. ERROR in X.java (at line 5)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=335751 ([1.7][compiler] Cycle inheritance in type arguments is not detected)
public void test335751() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<A extends B, B extends A> {}\n"
},
this.complianceLevel <= ClassFileConstants.JDK1_6 ?
"----------\n" +
"1. ERROR in X.java (at line 1)\n" +
" public class X<A extends B, B extends A> {}\n" +
" ^\n" +
"Illegal forward reference to type parameter B\n" +
"----------\n" :
// 1.7+ output.
"----------\n" +
"1. ERROR in X.java (at line 1)\n" +
" public class X<A extends B, B extends A> {}\n" +
" ^\n" +
"Cycle detected: a cycle exists in the type hierarchy between B and A\n" +
"----------\n");
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=334121 ([1.7][compiler] Stackoverflow error if compiled in 1.7 compliance mode)
public void test334121() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<A extends A> {}\n"
},
this.complianceLevel <= ClassFileConstants.JDK1_6 ?
"----------\n" +
"1. ERROR in X.java (at line 1)\n" +
" public class X<A extends A> {}\n" +
" ^\n" +
"Illegal forward reference to type parameter A\n" +
"----------\n" :
// 1.7+ output.
"----------\n" +
"1. ERROR in X.java (at line 1)\n" +
" public class X<A extends A> {}\n" +
" ^\n" +
"Cycle detected: the type A cannot extend/implement itself or one of its own member types\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=337751
public void test337751() {
Map compilerOptions14 = getCompilerOptions();
compilerOptions14.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2);
compilerOptions14.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
compilerOptions14.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
this.runConformTest(
new String[] {
"Project.java",
"import java.util.Map;\n" +
"public class Project {\n" +
" public Map getOptions(boolean b) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"",
null,
true,
null,
compilerOptions14,
null);
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"Y.java",
"import java.util.Map;\n" +
"public class Y {\n" +
" void foo(Project project) {\n" +
" Map<String, String> options=\n" +
" project != null ? project.getOptions(true) : null;\n" +
" options = project.getOptions(true);\n" +
" options = project == null ? null : project.getOptions(true);\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in Y.java (at line 5)\n" +
" project != null ? project.getOptions(true) : null;\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,String>\n" +
"----------\n" +
"2. WARNING in Y.java (at line 6)\n" +
" options = project.getOptions(true);\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,String>\n" +
"----------\n" +
"3. WARNING in Y.java (at line 7)\n" +
" options = project == null ? null : project.getOptions(true);\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,String>\n" +
"----------\n",
null,
false,
compilerOptions15,
null);
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=337751
public void test337751a() {
Map compilerOptions14 = getCompilerOptions();
compilerOptions14.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2);
compilerOptions14.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
compilerOptions14.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
this.runConformTest(
new String[] {
"Project.java",
"import java.util.Map;\n" +
"public class Project {\n" +
" public Map getOptions(boolean b) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"",
null,
true,
null,
compilerOptions14,
null);
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"Y.java",
"import java.util.Map;\n" +
"public class Y {\n" +
" void foo(Project project) {\n" +
" Map<String, String> options=\n" +
" project != null ? project.getOptions(true) : null;\n" +
" options = project.getOptions(true);\n" +
" options = project == null ? null : project.getOptions(true);\n" +
" }\n" +
"}\n"
},
"",
null,
false,
compilerOptions15,
null);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=337962
public void test337962() {
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.List;\n" +
"import java.util.ArrayList;\n" +
"class Super {\n" +
" protected List fList;\n" +
"}\n" +
"public class X extends Super {\n" +
" protected List fSubList; // raw type warning (good)\n" +
" {\n" +
" fSubList = new ArrayList();\n " +
" fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(null); // type safety warning (good, should not be hidden)\n" +
" }\n" +
" void foo(String s) {\n" +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" }\n" +
" X(String s) {\n" +
" fSubList = new ArrayList();\n " +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 4)\n" +
" protected List fList;\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 7)\n" +
" protected List fSubList; // raw type warning (good)\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 9)\n" +
" fSubList = new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 10)\n" +
" fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"5. WARNING in X.java (at line 11)\n" +
" super.fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"6. WARNING in X.java (at line 12)\n" +
" fSubList.add(null); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"7. WARNING in X.java (at line 15)\n" +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"8. WARNING in X.java (at line 16)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"9. WARNING in X.java (at line 17)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"10. WARNING in X.java (at line 20)\n" +
" fSubList = new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n" +
"11. WARNING in X.java (at line 21)\n" +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"12. WARNING in X.java (at line 22)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"13. WARNING in X.java (at line 23)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n",
null,
false,
compilerOptions15,
null);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=337962
public void test337962b() {
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.List;\n" +
"import java.util.ArrayList;\n" +
"class Super {\n" +
" protected List fList;\n" +
"}\n" +
"public class X extends Super {\n" +
" protected List fSubList; // raw type warning (good)\n" +
" {\n" +
" fSubList = new ArrayList();\n " +
" fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(null); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(null); // type safety warning (good, should not be hidden)\n" +
" }\n" +
" void foo(String s) {\n" +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" }\n" +
" X(String s) {\n" +
" fSubList = new ArrayList();\n " +
" fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" super.fList.add(s); // type safety warning (TODO: bad, should be hidden)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 4)\n" +
" protected List fList;\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 7)\n" +
" protected List fSubList; // raw type warning (good)\n" +
" ^^^^\n" +
"List is a raw type. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 9)\n" +
" fSubList = new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 12)\n" +
" fSubList.add(null); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"5. WARNING in X.java (at line 17)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n" +
"6. WARNING in X.java (at line 20)\n" +
" fSubList = new ArrayList();\n" +
" ^^^^^^^^^\n" +
"ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized\n" +
"----------\n" +
"7. WARNING in X.java (at line 23)\n" +
" fSubList.add(s); // type safety warning (good, should not be hidden)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized\n" +
"----------\n",
null,
false,
compilerOptions15,
null);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=338011
public void test338011() {
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.*;\n" +
"public class X extends A {\n" +
" public X(Map m) { // should warn about raw type m\n" +
" super(m);\n" +
" m.put(\"one\", 1); // warns about raw method invocation (good)\n" +
" }\n" +
" public X(Map<String, Integer> m, boolean b) {\n" +
" super(m); // shows that parametrizing the parameter type is no problem \n" +
" new A(m);\n" +
" m.put(\"one\", 1);\n" +
" }\n" +
"}\n" +
"class A {\n" +
" public A (Map m) {\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" public X(Map m) { // should warn about raw type m\n" +
" ^^^\n" +
"Map is a raw type. References to generic type Map<K,V> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" m.put(\"one\", 1); // warns about raw method invocation (good)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map<K,V> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 14)\n" +
" public A (Map m) {\n" +
" ^^^\n" +
"Map is a raw type. References to generic type Map<K,V> should be parameterized\n" +
"----------\n",
null,
false,
compilerOptions15,
null);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=338011
public void test338011b() {
Map compilerOptions15 = getCompilerOptions();
compilerOptions15.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
compilerOptions15.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
compilerOptions15.put(CompilerOptions.OPTION_ReportUnavoidableGenericTypeProblems, CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.*;\n" +
"public class X extends A {\n" +
" public X(Map m) { // should warn about raw type m\n" +
" super(m);\n" +
" m.put(\"one\", 1); // warns about raw method invocation (good)\n" +
" }\n" +
" public X(Map<String, Integer> m, boolean b) {\n" +
" super(m); // shows that parametrizing the parameter type is no problem \n" +
" new A(m);\n" +
" m.put(\"one\", 1);\n" +
" }\n" +
"}\n" +
"class A {\n" +
" public A (Map m) {\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" public X(Map m) { // should warn about raw type m\n" +
" ^^^\n" +
"Map is a raw type. References to generic type Map<K,V> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" m.put(\"one\", 1); // warns about raw method invocation (good)\n" +
" ^^^^^^^^^^^^^^^\n" +
"Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map<K,V> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 14)\n" +
" public A (Map m) {\n" +
" ^^^\n" +
"Map is a raw type. References to generic type Map<K,V> should be parameterized\n" +
"----------\n",
null,
false,
compilerOptions15,
null);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=339478
// To verify that diamond construct is not allowed in source level 1.6 or below
public void test339478a() {
if (this.complianceLevel >= ClassFileConstants.JDK1_7)
return;
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X<String> x = new X<>();\n" +
" x.testFunction(\"SUCCESS\");\n" +
" }\n" +
" public void testFunction(T param){\n" +
" System.out.println(param);\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X<String> x = new X<>();\n" +
" ^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=339478
// To verify that diamond construct is not allowed in source level 1.6 or below
public void test339478b() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X<> x1 = null;\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X<> x1 = null;\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478c() {
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.Map;\n" +
"public class X implements Map<> {\n" +
" static Map<> foo (Map<> x) { \n" +
" return null;\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" public class X implements Map<> {\n" +
" ^^^\n" +
"Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments <>\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" static Map<> foo (Map<> x) { \n" +
" ^^^\n" +
"Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments <>\n" +
"----------\n" +
"3. ERROR in X.java (at line 3)\n" +
" static Map<> foo (Map<> x) { \n" +
" ^^^\n" +
"Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478d() {
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.Map;\n" +
"public class X {\n" +
" static Map<> foo () { \n" +
" return null;\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" static Map<> foo () { \n" +
" ^^^\n" +
"Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478e() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" class Y<K> {\n" +
" }\n" +
" public static void main(String [] args) {\n" +
" X<String>.Y<> [] y = null; \n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" X<String>.Y<> [] y = null; \n" +
" ^^^^^^^^^^^\n" +
"Incorrect number of arguments for type X<String>.Y; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478f() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" class Y<K> {\n" +
" }\n" +
" public static void main(String [] args) {\n" +
" X<String>.Y<> y = null; \n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" X<String>.Y<> y = null; \n" +
" ^^^^^^^^^^^\n" +
"Incorrect number of arguments for type X<String>.Y; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478g() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public void foo(Object x) {\n" +
" if (x instanceof X<>) { \n" +
" }\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" if (x instanceof X<>) { \n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478h() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public void foo(Object x) throws X.Y<>.LException {\n" +
" }\n" +
" static class Y<T> {\n" +
" static class LException extends Throwable {}\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" public void foo(Object x) throws X.Y<>.LException {\n" +
" ^^^\n" +
"Incorrect number of arguments for type X.Y; it cannot be parameterized with arguments <>\n" +
"----------\n" +
"2. WARNING in X.java (at line 5)\n" +
" static class LException extends Throwable {}\n" +
" ^^^^^^^^^^\n" +
"The serializable class LException does not declare a static final serialVersionUID field of type long\n" +
"----------\n");
}
public void test339478i() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public void foo () {\n" +
" Object o = new X<> [10];\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" Object o = new X<> [10];\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478j() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X<>[] x1 = null;\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X<>[] x1 = null;\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478k() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" X<>[] x1 = null;\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" X<>[] x1 = null;\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478l() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X<> x1 = null;\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X<> x1 = null;\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478m() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" X<> f1 = null;\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" X<> f1 = null;\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478n() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public void foo(X<> args) {\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" public void foo(X<> args) {\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
public void test339478o() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" new X<>(){\n" +
" void newMethod(){\n" +
" }\n" +
" }.testFunction(\"SUCCESS\");\n" +
" }\n" +
" public void testFunction(T param){\n" +
" System.out.println(param);\n" +
" }\n" +
"}",
},
this.complianceLevel < ClassFileConstants.JDK1_7 ?
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" new X<>(){\n" +
" ^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" new X<>(){\n" +
" ^\n" +
"\'<>\' cannot be used with anonymous classes\n" +
"----------\n":
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" new X<>(){\n" +
" ^\n" +
"\'<>\' cannot be used with anonymous classes\n" +
"----------\n");
}
public void test339478p() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X Test = new X<>(){\n" +
" void newMethod(){\n" +
" }\n" +
" }.testFunction(\"SUCCESS\");\n" +
" }\n" +
" public void testFunction(T param){\n" +
" System.out.println(param);\n" +
" }\n" +
"}",
},
this.complianceLevel < ClassFileConstants.JDK1_7 ?
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" X Test = new X<>(){\n" +
" ^\n" +
"X is a raw type. References to generic type X<T> should be parameterized\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" X Test = new X<>(){\n" +
" ^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n" +
"3. ERROR in X.java (at line 3)\n" +
" X Test = new X<>(){\n" +
" ^\n" +
"\'<>\' cannot be used with anonymous classes\n" +
"----------\n" :
"----------\n" +
"1. WARNING in X.java (at line 3)\n" +
" X Test = new X<>(){\n" +
" ^\n" +
"X is a raw type. References to generic type X<T> should be parameterized\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" X Test = new X<>(){\n" +
" ^\n" +
"\'<>\' cannot be used with anonymous classes\n" +
"----------\n");
}
public void test339478q() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" public static void main(String[] args) {\n" +
" X Test = new X<>();\n" +
" }\n" +
"}",
},
this.complianceLevel < ClassFileConstants.JDK1_7 ?
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X Test = new X<>();\n" +
" ^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" X Test = new X<>();\n" +
" ^\n" +
"The type X is not generic; it cannot be parameterized with arguments <>\n" +
"----------\n":
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X Test = new X<>();\n" +
" ^\n" +
"The type X is not generic; it cannot be parameterized with arguments <>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334493
public void test334493() {
this.runNegativeTest(
new String[] {
"X.java",
"interface Super<P> {}\n" +
"class Y<C> implements Super<Integer>{}\n" +
"interface II extends Super<Double>{}\n" +
"class S<A> extends Y<Byte> {}\n" +
"interface T<B> extends II{}\n" +
"public class X {\n" +
" public static void main(String argv[]) {\n" +
" S<Integer> s = null;\n" +
" T<Integer> t = null;\n" +
" t = (T) s; //casting to raw type, no error\n" +
" System.out.println(t);\n" +
" }\n" +
"}\n"
},
this.complianceLevel < ClassFileConstants.JDK1_7 ?
"----------\n" +
"1. ERROR in X.java (at line 10)\n" +
" t = (T) s; //casting to raw type, no error\n" +
" ^^^^^\n" +
"Cannot cast from S<Integer> to T\n" +
"----------\n" +
"2. WARNING in X.java (at line 10)\n" +
" t = (T) s; //casting to raw type, no error\n" +
" ^^^^^\n" +
"Type safety: The expression of type T needs unchecked conversion to conform to T<Integer>\n" +
"----------\n" :
"----------\n" +
"1. WARNING in X.java (at line 10)\n" +
" t = (T) s; //casting to raw type, no error\n" +
" ^^^^^\n" +
"Type safety: The expression of type T needs unchecked conversion to conform to T<Integer>\n" +
"----------\n" +
"2. WARNING in X.java (at line 10)\n" +
" t = (T) s; //casting to raw type, no error\n" +
" ^\n" +
"T is a raw type. References to generic type T<B> should be parameterized\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334313
public void test334313() {
this.runNegativeTest(
new String[] {
"X.java",
"abstract class C<T> {\n" +
" public abstract Object foo(T x);\n" +
" public Integer foo(String x){ return 1; }\n" +
"}\n" +
"public class X extends C<String> {\n" +
" zork z;\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 6)\n" +
" zork z;\n" +
" ^^^^\n" +
"zork cannot be resolved to a type\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334313
public void test334313b() {
this.runNegativeTest(
new String[] {
"X.java",
"abstract class C<T> {\n" +
" public abstract Integer foo(T x);\n" +
" public Object foo(String x){ return 1; }\n" +
"}\n" +
"public class X extends C<String> {\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" public class X extends C<String> {\n" +
" ^\n" +
"The type X must implement the inherited abstract method C<String>.foo(String) to override C<String>.foo(String)\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334313
public void test334313c() {
this.runNegativeTest(
new String[] {
"X.java",
"abstract class B<T> {\n" +
" public abstract Object foo(T x);\n" +
"}\n" +
"abstract class C<T> extends B<T> {\n" +
" public Integer foo(String x){ return 1; }\n" +
"}\n" +
"public class X extends C<String> {\n" +
" zork z;\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 8)\n" +
" zork z;\n" +
" ^^^^\n" +
"zork cannot be resolved to a type\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334313
public void test334313d() {
this.runNegativeTest(
new String[] {
"X.java",
"abstract class B<T> {\n" +
" public abstract Integer foo(T x);\n" +
"}\n" +
"abstract class C<T> extends B<T> {\n" +
" public Object foo(String x){ return 1; }\n" +
"}\n" +
"public class X extends C<String> {\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 7)\n" +
" public class X extends C<String> {\n" +
" ^\n" +
"The type X must implement the inherited abstract method B<String>.foo(String) to override C<String>.foo(String)\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=334313
public void test334313e() {
this.runNegativeTest(
new String[] {
"X.java",
"abstract class C<T> {\n" +
" public abstract Object foo(T x);\n" +
" public static Integer foo(String x){ return 1; }\n" +
"}\n" +
"public class X extends C<String> {\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 5)\n" +
" public class X extends C<String> {\n" +
" ^\n" +
"The static method foo(String) conflicts with the abstract method in C<String>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347145
public void test347145() {
this.runNegativeTest(
new String[] {
"X.java",
"class A {}\n" +
"class B<V> extends A {} \n" +
"class F<T extends A, Y extends B<T>> {\n" +
" static <U extends A , V extends B<U>> F<U,V> g() {\n" +
" return null;\n" +
" }\n" +
"}\n" +
"public class X {\n" +
" F<? extends B, ? extends B<? extends B>> f011 = F.g();\n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 9)\n" +
" F<? extends B, ? extends B<? extends B>> f011 = F.g();\n" +
" ^\n" +
"B is a raw type. References to generic type B<V> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 9)\n" +
" F<? extends B, ? extends B<? extends B>> f011 = F.g();\n" +
" ^\n" +
"B is a raw type. References to generic type B<V> should be parameterized\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347426
public void test347426() {
this.runConformTest(
new String[] {
"X.java",
"public class X {\n" +
" class A<T extends B<?>> { }\n" +
" class B<T extends A<?>> {\n" +
" D<? extends B<T>> x;\n" +
" }\n" +
" class D<T extends B<?>> {}\n" +
" <E extends B<?>> X(E x, D<B<A<?>>> d) {\n" +
" if (x.x == d) {\n" +
" return;\n" +
" }\n" +
" }\n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347426
public void test347426b() {
this.runConformTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" class A<T extends X<?>> {\n" +
" B<? extends A<T>> x;\n" +
" }\n" +
" class B<T extends A<?>> {}\n" +
" boolean b = ((A<?>)null).x == ((B<A<X<?>>>)null); \n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347426
public void test347426c() {
this.runConformTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" class A<T extends X<? extends String>> {\n" +
" B<? extends A<T>> x;\n" +
" }\n" +
" class B<T extends A<?>> {}\n" +
" boolean b = ((A<? extends X<?>>)null).x == ((B<A<X<? extends String>>>)null); \n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=283353
public void _test283353() {
this.runConformTest(
new String[] {
"X.java",
"public class X {\n" +
" public static void main(String[] args) {\n" +
" EntityKey entityKey = null;\n" +
" new EntityCondenser().condense(entityKey); \n" +
" }\n" +
" public static class EntityCondenser {\n" +
" <I, E extends EntityType<I, E, K>, K extends EntityKey<I>> void condense(K entityKey) {\n" +
" }\n" +
" }\n" +
" public class EntityKey<I> {}\n" +
" public interface EntityType<\n" +
" I,\n" +
" E extends EntityType<I, E, K>,\n" +
" K extends EntityKey<I>> {\n" +
" }\n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347600
public void test347600() {
this.runNegativeTest(
new String[] {
"X.java",
"class A {}\n" +
"class B<V> extends A {} \n" +
"class D extends B<E> {}\n" +
"class E extends B<D> {}\n" +
"public class X<T, Y extends B<U>, U extends B<Y>> { \n" +
" public static <T1, Y1 extends B<U1>, U1 extends B<Y1>> X<T1, Y1, U1> getX() {\n" +
" return null;\n" +
" }\n" +
" X<B, ? extends D, ? extends E> f = getX(); \n" +
"}\n"
},
"----------\n" +
"1. WARNING in X.java (at line 9)\n" +
" X<B, ? extends D, ? extends E> f = getX(); \n" +
" ^\n" +
"B is a raw type. References to generic type B<V> should be parameterized\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=347746
public void test347746() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" class A<T extends B<?>> {}\n" +
" class B<T extends A<?>> extends D {}\n" +
" class C<T extends D> {}\n" +
" class D {}\n" +
" class E<T extends C<? extends B<?>>> {}\n" +
" <U extends C<V>, V extends B<W>, W extends A<V>> W foo(E<U> e) {\n" +
" return goo(e);\n" +
" }\n" +
" <P extends C<Q>, Q extends B<R>, R extends A<Q>> R goo(E<P> e) {\n" +
" return null;\n" +
" }\n" +
"}\n"
},
"");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=348493
// To verify that diamond construct is not allowed in source level 1.6 or below
public void test348493() {
if (this.complianceLevel >= ClassFileConstants.JDK1_7)
return;
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" class X2<Z> {}\n" +
" public static void main(String[] args) {\n" +
" X<String>.X2<> x = new X<String>().new X2<>();\n" +
" }\n" +
" public void testFunction(T param){\n" +
" System.out.println(param);\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 4)\n" +
" X<String>.X2<> x = new X<String>().new X2<>();\n" +
" ^^^^^^^^^^^^\n" +
"Incorrect number of arguments for type X<String>.X2; it cannot be parameterized with arguments <>\n" +
"----------\n" +
"2. ERROR in X.java (at line 4)\n" +
" X<String>.X2<> x = new X<String>().new X2<>();\n" +
" ^^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=348493
// To verify that diamond construct is not allowed in source level 1.6 or below
public void test348493a() {
if (this.complianceLevel >= ClassFileConstants.JDK1_7)
return;
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n" +
" public static void main(String[] args) {\n" +
" X<> x = new X<>();\n" +
" }\n" +
" public void testFunction(T param){\n" +
" System.out.println(param);\n" +
" }\n" +
"}",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" X<> x = new X<>();\n" +
" ^\n" +
"Incorrect number of arguments for type X<T>; it cannot be parameterized with arguments <>\n" +
"----------\n" +
"2. ERROR in X.java (at line 3)\n" +
" X<> x = new X<>();\n" +
" ^\n" +
"\'<>\' operator is not allowed for source level below 1.7\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131
public void test366131() {
this.runConformTest(
new String[] {
"X.java",
"public class X {\n" +
" public static void main(String [] args) {\n" +
" System.out.println(\"SUCCESS\");\n" +
" }\n" +
"}\n" +
"class Range<T extends Comparable<? super T>> {\n" +
" public boolean containsNC(T value) {\n" +
" return false;\n" +
" }\n" +
"}\n" +
"class NumberRange<T extends Number & Comparable<? super T>> extends Range<T> {\n" +
" public boolean contains(Comparable<?> value) {\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" }\n" +
" public <N extends Number & Comparable<? super N>> NumberRange<N>\n" +
"castTo(Class<N> type) {\n" +
" return null;\n" +
" }\n" +
"}\n",
},
"SUCCESS");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=366131
public void test366131b() {
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" public static void main(String [] args) {\n" +
" Zork z;\n" +
" }\n" +
"}\n" +
"class Range<T extends Comparable<? super T>> {\n" +
" public boolean containsNC(T value) {\n" +
" return false;\n" +
" }\n" +
"}\n" +
"class NumberRange<T extends Number & Comparable<? super T>> extends Range<T> {\n" +
" public boolean contains(Comparable<?> value) {\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" }\n" +
" public <N extends Number & Comparable<? super N>> NumberRange<N>\n" +
"castTo(Class<N> type) {\n" +
" return null;\n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 3)\n" +
" Zork z;\n" +
" ^^^^\n" +
"Zork cannot be resolved to a type\n" +
"----------\n" +
"2. WARNING in X.java (at line 13)\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" ^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: Unchecked invocation castTo(Class) of the generic method castTo(Class<N>) of type NumberRange<T>\n" +
"----------\n" +
"3. WARNING in X.java (at line 13)\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type safety: The method containsNC(Comparable) belongs to the raw type Range. References to generic type Range<T> should be parameterized\n" +
"----------\n" +
"4. WARNING in X.java (at line 13)\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" ^^^^^^^^^^^^\n" +
(this.complianceLevel < ClassFileConstants.JDK1_8 ?
"Type safety: The expression of type Class needs unchecked conversion to conform to Class<Number&Comparable<? super Number&Comparable<? super N>>>\n"
:
"Type safety: The expression of type Class needs unchecked conversion to conform to Class<Comparable<? super Comparable<? super N>&Number>&Number>\n"
) +
"----------\n" +
"5. WARNING in X.java (at line 13)\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" ^^^^^\n" +
"Class is a raw type. References to generic type Class<T> should be parameterized\n" +
"----------\n" +
"6. WARNING in X.java (at line 13)\n" +
" return castTo((Class) null).containsNC((Comparable) null);\n" +
" ^^^^^^^^^^\n" +
"Comparable is a raw type. References to generic type Comparable<T> should be parameterized\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=375394
// FAIL ERRMSG
public void _test375394() {
this.runNegativeTest(
new String[] {
"X.java",
"import java.util.Collection;\n" +
"public class X {\n" +
" static <C1,C2 extends Collection<Object>> boolean foo(C1 c, C2 c2) {\n" +
" return foo(c2,c); \n" +
" }\n" +
"}\n",
},
"----------\n" +
"1. ERROR in X.java (at line 4)\n" +
" return foo(c2,c); \n" +
" ^^^\n" +
"Bound mismatch: The generic method foo(C1, C2) of type X is not applicable for the arguments (C2, C1). The inferred type C1 is not a valid substitute for the bounded parameter <C2 extends Collection<Object>>\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=375394
public void test375394a() {
if (this.complianceLevel < ClassFileConstants.JDK1_7)
return;
this.runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" B<C, ? extends C<C>, ? extends C<C>> b = new B<>();\n" +
"}\n" +
"class B <T, U extends C<T>, V extends U>{}\n" +
"class C<T> {}\n",
},
"----------\n" +
"1. WARNING in X.java (at line 2)\n" +
" B<C, ? extends C<C>, ? extends C<C>> b = new B<>();\n" +
" ^\n" +
"C is a raw type. References to generic type C<T> should be parameterized\n" +
"----------\n" +
"2. WARNING in X.java (at line 2)\n" +
" B<C, ? extends C<C>, ? extends C<C>> b = new B<>();\n" +
" ^\n" +
"C is a raw type. References to generic type C<T> should be parameterized\n" +
"----------\n" +
"3. WARNING in X.java (at line 2)\n" +
" B<C, ? extends C<C>, ? extends C<C>> b = new B<>();\n" +
" ^\n" +
"C is a raw type. References to generic type C<T> should be parameterized\n" +
"----------\n");
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=385780
public void test385780() {
Map customOptions = getCompilerOptions();
customOptions.put(
CompilerOptions.OPTION_ReportUnusedTypeParameter,
CompilerOptions.ERROR);
this.runNegativeTest(
new String[] {
"X.java",
"public class X<T> {\n"+
"public <S> X() {\n"+
"}\n"+
"public void ph(int t) {\n"+
"}\n"+
"}\n"+
"interface doNothingInterface<T> {\n"+
"}\n"+
"class doNothing {\n"+
"public <T> void doNothingMethod() {"+
"}\n"+
"}\n"+
"class noerror {\n"+
"public <T> void doNothing(T t) {"+
"}"+
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 1)\n" +
" public class X<T> {\n" +
" ^\n" +
"Unused type parameter T\n" +
"----------\n" +
"2. ERROR in X.java (at line 2)\n" +
" public <S> X() {\n" +
" ^\n" +
"Unused type parameter S\n" +
"----------\n" +
"3. ERROR in X.java (at line 7)\n" +
" interface doNothingInterface<T> {\n" +
" ^\n" +
"Unused type parameter T\n" +
"----------\n" +
"4. ERROR in X.java (at line 10)\n" +
" public <T> void doNothingMethod() {}\n" +
" ^\n" +
"Unused type parameter T\n" +
"----------\n",
null, true, customOptions);
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// version with intermediate assignment, always worked
public void testBug395002_1() {
runConformTest(new String[] {
"Client.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"public class Client {\n" +
" <A extends SelfBound<?,A>> void foo3(A arg3) {\n" +
" SelfBound<?, A> var3 = arg3;\n" +
" SelfBound<? extends SelfBound<?, A>, ?> var4 = var3;\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// version with direct assignment to local
public void testBug395002_2() {
runConformTest(new String[] {
"Client.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"public class Client {\n" +
" <A extends SelfBound<?,A>> void foo2(A arg2) {\n" +
" SelfBound<? extends SelfBound<?, A>, ?> var2 = arg2;\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// version with direct assignment to field
public void testBug395002_3() {
runConformTest(new String[] {
"Client.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"public class Client<A extends SelfBound<?,A>> {\n" +
" SelfBound<? extends SelfBound<?, A>, ?> field2;\n" +
" void foo2(A arg2) {\n" +
" field2 = arg2;\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// version with argument passing
public void testBug395002_4() {
runConformTest(new String[] {
"Client.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"public class Client<A extends SelfBound<?,A>> {\n" +
" void bar(SelfBound<? extends SelfBound<?, A>, ?> argBar) {};\n" +
" void foo2(A arg2) {\n" +
" bar(arg2);\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// original problem with invocation of generic type
public void testBug395002_full() {
runConformTest(new String[] {
"Bug.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"class Test<X extends SelfBound<? extends Y, ?>, Y> {\n" +
"}\n" +
"public class Bug<A extends SelfBound<?, A>> {\n" +
" public Bug() {\n" +
" new Test<A, SelfBound<?, A>>();\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation.
// combined version with direct assignment to local + original problem w/ invocation of generic type
public void testBug395002_combined() {
runConformTest(new String[] {
"Client.java",
"interface SelfBound<S extends SelfBound<S, T>, T> {\n" +
"}\n" +
"class Test<X extends SelfBound<? extends Y, ?>, Y> {\n" +
"}\n" +
"public class Client {\n" +
" <A extends SelfBound<?,A>> void foo2(A arg2) {\n" +
" Object o = new Test<A, SelfBound<?, A>>();\n" +
" SelfBound<? extends SelfBound<?, A>, ?> var2 = arg2;\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=397888
public void test397888a() {
Map customOptions = getCompilerOptions();
customOptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
customOptions.put(CompilerOptions.OPTION_ReportUnusedTypeParameter, CompilerOptions.ERROR);
customOptions.put(CompilerOptions.OPTION_ReportUnusedParameter, CompilerOptions.ERROR);
customOptions.put(CompilerOptions.OPTION_ReportUnusedParameterIncludeDocCommentReference,
CompilerOptions.ENABLED);
this.runNegativeTest(
new String[] {
"X.java",
"/***\n" +
" * @param <T>\n" +
" */\n" +
"public class X <T> {\n"+
"/***\n" +
" * @param <S>\n" +
" */\n" +
" public <S> void ph(int i) {\n"+
" }\n"+
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 8)\n" +
" public <S> void ph(int i) {\n" +
" ^\n" +
"The value of the parameter i is not used\n" +
"----------\n",
null, true, customOptions);
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=397888
public void test397888b() {
Map customOptions = getCompilerOptions();
customOptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
customOptions.put(CompilerOptions.OPTION_ReportUnusedTypeParameter, CompilerOptions.ERROR);
customOptions.put(CompilerOptions.OPTION_ReportUnusedParameterIncludeDocCommentReference,
CompilerOptions.DISABLED);
this.runNegativeTest(
new String[] {
"X.java",
"/***\n" +
" * @param <T>\n" +
" */\n" +
"public class X <T> {\n"+
"/***\n" +
" * @param <S>\n" +
" */\n" +
"public <S> void ph() {\n"+
"}\n"+
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 4)\n" +
" public class X <T> {\n" +
" ^\n" +
"Unused type parameter T\n" +
"----------\n" +
"2. ERROR in X.java (at line 8)\n" +
" public <S> void ph() {\n" +
" ^\n" +
"Unused type parameter S\n" +
"----------\n",
null, true, customOptions);
}
// Bug 401456 - Code compiles from javac/intellij, but fails from eclipse
public void test401456() {
runConformTest(
new String[] {
"App.java",
"import java.util.List;\n" +
"\n" +
"public class App {\n" +
"\n" +
" public interface Command_1<T> {\n" +
" public void execute(T o);\n" +
" }\n" +
" public static class ObservableEventWithArg<T> {\n" +
" public class Monitor {\n" +
" public Object addListener(final Command_1<T> l) {\n" +
" return null;\n" +
" }\n" +
" }\n" +
" }\n" +
" public static class Context<T> {\n" +
" public ObservableEventWithArg<String>.Monitor getSubmissionErrorEventMonitor() {\n" +
" return new ObservableEventWithArg<String>().new Monitor();\n" +
" }\n" +
" }\n" +
"\n" +
" public static void main(String[] args) {\n" +
" compileError(new Context<List<String>>());\n" +
" }\n" +
"\n" +
" private static void compileError(Context context) {\n" +
" context.getSubmissionErrorEventMonitor().addListener(\n" + // here the inner message send bogusly resolved to ObservableEventWithArg#RAW.Monitor
" new Command_1<String>() {\n" +
" public void execute(String o) {\n" +
" }\n" +
" });\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/405706 - Eclipse compiler fails to give compiler error when return type is a inferred generic
// original test
public void testBug405706a() {
runNegativeTest(
new String[] {
"TypeUnsafe.java",
"import java.util.Collection;\n" +
"\n" +
"public class TypeUnsafe {\n" +
" public static <Type,\n" +
" CollectionType extends Collection<Type>>\n" +
" CollectionType\n" +
" nullAsCollection(Class<Type> clazz) {\n" +
" return null;\n" +
" }\n" +
"\n" +
" public static void main(String[] args) {\n" +
" Collection<Integer> integers = nullAsCollection(String.class);\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in TypeUnsafe.java (at line 12)\n" +
" Collection<Integer> integers = nullAsCollection(String.class);\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type mismatch: cannot convert from Collection<String> to Collection<Integer>\n" +
"----------\n");
}
// https://bugs.eclipse.org/405706 - Eclipse compiler fails to give compiler error when return type is a inferred generic
// include compatibility List <: Collection
public void testBug405706b() {
runNegativeTest(
new String[] {
"TypeUnsafe.java",
"import java.util.Collection;\n" +
"import java.util.List;\n" +
"\n" +
"public class TypeUnsafe {\n" +
" public static <Type,\n" +
" CollectionType extends List<Type>>\n" +
" CollectionType\n" +
" nullAsList(Class<Type> clazz) {\n" +
" return null;\n" +
" }\n" +
"\n" +
" public static void main(String[] args) {\n" +
" Collection<Integer> integers = nullAsList(String.class);\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in TypeUnsafe.java (at line 13)\n" +
" Collection<Integer> integers = nullAsList(String.class);\n" +
" ^^^^^^^^^^^^^^^^^^^^^^^^\n" +
"Type mismatch: cannot convert from List<String> to Collection<Integer>\n" +
"----------\n");
}
// https://bugs.eclipse.org/408441 - Type mismatch using Arrays.asList with 3 or more implementations of an interface with the interface type as the last parameter
public void testBug408441() {
runConformTest(
new String[] {
"TypeMistmatchIssue.java",
"import java.util.Arrays;\n" +
"import java.util.List;\n" +
"\n" +
"\n" +
"public class TypeMistmatchIssue {\n" +
" static interface A {\n" +
" }\n" +
" static class B implements A {\n" +
" }\n" +
" static class C implements A {\n" +
" }\n" +
" static class D implements A {\n" +
" }\n" +
" \n" +
" void illustrate() {\n" +
" List<Class<? extends A>> no1= Arrays.asList(B.class, A.class); // compiles\n" +
" List<Class<? extends A>> no2= Arrays.asList(C.class, B.class, A.class); // compiles\n" +
" List<Class<? extends A>> no3= Arrays.asList(D.class, B.class, A.class); // compiles\n" +
" \n" +
" List<Class<? extends A>> no4= Arrays.asList(D.class, C.class, B.class, A.class); // cannot convert error !!!\n" +
"\n" +
" List<Class<? extends A>> no5= Arrays.asList(A.class, B.class, C.class, D.class); // compiles\n" +
" List<Class<? extends A>> no6= Arrays.asList(A.class, D.class, C.class, B.class); // compiles\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/413958 - Function override returning inherited Generic Type
public void testBug413958_1() {
runConformTest(
new String[] {
"TestA.java",
"public class TestA { }\n",
"TestB.java",
"public class TestB { }\n",
"ReadOnlyWrapper.java",
"@SuppressWarnings(\"unchecked\")\n" +
"public class ReadOnlyWrapper<A extends TestA, B extends TestB> {\n" +
" protected A a;\n" +
" protected B b;\n" +
" public ReadOnlyWrapper(A ax,B bx){\n" +
" this.a = ax;\n" +
" this.b = bx;\n" +
" }\n" +
" public <X extends ReadOnlyWrapper<A,B>> X copy() {\n" +
" return (X) new ReadOnlyWrapper<A,B>(a,b);\n" +
" }\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy() {\n" +
" return (X) new ReadOnlyWrapper<A,B>(a,b);\n" +
" }\n" +
" public A getA() {\n" +
" return this.a;\n" +
" }\n" +
" public B getB() {\n" +
" return this.b;\n" +
" }\n" +
"}",
"WritableWrapper.java",
"@SuppressWarnings(\"unchecked\")\n" +
"public class WritableWrapper<A extends TestA, B extends TestB> extends ReadOnlyWrapper<A, B> {\n" +
" public WritableWrapper(A ax,B bx){\n" +
" super(ax,bx);\n" +
" }\n" +
" @Override\n" +
" public <X extends ReadOnlyWrapper<A,B>> X copy() {\n" +
" return (X) new WritableWrapper<A, B>(a,b);\n" +
" }\n" +
" @Override\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy() {\n" +
" // Works in Indigo, Fails in Kepler\n" +
" return (X) new WritableWrapper<A,B>(a,b);\n" +
" }\n" +
" public void setA(A ax) {\n" +
" this.a = ax;\n" +
" }\n" +
" public void setB(B bx) {\n" +
" this.b = bx;\n" +
" }\n" +
"}\n",
"TestGenerics.java",
"public class TestGenerics {\n" +
" public static void main(String [] args) {\n" +
" final WritableWrapper<TestA, TestB> v1 = new WritableWrapper<TestA, TestB>(new TestA(), new TestB());\n" +
" final WritableWrapper<TestA,TestB> v2 = v1.copy();\n" +
" final WritableWrapper<TestA,TestB> v3 = v1.icopy();\n" +
" }\n" +
"}\n"
});
}
// https://bugs.eclipse.org/413958 - Function override returning inherited Generic Type
// variation showing different inference with / without a method parameter
public void testBug413958_2() {
runNegativeTest(
new String[] {
"TestA.java",
"public class TestA { }\n",
"TestB.java",
"public class TestB { }\n",
"TestA2.java",
"public class TestA2 extends TestA { }\n",
"ReadOnlyWrapper.java",
"@SuppressWarnings(\"unchecked\")\n" +
"public class ReadOnlyWrapper<A extends TestA, B extends TestB> {\n" +
" protected A a;\n" +
" protected B b;\n" +
" public ReadOnlyWrapper(A ax,B bx){\n" +
" this.a = ax;\n" +
" this.b = bx;\n" +
" }\n" +
" public <X extends ReadOnlyWrapper<A,B>> X copy() {\n" +
" return (X) new ReadOnlyWrapper<A,B>(a,b);\n" +
" }\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy() {\n" +
" return (X) new ReadOnlyWrapper<A,B>(a,b);\n" +
" }\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy2(TA in) {\n" +
" return (X) new ReadOnlyWrapper<A,B>(a,b);\n" +
" }\n" +
" public A getA() {\n" +
" return this.a;\n" +
" }\n" +
" public B getB() {\n" +
" return this.b;\n" +
" }\n" +
"}",
"WritableWrapper.java",
"@SuppressWarnings(\"unchecked\")\n" +
"public class WritableWrapper<A extends TestA, B extends TestB> extends ReadOnlyWrapper<A, B> {\n" +
" public WritableWrapper(A ax,B bx){\n" +
" super(ax,bx);\n" +
" }\n" +
" @Override\n" +
" public <X extends ReadOnlyWrapper<A,B>> X copy() {\n" +
" return (X) new WritableWrapper<A, B>(a,b);\n" +
" }\n" +
" @Override\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy() {\n" +
" return (X) new WritableWrapper<A,B>(a,b);\n" +
" }\n" +
" @Override\n" +
" public <TA extends TestA,TB extends TestB,X extends ReadOnlyWrapper<TA,TB>> X icopy2(TA in) {\n" +
" return (X) new WritableWrapper<A,B>(a,b);\n" +
" }\n" +
" public void setA(A ax) {\n" +
" this.a = ax;\n" +
" }\n" +
" public void setB(B bx) {\n" +
" this.b = bx;\n" +
" }\n" +
"}\n",
"TestGenerics.java",
"public class TestGenerics {\n" +
" public static void main(String [] args) {\n" +
" final WritableWrapper<TestA, TestB> v1 = new WritableWrapper<TestA, TestB>(new TestA(), new TestB());\n" +
" final WritableWrapper<TestA,TestB> v2 = v1.copy();\n" +
" final WritableWrapper<TestA,TestB> v3 = v1.icopy();\n" +
" final WritableWrapper<TestA2,TestB> v4 = v1.icopy();\n" +
" final WritableWrapper<TestA2,TestB> v5 = v1.icopy2(new TestA2());\n" +
" }\n" +
"}\n"
},
"----------\n" +
"1. ERROR in TestGenerics.java (at line 6)\n" +
" final WritableWrapper<TestA2,TestB> v4 = v1.icopy();\n" +
" ^^^^^^^^^^\n" +
"Type mismatch: cannot convert from ReadOnlyWrapper<TestA,TestB> to WritableWrapper<TestA2,TestB>\n" +
"----------\n");
}
// Disabled due to spec bug, see https://bugs.eclipse.org/423496
public void _testBug415734() {
String compileSrc =
"import java.util.ArrayList;\n" +
"import java.util.List;\n" +
"\n" +
"public class Compile {\n" +
"\n" +
" public <T, Exp extends List<T>> Exp typedNull() {\n" +
" return null;\n" +
" }\n" +
"\n" +
" public void call() {\n" +
" ArrayList<String> list = typedNull();\n" +
" }\n" +
"}\n";
if (this.complianceLevel < ClassFileConstants.JDK1_8) {
runNegativeTest(
new String[] {
"Compile.java",
compileSrc
},
"----------\n" +
"1. ERROR in Compile.java (at line 11)\n" +
" ArrayList<String> list = typedNull();\n" +
" ^^^^^^^^^^^\n" +
"Type mismatch: cannot convert from List<Object> to ArrayList<String>\n" +
"----------\n");
} else {
runConformTest(
new String[] {
"Compile.java",
compileSrc
});
}
}
} | [
"[email protected]"
] | |
fe7c5985a2a88d2ce809bb5abe5bf877aa32b0f1 | d064b7ced30dba1a8a13c6992568a14f2fa389e7 | /migo-common/src/main/java/com/migo/dao/TaskSearchDao.java | 86fb775d14552e0bcba1518743dac9b241e4de8f | [] | no_license | eagle646944325/migo-security-master | 72b8e35e6d364a33851b67c6420d4f6ecd576722 | 9c6a05e3b4a39f9c0a3926a7a560911782461bef | refs/heads/master | 2020-03-23T01:28:27.364809 | 2018-09-09T06:52:20 | 2018-09-09T06:52:20 | 140,919,268 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 246 | java | package com.migo.dao;
import com.migo.entity.TaskSearchEntity;
/**
* 任务搜索条件
*
* @author zhiqiu
* @email [email protected]
* @date 2018-07-24 11:36:01
*/
public interface TaskSearchDao extends BaseDao<TaskSearchEntity> {
}
| [
"[email protected]"
] | |
45c381cc9fdf207d01cbdc81960bf59a06b32bcb | 87eb16216e2f6d8b846f1909efc1d9463bc535fe | /AlgoritmosEmGrafos-FranzeJr/src/estruturas/OrderedVector.java | 030bf209254b343d7ab4563fd0d34471c8117148 | [] | no_license | lucasgarrido/projeto-algoritmos-em-grafos-java | b4f9cdea333919e2fc28c665fe69aed0b9b55d6c | 1f006078f21d3f083a4f029bdd012a5cf53d3732 | refs/heads/master | 2020-05-20T13:15:45.165128 | 2011-05-22T22:48:27 | 2011-05-22T22:48:27 | 32,984,733 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 938 | java | package estruturas;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class OrderedVector {
private List<Aresta> elements = new ArrayList<Aresta>();
public OrderedVector(List<Aresta> elements) {
this.elements.addAll(elements);
Collections.sort(this.elements);
}
public void addElement(Aresta element){
int index = this.elements.size();
for(int i=0;i<elements.size();i++){
Aresta eTempi = elements.get(i);
if(element.compareTo(eTempi)<=0){
index = i;
break;
}
}
elements.add(index, element);
}
public void remove(Aresta element){
int index = this.elements.indexOf(element);
if(index>=0)
this.elements.remove(index);
}
public Aresta deleteFirst(){
return this.elements.remove(0);
}
@Override
public String toString() {
String s = "";
for(Aresta a:this.elements)
s+="\n"+a.toString();
return s;
}
}
| [
"[email protected]@5da559a9-3a4f-77a5-d58b-6de179e295d9"
] | [email protected]@5da559a9-3a4f-77a5-d58b-6de179e295d9 |
6ef7de1ef93fbf724aa01b9d9ecb89c6a1f9163a | 643520557d3ad53126374535a1464ea3aef40afb | /src/main/java/com/library/mdct/dao/BookDAOImpl.java | 0fd5e02f512ab37d138c1f52223e2994ebec3dc1 | [] | no_license | luckyjyp/mdctpro | 3052cd602e0e365ce239d68f47dc48fba4bd58b5 | a7bb4afdf0f9ed5d6245bbbefa455a8e163b4941 | refs/heads/master | 2021-01-22T05:42:41.079304 | 2017-06-19T08:54:02 | 2017-06-19T08:54:02 | 92,488,299 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,595 | java | package com.library.mdct.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.library.mdct.dto.BookVO;
@Repository
public class BookDAOImpl implements LibraryDAO {
@Inject
SqlSession sqlSession;
//전체도서조회
@Override
public List<BookVO> searchList() throws Exception {
return sqlSession.selectList("lib.booklist");
}
//도서상세조회
@Override
public BookVO oneSearch(String book_no) throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("book_no",book_no);
BookVO vo = sqlSession.selectOne("lib.bookInfo", map);
//System.out.println("DAO거쳐서 가져온 정보"+vo.toString());
return vo;
}
//도서신규생성
@Override
public void insert(Map<String, String> map) throws Exception {
BookVO vo = new BookVO();
//System.out.println(obj.toString());
vo.setBook_no(map.get("book_no"));
vo.setBook_name(map.get("book_name"));
vo.setWriter(map.get("writer"));
vo.setGenre(map.get("genre"));
vo.setPrice(map.get("price"));
vo.setPub_no(map.get("pub_no"));
sqlSession.insert("lib.bookInsert", vo);
}
//도서정보변경
@Override
public void update(Map<String, String> map) throws Exception {
sqlSession.update("lib.bookUpdate", map);
}
//도서삭제
@Override
public void delete(String book_no) throws Exception {
System.out.println("dao에서"+book_no);
sqlSession.delete("lib.bookDelete",book_no);
}
//도서번호중복확인
public boolean booknochk(String book_no) throws Exception{
boolean result = false;
int count = 0;
/*Map<String, String> map = new HashMap<String, String>();
map.put("book_no", book_no);*/
count= sqlSession.selectOne("lib.booknochk",book_no);
System.out.println("dao: "+count);
if(count==0) result=true;
return result;
}
//보관도서 중복확인
public boolean storenochk(String book_no) throws Exception{
boolean result = false;
int count = 0;
count= sqlSession.selectOne("lib.storenochk",book_no);
System.out.println("dao: "+count);
if(count==0) result=true;
return result;
}
//대출자중복확인
public boolean bornochk(String bor_no) throws Exception{
boolean result = false;
int count = 0;
count= sqlSession.selectOne("lib.bornochk",bor_no);
System.out.println("dao: "+count);
if(count==0) result=true;
return result;
}
}
| [
"[email protected]"
] | |
8dcd291db4833e9fedb385a28bd5dc5fcb7c9f6c | dac26f9aaf5570c2482c32ef0a1cd82538973748 | /src/main/java/com/wantedtech/common/xpresso/types/list.java | 4c294c722ce16ca7517ef13f3de1f30751e389f4 | [
"MIT"
] | permissive | nkhuyu/xpresso | 79feaebfa48de955b878a13791284f0d92d94b8f | 39c52aa388b3f41fe8428904c70aa70636bfe5c9 | refs/heads/master | 2020-12-28T20:20:30.477057 | 2015-06-07T23:26:11 | 2015-06-07T23:26:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,504 | java | package com.wantedtech.common.xpresso.types;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import com.wantedtech.common.xpresso.Slicable;
import com.wantedtech.common.xpresso.Slicer;
import com.wantedtech.common.xpresso.x;
import com.wantedtech.common.xpresso.helpers.Helpers;
public class list<T> implements Iterable<T>,Slicable<T>,Comparable<list<T>>,Serializable{
/**
*
*/
private static final long serialVersionUID = 3923221503510025027L;
//used by the construction list.setAt(index).value(val);
private int setAtIndex = Integer.MAX_VALUE;
//used by the construction list.setAt(startIndex,endIndex).values(iterable);
private int setAtStartIndex = Integer.MAX_VALUE;
private int setAtEndIndex = Integer.MAX_VALUE;
protected ArrayList<T> list;
public list(){
this.list = new ArrayList<T>();
}
public list(Iterable<T> elements){
if (elements instanceof list<?>){
this.list = ((list<T>)elements).toArrayList();
}else{
this.list = Helpers.newArrayList(elements);
}
}
public list<T> plus(Iterable<T> iterable){
ArrayList<T> newList = new ArrayList<T>();
newList.addAll(this.list);
if(iterable instanceof ArrayList<?>){
newList.addAll((ArrayList<T>)iterable);
}else if(iterable instanceof list<?>){
newList.addAll(((list<T>)iterable).toArrayList());
}else{
newList.addAll(Helpers.newArrayList(iterable));
}
return new list<T>(newList);
}
@SuppressWarnings("unchecked")
public list<T> plus(T element0,T element1,T... elements){
return plus(Helpers.newArrayList(element0,element1,elements));
}
@SuppressWarnings("unused")
public list<T> times(int multiplier){
list<T> newList = x.list();
for(int i : x.countTo(multiplier)){
for(T element : this.list){
newList.append(element);
}
}
return newList;
}
public list<T> setAt(Slicer slicer){
if(slicer.step != 1){
throw new IllegalArgumentException("Step has to be equal to 1.");
}
return setAt(slicer.startIndex,slicer.endIndex);
}
public list<T> setAt(int startIndex,int endIndex){
if (startIndex < 0){
startIndex = this.list.size()+startIndex;
}
if (startIndex < 0){
startIndex = 0;
}
if (endIndex < 0){
endIndex = this.list.size()+endIndex;
}
if (endIndex < 0){
endIndex = 0;
}
if (startIndex > this.list.size()){
startIndex = this.list.size();
}
if (endIndex > this.list.size()){
endIndex = this.list.size();
}
this.setAtStartIndex = startIndex;
this.setAtEndIndex = endIndex;
return this;
}
public void values(Iterable<T> values){
this.list = this.sliceTo(setAtStartIndex).plus(values).plus(this.sliceFrom(this.setAtEndIndex)).toArrayList();
}
public list<T> slice(Slicer slicer){
return slice(slicer.startIndex,slicer.endIndex,slicer.step,slicer.includeEnd);
}
private list<T> slice(int startIndex,int endIndex, int step, boolean includeEnd){
if(step == 0){
step = 1;
}
if (startIndex < 0){
startIndex = this.list.size()+startIndex;
}
if (startIndex < 0){
startIndex = 0;
}
if (endIndex < 0){
endIndex = this.list.size()+endIndex;
}
if (endIndex < 0){
endIndex = 0;
if(step < 0 && startIndex >= endIndex){
includeEnd = true;
}
}
if (startIndex > this.list.size()-1){
startIndex = this.list.size()-1;
}
if (endIndex > this.list.size()-1){
endIndex = this.list.size()-1;
includeEnd = true;
}
list<T> newList = x.list();
if(step > 0){
while (startIndex < endIndex + (includeEnd?1:0)){
newList.append(this.get(startIndex));
startIndex+=step;
}
}else{
while (startIndex > endIndex - (includeEnd?1:0)){
newList.append(this.get(startIndex));
startIndex+=step;
}
}
return newList;
}
public list<T> slice(int startIndex,int endIndex, int step){
return slice(startIndex, endIndex, step, false);
}
public list<T> sliceTo(int endIndex,int step){
int startIndex = 0;
if (step < 0){
startIndex = x.len(this)-1;
return slice(startIndex,endIndex,step,true);
}
return slice(startIndex,endIndex,step);
}
public list<T> sliceFrom(int startIndex, int step){
int endIndex = x.len(this)-1;
if (step < 0){
endIndex = 0;
}
return slice(startIndex,endIndex,step,true);
}
public list<T> sliceTo(int endIndex) {
return sliceTo(endIndex, 1);
}
public list<T> sliceFrom(int startIndex) {
return sliceFrom(startIndex,1);
}
public list<T> slice(int startIndex, int endIndex) {
return slice(startIndex, endIndex, 1);
}
public list<T> slice(int step){
if (step < 0){
return slice(x.len(this)-1,0,step,true);
}else{
return slice(0,x.len(this),step,false);
}
}
public list<T> slice(){
return slice(1);
}
public T get(int index){
if (index < 0){
index = this.list.size()+index;
if (index < 0){
index = 0;
}
}
return this.list.get(index);
}
public T get(Object index){
return get(((int)index));
}
public list<T> extend(Iterable<T> iterable){
for(T element : iterable){
this.list.add(element);
}
return this;
}
private list<T> set(int index,T value){
this.list.set(index, value);
return this;
}
public list<T> setAt(int index){
if (index < 0){
index = this.list.size()+index;
if (index < 0){
index = 0;
}
}
if(this.list.size() < index - 1){
throw new IndexOutOfBoundsException();
}
setAtIndex = index;
return this;
}
public void value(T value){
set(setAtIndex,value);
}
public boolean contains(T value){
return this.list.contains(value);
}
public boolean in(Iterable<list<T>> anotherList){
return x.list(anotherList).contains(this);
}
public boolean in(@SuppressWarnings("unchecked") list<T>... lists){
return x.list(lists).contains(this);
}
public boolean notIn(Iterable<list<T>> anotherList){
return !in(anotherList);
}
public boolean notIn(@SuppressWarnings("unchecked") list<T>... lists){
return !in(lists);
}
public int count(T value){
int counter = 0;
if(this.list.contains(value)){
for(T element : this.list){
if((element).equals(value)){
counter++;
}
}
}
return counter;
}
public list<T> append(T element){
this.list.add(element);
return this;
}
public list<list<T>> ngrams(int n) {
list<list<T>> ngrams = x.list();
for (int i = 0; i < x.len(this) - n + 1; i++){
ngrams.append(this.slice(i, i+n));
}
return ngrams;
}
public <E> list<E> flattened(Class<E> classOfelements){
list<E> result = x.list();
for(T element : this){
if(element instanceof list<?>){
result.extend(((list<?>)element).<E>flattened(classOfelements));
}else if(element instanceof Iterable<?>){
result.extend((x.list((Iterable<?>)element)).<E>flattened(classOfelements));
}else{
result.append(classOfelements.cast(element));
}
}
return result;
}
public list<T> copy(){
ArrayList<T> newArrayList = Helpers.newArrayList(this.list);
return x.list(newArrayList);
}
public ArrayList<T> toArrayList(){
return Helpers.newArrayList(this);
}
@Override
public String toString(){
return "["+x.String(", ").join(list)+"]";
}
public Iterator<T> iterator(){
return this.list.iterator();
}
@Override
public int compareTo(list<T> o) {
return this.toString().compareTo(o.toString());
}
@Override
public boolean equals(Object o) {
if(o instanceof list){
return this.toString().equals(o.toString());
}
return false;
}
}
| [
"[email protected]"
] | |
d181e033be405f0127aa4ded5d70a55bcf05b2a5 | 8be538ef35f0ef0df9cf4a6ff6fae3973aa6f093 | /cdi /projet java/src3/hood/robin/FORMATION-SAV/ALGO-JAVA/Exercices/JAVA/PiecesUsine/src/Couleur.java | 0b817398826570fc87c69cddc6260085c2af702c | [] | no_license | Blackset/Cdi18 | e128ae13b887119a8db8f150c11cbaf396470584 | e636e66cba62cc01de777006f04d968705f76d2d | refs/heads/main | 2023-03-04T20:21:42.211990 | 2021-02-04T20:48:13 | 2021-02-04T20:48:13 | 336,063,563 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | enum Couleur
{
JAUNE, VERT, BLEU, ROUGE, ORANGE, MAUVE;
public static Couleur saisie()
{
String colorS;
Couleur color = null;
boolean ok = true;
do
{
System.out.print("\t-Couleur de la pièce (");
for (Couleur c : Couleur.values())
{
System.out.print(c + " ");
}
System.out.print(") : ");
colorS = Lire.S().toUpperCase();
try
{
color = Couleur.valueOf(colorS);
ok = true;
}
catch (Exception e)
{
ok = false;
}
}
while (!ok);
return color;
}
public static void afficher(Couleur couleur)
{
System.out.println("\t-COULEUR : " + couleur);
}
} | [
"[email protected]"
] | |
4ef4508f305df66c7c7176057bc570c5d9c174db | 797cfaf0df3a0abcaeb230917db73bcd1f4e660a | /src/main/java/com/rucrealex/Calculator.java | 85ef71cb5a137ef5e8d4aedfdaffd784a38be67c | [] | no_license | rucrealex/Calculator | 10e3451678c53b40e759f5052424b2630588eb6a | 9ecbd89713f60731ec0fdf9b979f929d9d30c190 | refs/heads/master | 2020-03-17T07:32:11.641725 | 2018-05-14T18:20:03 | 2018-05-14T18:20:03 | 133,402,343 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,058 | java | package com.rucrealex;
import com.rucrealex.operations.Operation;
import com.rucrealex.screen.BaseMonitor;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Calculator {
private BaseMonitor baseMonitor;
private Operation operation;
public Calculator(BaseMonitor baseMonitor, Operation operation) {
this.baseMonitor = baseMonitor;
this.operation = operation;
}
private void execute(String[] args) {
Long op1 = Long.valueOf(args[0]);
Long op2 = Long.valueOf(args[1]);
String str = "RESULT: " + args[0] +" " + this.operation.getOperationName() + " " + args[1] + " = " +
operation.execute(op1, op2);
this.baseMonitor.print(str);
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
Calculator calculator = (Calculator) context.getBean("calculator");
calculator.execute(args);
}
}
| [
"[email protected]"
] | |
ee45c91abbb0014292fb8c741448235b1deb2362 | 1cda4d522512382ee85e1c98850c2ee9700b972c | /1701040103_SE2_Tut (10)/tut10/src/to_dos/adapter/adapter/SquarePegAdapter.java | e5520a18efb66353b3f4db1f35c1594b367b97f6 | [] | no_license | HoangTienLong/SE2_Tutorial_1701040103 | f5792e34d0b062a837c2e2a62ad123d6b9fc2713 | f0b450a6ab0a4eff9b4a8250da2d6042d7580668 | refs/heads/master | 2022-09-08T02:54:12.043341 | 2020-06-01T15:19:44 | 2020-06-01T15:19:44 | 268,555,934 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 604 | java | package tuts.tut10.to_dos.adapter.adapter;
import tuts.tut10.complete.adapter.round.RoundPeg;
import tuts.tut10.complete.adapter.square.SquarePeg;
/**
* Adapter allows fitting square pegs into round holes.
*/
public class SquarePegAdapter extends RoundPeg {
private SquarePeg peg;
public SquarePegAdapter(SquarePeg peg) {
this.peg = peg;
}
@Override
public double getRadius() {
double result;
// Calculate a minimum circle radius, which can fit this peg.
result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
return result;
}
} | [
"[email protected]"
] | |
fbf0d27a7247b206d09f27ddc65a2760042b72bf | 0b47863f7e5f2fcba78d490257665ae3e820b0b2 | /src/main/java/com/diaspark/csvtomongo/model/CustomResultList.java | dc0f760feb80e6dd75d4e3cf58b44e3e84c1fa4e | [] | no_license | surendrarai2018/SpringBatch | 9bb3bd6ed242956fccd481fa4b463bc86a3a0858 | 3d9ba13a4d3355fae5fa7f3700656fb74db2bd3c | refs/heads/master | 2020-04-09T23:55:02.799276 | 2018-12-06T13:33:28 | 2018-12-06T13:33:28 | 160,670,404 | 0 | 0 | null | 2018-12-06T13:33:29 | 2018-12-06T12:16:46 | null | UTF-8 | Java | false | false | 741 | java | package com.diaspark.csvtomongo.model;
import java.io.Serializable;
import java.util.List;
public class CustomResultList implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1693046355859466074L;
private List<Domain> results;
private String nextLine;
private long count;
public List<Domain> getResults() {
return results;
}
public void setResults(List<Domain> results) {
this.results = results;
}
public String getNextLine() {
return nextLine;
}
public void setNextLine(String nextLine) {
this.nextLine = nextLine;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
}
| [
"[email protected]"
] | |
9bdd069e85cc69057b0321ba28210df72ef564f8 | 10a03cbf68b9381b2bc07b6a273aea64e7423756 | /src/main/java/com/jaba/code/leetcode/problemsolving/problems/MedianOfTwoSortedArrays.java | 87ec547de4846733ddac025c3087496a519c4e48 | [] | no_license | augustojaba/problem-solving | a32beecde85aa28a42ca6d74fe8d900ac4eaf8dc | 0903d6bdb898db0302c21623ba091c862eb13f5a | refs/heads/master | 2023-07-16T10:32:21.875250 | 2021-09-01T03:57:14 | 2021-09-01T03:57:14 | 210,165,794 | 0 | 0 | null | 2021-09-01T03:57:14 | 2019-09-22T15:01:42 | Java | UTF-8 | Java | false | false | 2,545 | java | package com.jaba.code.leetcode.problemsolving.problems;
public class MedianOfTwoSortedArrays {
public static void main(String[] args) {
MedianOfTwoSortedArrays solution = new MedianOfTwoSortedArrays();
// System.out.println(solution.solutionBruteForce(new int[] {1, 2}, new int[] {3, 4}));
System.out.println(solution.solutionBinarySearch(new int[] {}, new int[] {}));
}
public double solutionBinarySearch(int[] nums1, int[] nums2) {
int[] x, y;
if (nums1.length + nums2.length == 0) {
throw new IllegalArgumentException();
}
if (nums1.length < nums2.length) {
x = nums1;
y = nums2;
} else {
y = nums1;
x = nums2;
}
int low = 0;
int high = x.length;
while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = ((x.length + y.length + 1) / 2) - partitionX;
int maxLeftX = partitionX == 0 ? Integer.MIN_VALUE : x[partitionX - 1];
int minRightX = partitionX == x.length ? Integer.MAX_VALUE : x[partitionX];
int maxLeftY = partitionY == 0 ? Integer.MIN_VALUE : y[partitionY - 1];
int minRightY = partitionY == y.length ? Integer.MAX_VALUE : y[partitionY];
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
if ((x.length + y.length) % 2 == 0) {
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2.0;
} else {
return Math.max(maxLeftX, maxLeftY);
}
} else if (maxLeftX > minRightY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}
throw new IllegalArgumentException();
}
public double solutionBruteForce(int[] nums1, int[] nums2) {
int[] aux = new int[nums1.length + nums2.length];
if (nums1.length == 0 && nums2.length == 0) {
return 0d;
} else if (nums1.length == 0 && nums2.length != 0) {
aux = nums2;
} else if (nums1.length != 0 && nums2.length == 0) {
aux = nums1;
} else {
int p1 = 0;
int p2 = 0;
for (int i = 0; i < aux.length; i++) {
if (p2 >= nums2.length || (p1 < nums1.length && nums1[p1] <= nums2[p2])) {
aux[i] = nums1[p1];
p1++;
} else {
aux[i] = nums2[p2];
p2++;
}
}
}
for (int i = 0; i < aux.length; i++) {
System.out.println(aux[i]);
}
if (aux.length % 2 == 0) {
return (aux[(aux.length / 2) - 1] + aux[aux.length / 2]) / 2.0;
} else {
return aux[(aux.length - 1) / 2];
}
}
}
| [
"[email protected]"
] | |
f06520a575fae61939b5075850c68ca2ea049e78 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /java/neo4j/2019/8/JavaUtilHashFunction.java | 18087293877310b85432b7dae929bdddb1e61673 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Java | false | false | 1,559 | java | /*
* Copyright (c) 2002-2019 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.hashing;
/**
* @see HashFunction#javaUtilHashing()
*/
class JavaUtilHashFunction implements HashFunction
{
static final HashFunction INSTANCE = new JavaUtilHashFunction();
private JavaUtilHashFunction()
{
}
@Override
public long initialise( long seed )
{
return seed;
}
@Override
public long update( long intermediateHash, long value )
{
return hashSingleValueToInt( intermediateHash + value );
}
@Override
public long finalise( long intermediateHash )
{
return intermediateHash;
}
@Override
public int hashSingleValueToInt( long value )
{
int h = (int) ((value >>> 32) ^ value);
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}
| [
"[email protected]"
] | |
b700f8ab40c5448ea2c5bd618e18d8346e6bf94d | 8d85bd979c08a6313c31d00fd3f10bbe836d691d | /cameraserver/src/main/java/edu/wpi/first/vision/VisionThread.java | 576cb9672b62ab296ed347edb00fc14b8d89e1e2 | [
"BSD-3-Clause"
] | permissive | Aaquib111/allwpilib | e7c1a9eb0693867287494da2c38125354b295476 | 59507b12dc6aec05167fb9c086c3a70c9e5ed632 | refs/heads/master | 2020-09-11T20:59:51.018124 | 2019-11-16T05:51:31 | 2019-11-16T05:51:31 | 222,188,562 | 2 | 0 | NOASSERTION | 2019-11-17T02:52:19 | 2019-11-17T02:52:19 | null | UTF-8 | Java | false | false | 1,943 | java | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2016-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.vision;
import edu.wpi.cscore.VideoSource;
/**
* A vision thread is a special thread that runs a vision pipeline. It is a <i>daemon</i> thread;
* it does not prevent the program from exiting when all other non-daemon threads
* have finished running.
*
* @see VisionPipeline
* @see VisionRunner
* @see Thread#setDaemon(boolean)
*/
public class VisionThread extends Thread {
/**
* Creates a vision thread that continuously runs a {@link VisionPipeline}.
*
* @param visionRunner the runner for a vision pipeline
*/
public VisionThread(VisionRunner<?> visionRunner) {
super(visionRunner::runForever, "WPILib Vision Thread");
setDaemon(true);
}
/**
* Creates a new vision thread that continuously runs the given vision pipeline. This is
* equivalent to {@code new VisionThread(new VisionRunner<>(videoSource, pipeline, listener))}.
*
* @param videoSource the source for images the pipeline should process
* @param pipeline the pipeline to run
* @param listener the listener to copy outputs from the pipeline after it runs
* @param <P> the type of the pipeline
*/
public <P extends VisionPipeline> VisionThread(VideoSource videoSource,
P pipeline,
VisionRunner.Listener<? super P> listener) {
this(new VisionRunner<>(videoSource, pipeline, listener));
}
}
| [
"[email protected]"
] | |
fb1322e2da5b4186abd6b6a91959421f31f0b15b | 8e2b58ba3daa2c4a4a30a6aa14bf4b041888be7f | /app/src/main/java/com/androidchatapp/Knob_Unlock_Activity.java | 286370a7f77ce07b67c54744fb4f84dfa28dd433 | [] | no_license | billkao1013/MeetYou_AndroidChatApp | 00b7a062915a210997c8832a0389a139b274f4c9 | cb717e7c0a574a5ca2b093bc8aa1920a1f8e63ec | refs/heads/master | 2021-05-09T10:29:56.056286 | 2018-01-25T20:44:51 | 2018-01-25T20:44:51 | 118,964,381 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 788 | java | package com.androidchatapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by billkao on 4/25/17.
*/
public class Knob_Unlock_Activity extends AppCompatActivity implements Fragment_FancyRotaryKnob.UnlockListener{
final static int FANCYROTARYVIEWFRAGMENT = 6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fancy_knob_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.knob_container, Fragment_FancyRotaryKnob.newInstance(0))
.commit();
}
@Override
public void Unlock(){
startActivity(new Intent(this, Main_activity.class));
}
}
| [
"[email protected]"
] | |
3c9183c352c96d52ecb5981b4950b186f5540ea0 | 2dd5750074b66ace2da9114a4f6ecdb2495cd992 | /src/java/com/thinkgem/jeesite/modules/sys/entity/Office.java | d22464cf7a59a9d1a55c0f4d5cedebb37e40d676 | [] | no_license | reharder1200/socialAffairControl | 505296ed19921444886e2e1f01e1d5c345d8b32e | daf83ec1dc193a0181d1faebfc775cae0f654009 | refs/heads/master | 2022-11-06T23:01:01.320311 | 2020-07-03T09:46:00 | 2020-07-03T09:46:00 | 271,162,608 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,406 | java | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.entity;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.TreeEntity;
/**
* 机构Entity
* @author ThinkGem
* @version 2013-05-15
*/
public class Office extends TreeEntity<Office> {
private static final long serialVersionUID = 1L;
// private Office parent; // 父级编号
// private String parentIds; // 所有父级编号
private Area area; // 归属区域
private String code; // 机构编码
// private String name; // 机构名称
// private Integer sort; // 排序
private String type; // 机构类型(1:公司;2:部门;3:小组)
private String grade; // 机构等级(1:一级;2:二级;3:三级;4:四级)
private String address; // 联系地址
private String zipCode; // 邮政编码
private String master; // 负责人
private String phone; // 电话
private String fax; // 传真
private String email; // 邮箱
private String useable;//是否可用
private User primaryPerson;//主负责人
private User deputyPerson;//副负责人
private List<String> childDeptList;//快速添加子部门
public Office(){
super();
// this.sort = 30;
this.type = "2";
}
public Office(String id){
super(id);
}
public List<String> getChildDeptList() {
return childDeptList;
}
public void setChildDeptList(List<String> childDeptList) {
this.childDeptList = childDeptList;
}
public String getUseable() {
return useable;
}
public void setUseable(String useable) {
this.useable = useable;
}
public User getPrimaryPerson() {
return primaryPerson;
}
public void setPrimaryPerson(User primaryPerson) {
this.primaryPerson = primaryPerson;
}
public User getDeputyPerson() {
return deputyPerson;
}
public void setDeputyPerson(User deputyPerson) {
this.deputyPerson = deputyPerson;
}
// @JsonBackReference
// @NotNull
public Office getParent() {
return parent;
}
public void setParent(Office parent) {
this.parent = parent;
}
//
// @Length(min=1, max=2000)
// public String getParentIds() {
// return parentIds;
// }
//
// public void setParentIds(String parentIds) {
// this.parentIds = parentIds;
// }
@NotNull
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
//
// @Length(min=1, max=100)
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Integer getSort() {
// return sort;
// }
//
// public void setSort(Integer sort) {
// this.sort = sort;
// }
@Length(min=1, max=1)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Length(min=1, max=1)
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
@Length(min=0, max=255)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Length(min=0, max=100)
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
@Length(min=0, max=100)
public String getMaster() {
return master;
}
public void setMaster(String master) {
this.master = master;
}
@Length(min=0, max=200)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Length(min=0, max=200)
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
@Length(min=0, max=200)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Length(min=0, max=100)
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
// public String getParentId() {
// return parent != null && parent.getId() != null ? parent.getId() : "0";
// }
@Override
public String toString() {
return name;
}
} | [
"[email protected]"
] | |
dd795ecd18d175ed88c8af460cc1501a1cdc377f | 7f311a714599184dbdfcef7c143f727a2077af50 | /build/generated-sources/ap-source-output/Models/BankBranch_.java | 3de6ba819b527cb7b6f3a6a694fb8a4d07954d86 | [] | no_license | FleuryRomain/ORM | d9ecd6d9ac95586afe4264c9918bfca0c338c522 | 7a6ab83061a942f2c82bc75607a7f730c300d056 | refs/heads/master | 2020-04-02T02:26:31.087312 | 2018-10-20T13:42:54 | 2018-10-20T13:42:54 | 153,909,319 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package Models;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-10-11T14:10:32")
@StaticMetamodel(BankBranch.class)
public class BankBranch_ {
public static volatile SingularAttribute<BankBranch, String> adresse;
public static volatile SingularAttribute<BankBranch, Integer> codeAgence;
} | [
"[email protected]"
] | |
a88c70f0148e105876db72f860ef9762d77dc482 | 566d65d148c28426349c84b3a819dc8dcd68dc85 | /src/registrar/mascota/RegistrarMascota.java | 054673f3e034146627949d1d95dbf82beb846d16 | [] | no_license | kevinah95/PetSaviors | 754c7ec5447a6adbe417f5deea975b3c2df6c3e1 | d77fd2013a6bd1316b6abeee560510143a0a983c | refs/heads/master | 2021-01-09T05:59:01.677848 | 2016-04-10T04:30:02 | 2016-04-10T04:30:02 | 26,179,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,999 | java | package registrar.mascota;
import javax.swing.JDialog;
import javax.swing.JPanel;
import java.awt.CardLayout;
public class RegistrarMascota extends JDialog {
public static String modoRegistro = "";
public static final String ENCONTRADO = "Encontrado";
public static final String EXTRAVIADO = "Extraviado";
static JPanel panelCards = new JPanel();
static CardLayout cardlayout = new CardLayout();
public static VistaEtapaImagenes vistaetapaimagenes;
public static VistaEtapaDatos vistaetapadatos;
public RegistrarMascota() {
setSize(600, 600);
setContentPane(panelCards);
panelCards.setLayout(cardlayout);
setLocationRelativeTo(null);
agregarPaneles();
setModal(true);
setAlwaysOnTop(true);
setModalityType(ModalityType.APPLICATION_MODAL);
setResizable(false);
setVisible(true);
}
public void agregarPaneles() {
ModeloEtapaSeleccion modeloetapaseleccion = new ModeloEtapaSeleccion();
VistaEtapaSeleccion etapaseleccion = new VistaEtapaSeleccion();
new ControladorEtapaSeleccion(etapaseleccion,modeloetapaseleccion);
panelCards.add("VistaEtapaSeleccion", etapaseleccion);
vistaetapadatos = new VistaEtapaDatos();
ModeloEtapaDatos modeloetapadatos = new ModeloEtapaDatos();
new ControladorEtapaDatos(vistaetapadatos,modeloetapadatos);
panelCards.add("VistaEtapaDatos", vistaetapadatos);
ModeloEtapaImagenes modeloetapaimagenes = new ModeloEtapaImagenes();
vistaetapaimagenes = new VistaEtapaImagenes();
new ControladorEtapaImagenes(vistaetapaimagenes,modeloetapaimagenes);
panelCards.add("VistaEtapaImagenes", vistaetapaimagenes);
cardlayout.show(panelCards, "VistaEtapaSeleccion");
}
public static void main(String[] args) {
RegistrarMascota reg = new RegistrarMascota();
}
public static void actualizarModo() {
if (modoRegistro.equals(ENCONTRADO)) {
vistaetapaimagenes.txtRecompensa.setEnabled(false);
} else if (modoRegistro.equals(EXTRAVIADO)) {
vistaetapaimagenes.txtRecompensa.setEnabled(true);
}
}
}
| [
"[email protected]"
] | |
055d471a9dcc0b8082522df861475fc717bb57de | 85a721430ec52fb989a6c2afea2396d7cdead0ba | /Eclispe_Workspace/src/com/gforg/misc/MergeIntervals.java | dbcac7bfb71a247bb67d00280ce4e3af2fb281d5 | [] | no_license | akiankit/JavaCodes | 395c003ed75a748118fe42041e1d0175b7e98762 | e5f549cca8e2134a46deb527a1ba12467e7ca5f0 | refs/heads/master | 2021-01-01T20:12:38.745370 | 2018-02-25T11:02:13 | 2018-02-25T11:02:13 | 40,881,053 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,025 | java |
package com.gforg.misc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MergeIntervals {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int t = Integer.parseInt(line);
for (int i = 0; i < t; i++) {
line = sc.nextLine();
int num = Integer.parseInt(line);
line = sc.nextLine();
String[] words = line.split(" ");
Interval[] intervals = new Interval[num];
int index = 0;
for (int j = 0; j < words.length; j += 2) {
int d1 = Integer.parseInt(words[j]);
int d2 = Integer.parseInt(words[j + 1]);
intervals[index++] = new Interval(d1, d2);
}
mergeIntervals(intervals);
}
sc.close();
}
public static void mergeIntervals(Interval[] intervals) {
// System.out.println(Arrays.toString(intervals));
Arrays.sort(intervals);
List<Interval> list = mergeOverlappingTracks(intervals);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).col1 + " " + list.get(i).col2 + " ");
}
}
private static List<Interval> mergeOverlappingTracks(Interval[] intervals) {
int size = intervals.length;
List<Interval> newIntervals = new ArrayList<>(size);
if (size == 1) {
newIntervals.add(intervals[0]);
return newIntervals;
}
for (int i = 0; i < size;) {
Interval start = intervals[i];
int c2 = start.col2;
i++;
while (i < size && c2 >= intervals[i].col1) {
c2 = Math.max(c2, intervals[i].col2);
i++;
}
newIntervals.add(new Interval(start.col1, c2));
}
return newIntervals;
}
static class Interval implements Comparable<Interval> {
int col1;
int col2;
public Interval(int col1, int col2) {
this.col1 = col1;
this.col2 = col2;
}
@Override
public String toString() {
return "[col1=" + col1 + ",col2=" + col2 + "]";
}
@Override
public int compareTo(Interval o) {
if (this.col1 == o.col1)
return this.col2 - o.col2;
return this.col1 - o.col1;
}
}
}
| [
"[email protected]"
] | |
22296fbc57b1806ca879be3bd55920bf5e91fa11 | 282f4c25f709c7b1dc5ba9107068d565dc0b9851 | /Hospital/src/Model/MedicalItems.java | 8994d4deb05806110eef269ac382f67cf3c14b66 | [] | no_license | maniratnam284/masters-projects | 6a6c7f1219ad56db6799c467cbf580c48024ce82 | 4b9c4dbbc042c341a5277824a2ce1d9857c3701a | refs/heads/master | 2020-07-23T06:00:46.616728 | 2017-06-14T16:47:15 | 2017-06-14T16:47:15 | 94,351,159 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 939 | java | package Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "MEDICALITEMS")
public class MedicalItems {
@Id @GeneratedValue
@Column(name = "ID")
long id;
@Column(name = "MEDICALITEMCODE")
String medicalItemCode;
@Column(name = "MEDICALITEMDESCRIPTION")
String medicalItemDescription;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMedicalItemCode() {
return medicalItemCode;
}
public void setMedicalItemCode(String medicalItemCode) {
this.medicalItemCode = medicalItemCode;
}
public String getMedicalItemDescription() {
return medicalItemDescription;
}
public void setMedicalItemDescription(String medicalItemDescription) {
this.medicalItemDescription = medicalItemDescription;
}
}
| [
"[email protected]"
] | |
f35e7b92afd1a61657a777d887a5546e662047b1 | c424a70daad91c88c937daa723edb6164b898ec4 | /JavaRush/javarush/test/level18/lesson08/task04/TxtInputStream.java | 606776db168845809180b16b2e8abb9b1410b23e | [] | no_license | MrAndersonn/Java | 71c02613a0323dee29390f55a0560a6b2420f9b6 | 2b71562b2e6c5b0f7fff45be8ad93133c4b0cc13 | refs/heads/master | 2021-01-22T11:37:41.901558 | 2015-09-06T17:01:41 | 2015-09-06T17:01:41 | 33,201,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 812 | java | package com.javarush.test.level18.lesson08.task04;
import java.io.*;
/* UnsupportedFileName
Измените класс TxtInputStream так, чтобы он работал только с txt-файлами (*.txt)
Например, first.txt или name.1.part3.txt
Если передан не txt-файл, например, file.txt.exe, то конструктор должен выбрасывать исключение UnsupportedFileNameException
*/
public class TxtInputStream extends FileInputStream
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public TxtInputStream(String fileName) throws FileNotFoundException, Exception
{
super(fileName);
if (!fileName.endsWith(".txt")) throw new UnsupportedFileNameException();
}
}
| [
"[email protected]"
] | |
e7c3f2acba904daf29fdd6a3684526043029d109 | 2cf79a745b7f0b9d272155a3946146534fa3697c | /src/main/java/com/gdms/service/reply/impl/ReplyGroupStudentServiceImpl.java | e0e540cc9cdf9564dcf9433c18c5540784fd49d4 | [] | no_license | HackerStudy/gdms | fd30f95c1aedbcfd7a77385142f567fba673a8a4 | 915e42eb5d929145261eee8a7aa59e1a3a8e45a0 | refs/heads/master | 2020-03-14T01:29:44.196997 | 2018-06-22T12:18:48 | 2018-06-22T12:18:48 | 131,378,627 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,190 | java | package com.gdms.service.reply.impl;
import com.gdms.dao.ReplyGroupMapper;
import com.gdms.dao.ReplyGroupStudentMapper;
import com.gdms.dao.ReplyGroupTeacherMapper;
import com.gdms.model.ReplyGroupStudent;
import com.gdms.model.ReplyGroupTeacher;
import com.gdms.service.common.impl.BaseServiceImpl;
import com.gdms.service.reply.ReplyGroupService;
import com.gdms.service.reply.ReplyGroupStudentService;
import com.gdms.service.reply.ReplyGroupTeacherService;
import com.gdms.vo.ReplyStudentVo;
import com.github.pagehelper.PageHelper;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service("replyGroupStudentService")
@Transactional(rollbackFor = Exception.class)
public class ReplyGroupStudentServiceImpl extends BaseServiceImpl<ReplyGroupStudent> implements ReplyGroupStudentService {
private Logger log = Logger.getLogger(ReplyGroupStudentServiceImpl.class);
@Resource
private ReplyGroupStudentMapper replyGroupStudentMapper;
public List<ReplyStudentVo> queryReplyStudentVo() {
return replyGroupStudentMapper.queryReplyStudentVo();
}
public ReplyGroupStudent queryReplyGroupStudentBySid(String sid) {
return replyGroupStudentMapper.queryReplyGroupStudentBySid(sid);
}
public int insertReplyGroupStudent(ReplyGroupStudent replyGroupStudent) {
return replyGroupStudentMapper.insertReplyGroupStudent(replyGroupStudent);
}
public List<ReplyStudentVo> queryPageReplyStudentVo(Integer gid, Integer page, Integer rows) {
PageHelper.startPage(page, rows);
return queryReplyStudentVoByGid(gid);
}
public List<ReplyStudentVo> queryReplyStudentVoByGid(Integer gid) {
return replyGroupStudentMapper.queryReplyStudentVoByGid(gid);
}
public int queryCountReplyStudentVoByGid(Integer gid) {
return replyGroupStudentMapper.queryCountReplyStudentVoByGid(gid);
}
public List<ReplyGroupStudent> queryReplyGroupStudentByGid(Integer gid) {
return replyGroupStudentMapper.queryReplyGroupStudentByGid(gid);
}
}
| [
"[email protected]"
] | |
e17bbe75a826371830f8bf172da8f572d055c6ff | 6c8248f92606744d49c3d652c0b9021847f3380a | /Arc/src/main/java/msa/arc/base/BaseFragment.java | 394b7c58e0b2aaf3e99377b4bc23ad11001e9e5c | [
"Apache-2.0"
] | permissive | abhimuktheeswarar/Arena | e5346b23c688298dbc94f91464743f3ce3c8a90b | 471a1649839619e4a75ff1e9feaa9647543e71f8 | refs/heads/master | 2021-09-24T06:44:07.533034 | 2018-10-04T17:04:06 | 2018-10-04T17:04:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,978 | java | /*
* Copyright 2017, Abhi Muktheeswarar
*
* 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 msa.arc.base;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.support.v4.app.Fragment;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import rx.subscriptions.CompositeSubscription;
/**
* Created by Abhimuktheeswarar on 08-06-2017.
*/
public class BaseFragment extends Fragment implements Injectable {
protected final String TAG = this.getClass().getSimpleName();
@Inject
protected ViewModelProvider.Factory viewModelFactory;
protected CompositeDisposable compositeDisposable;
protected CompositeSubscription compositeSubscription;
protected <V extends BaseViewModel> V getViewModel(Class<V> viewModelClass) {
return ViewModelProviders.of(this, viewModelFactory).get(viewModelClass);
}
public Observable<Boolean> listenForInternetConnectivity() {
return ((BaseActivity) getActivity()).listenForInternetConnectivity();
}
@Override
public void onStart() {
super.onStart();
compositeDisposable = new CompositeDisposable();
compositeSubscription = new CompositeSubscription();
}
@Override
public void onStop() {
super.onStop();
compositeDisposable.dispose();
compositeSubscription.unsubscribe();
}
}
| [
"[email protected]"
] | |
8fa485096a2289d5dd751cc27cd684df41ea4606 | 359bba5d2f25b30a18d08c743e668be51edd4ed7 | /src/buoy/event/CellValueChangedEvent.java | e76e841169ccfd67fed7b679515b5da573d0ca2c | [
"Apache-2.0"
] | permissive | undeadinu/gavrog | 74e76d46f6818730aa4f5bf34b4593d8afdb8957 | 159ebdb80ba661c48164b392d59a0519ec643521 | refs/heads/master | 2020-04-16T06:18:20.625109 | 2018-11-05T09:50:08 | 2018-11-05T09:50:08 | 165,339,987 | 0 | 0 | Apache-2.0 | 2019-01-12T03:35:24 | 2019-01-12T03:05:54 | Java | UTF-8 | Java | false | false | 1,124 | java | package buoy.event;
import buoy.widget.*;
import java.util.*;
/**
* A CellValueChangedEvent is generated when the user edits the value in a cell of a BTable.
*
* @author Peter Eastman
*/
public class CellValueChangedEvent extends EventObject implements WidgetEvent
{
private Widget widget;
private int row, col;
/**
* Create a CellValueChangedEvent.
*
* @param widget the Widget whose value has changed
* @param row the row containing the cell whose value was edited
* @param col the column containing the cell whose value was edited
*/
public CellValueChangedEvent(Widget widget, int row, int col)
{
super(widget);
this.widget = widget;
this.row = row;
this.col = col;
}
/**
* Get the Widget which generated this event.
*/
public Widget getWidget()
{
return widget;
}
/**
* Get the row containing the cell whose value was edited.
*/
public int getRow()
{
return row;
}
/**
* Get the column containing the cell whose value was edited.
*/
public int getColumn()
{
return col;
}
}
| [
"[email protected]"
] | |
d274bab8969c82fe94b1834984b22ab6bf88dfa0 | 0cdd8fdce78a4d1563401385be4c8adaf657ba24 | /src/main/java/org/adostic/kata/RomanNumeral.java | 8f728294a039f8f9150976d1ca6441a5b615a404 | [] | no_license | adostic/kata | 3efe06cc237fd9e4e653c3760f587b4328f48f62 | 2217efd6712090f157fb885110e5f9740df23adf | refs/heads/master | 2021-01-20T02:17:13.178668 | 2015-03-31T10:47:46 | 2015-03-31T10:47:46 | 33,179,894 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,236 | java | package org.adostic.kata;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author adostic
* @since 31.03.2015 10:41:58 AM
*/
public class RomanNumeral {
private List<Mapping> mappings = new ArrayList<>(13);
public RomanNumeral() {
mappings.add(new Mapping(1000, "M"));
mappings.add(new Mapping(900, "CM"));
mappings.add(new Mapping(500, "D"));
mappings.add(new Mapping(400, "CD"));
mappings.add(new Mapping(100, "C"));
mappings.add(new Mapping(90, "XC"));
mappings.add(new Mapping(50, "L"));
mappings.add(new Mapping(40, "XL"));
mappings.add(new Mapping(10, "X"));
mappings.add(new Mapping(9, "IX"));
mappings.add(new Mapping(5, "V"));
mappings.add(new Mapping(4, "IV"));
mappings.add(new Mapping(1, "I"));
}
@SuppressWarnings("AssignmentToMethodParameter")
public String toRoman(int arabic) {
String result = "";
if (arabic < 0) {
result += "-";
arabic *= -1;
}
for (Mapping mapping : mappings) {
while (arabic >= mapping.arabic) {
result += mapping.roman;
arabic -= mapping.arabic;
}
}
return result;
}
}
class Mapping {
int arabic;
String roman;
public Mapping(int arabic, String roman) {
this.arabic = arabic;
this.roman = roman;
}
}
| [
"[email protected]"
] | |
86cbccb5da8440c61f6db16c7598915e3873b4a4 | ed932dd6b2d780da8d4c3acef6bb74f89d3820cc | /src/com/auxiliares/Auxiliares.java | e1b28f94c21b2ea85563608e687f1a8a6f2937a9 | [] | no_license | zGustavoTeles/ProjetoAgil | 97e7da9a9b1265fc8442d7a04f2e17cf32e1b622 | 37c956f81dcbe4610e0a4a5499cae3c52370e2e3 | refs/heads/main | 2023-02-12T08:37:41.924444 | 2021-01-11T22:06:22 | 2021-01-11T22:06:22 | 319,637,363 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 6,230 | java | package com.auxiliares;
import com.messageBox.MessageBox;
import totalcross.sys.Convert;
import totalcross.sys.Settings;
import totalcross.ui.Container;
import totalcross.ui.MainWindow;
import totalcross.ui.dialog.InputBox;
import totalcross.ui.font.Font;
import totalcross.ui.gfx.Color;
import totalcross.ui.image.Image;
public class Auxiliares {
public static final String NOMEAPP = "ALGIL";
public static final String VERSAO = "1.0";
public static final String TELEFONE = "(62) 9259-7360";
public static final String NOMESISTEMA = "AGIL-PC";
public static final String DESCRICAO = "Copyright©2020-Todos os direitos reservados";
public static final String ADM = "true";
public static final String SENHAADM = "agil@2031";
public static String NOMEUSUARIO = "";
public static int codigoVendedor;
public static int fonteSizeTab = Font.NORMAL_SIZE;
public static int fonteSizeGrid = Font.NORMAL_SIZE;
// private MenuBar mbar;
public static int defaultBackColor = Color.getRGB(11, 43, 149);
public static int defaultForeColor = Color.WHITE;
public static int lstSelectedColor = Color.getRGB(89, 85, 253);
public static int defaultSelectedButton = Color.getRGB(229, 132, 3);
public static int defaultForeColorButton = Color.getRGB(54, 54, 65);// Color.getRGB(11,43,149);
public static String usuario, nomeVendedor;
public static int codigoUnidade;
public static int secondStripeColor = Color.getRGB(173, 216, 230);
public static int firstStripeColor = Color.getRGB(255, 255, 255);
public static int highlightColor = Color.getRGB(0, 191, 255);
public static int checkColor = Color.getRGB(0, 0, 0);
public static int captionsBackColor = Color.getRGB(176, 224, 230);
public static int backColorGrid = Color.getRGB(176, 224, 230);
public static int borderColor3DG = Color.getRGB(50, 85, 131);
public static int defaultBackColorButton = Color.getRGB(101, 127, 154);
public static int fonteSize = Font.NORMAL_SIZE;
public static String CODIGOVENDEDOR;
//Novo
public static int defaultBackColorNovo = Color.getRGB(11, 43, 149);
public static int defaultForeColorNovo = 16777215;
public static int secondStripeColorNovo = Color.getRGB(240, 240, 240);
public static int firstStripeColorNovo = Color.getRGB(255, 255, 255);
public static int highlightColorNovo = Color.getRGB(0, 191, 255);
public static int checkColorNovo = Color.getRGB(0, 0, 0);
public static int captionsBackColorNovo = Color.getRGB(64, 95, 140);
public static int backColorGridNovo = Color.getRGB(176, 224, 230);
public static int defaultSelectedButtonNovo = Color.getRGB(191, 191, 191);
public static int defaultBackColorButtonNovo = Color.getRGB(251, 251, 251);
public static int defaultForeColorButtonNovo = Color.getRGB(83, 102, 113);
public static int defaultForeColorGridNovo = Color.getRGB(211, 211, 211);
public static int messagebox(String titulo, String msg) {
msg = Convert.insertLineBreak(2 * (Settings.screenWidth / 4), MainWindow.getMainWindow().fm, msg);
MessageBox amb = new MessageBox(titulo, msg);
amb.setRect(Container.CENTER, Container.CENTER, Container.SCREENSIZE + 60, Container.SCREENSIZE + 60);
amb.popup();
return amb.getPressedButonIndex();
}
public static int messageBox(String titulo, String msg, String[] captions) {
msg = Convert.insertLineBreak(2 * (Settings.screenWidth / 4), MainWindow.getMainWindow().fm, msg);
MessageBox amb = new MessageBox(titulo, msg, captions);
amb.setRect(Container.CENTER, Container.CENTER, Container.SCREENSIZE + 60, Container.SCREENSIZE + 60);
amb.popup();
return amb.getPressedButonIndex();
}
public static String messageInput(String titulo, String msg,
String textoDefault) {
InputBox inp_ = new InputBox(titulo, msg, textoDefault);
inp_.headerColor = Color.BLACK;
inp_.footerColor = Color.BLUE;
inp_.titleColor = Color.WHITE;
inp_.getEdit().setValidChars(
"@,._-1234567890qwertyuiopasdfghjkl�zxcvbnm");
inp_.repaintNow();
inp_.popup();
inp_.setBackForeColors(Color.BLUE, Color.BLUE);
if (inp_.getPressedButtonIndex() == 1) {
return "";
} else {
return inp_.getValue();
}
}
public static Image getLogo() {
try {
int w = Settings.screenWidth;
if (w >= 240 && w < 320)
return new Image("img/cadastrarProdutoEstoque.png");
else if (w >= 320)
return new Image("img/cadastrarProdutoEstoque.png");
else
return new Image("img/cadastrarProdutoEstoque.png");
} catch (Exception e) {
return null;
}
}
public static Font getFontDetalhe() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSize() - 5);
}
public static Font getFontDetalheCelulaCima() {
return Font.getFont(Font.DEFAULT, false, getFontSize());
}
public static Font getFontDetalheCelulaAbaixo() {
return Font.getFont(Font.DEFAULT, true, getFontSize());
}
public static Font getFontDetalheBold() {
return Font.getFont(Font.DEFAULT, true, getFontSize());// aarq
}
public static Font getFontPequenaBold() {
return Font.getFont(Font.DEFAULT, true, getFontSize() - 10);// aarq
}
public static int getFontSize() {
return fonteSize;
}
public static void setFontSize(int f) {
fonteSize = f;
}
public static void setFontSizeTab(int f) {
fonteSizeTab = f;
}
public static void setFontSizeGrid(int f) {
fonteSizeGrid = f;
}
public static int getFontSizeTab() {
return fonteSizeTab;
}
public static int getFontSizeGrid() {
return fonteSizeGrid;
}
public static Font getFontBold() {
return getFontNormal().asBold();
}
public static Font getFontNormal() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSize());
}
public static Font getFontGrande() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSize() + 10);
}
public static Font getFontPequena() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSize() - 4);
}
public static Font getFontGrid() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSizeGrid());
}
public static Font getFontGridBold() {
return Font.getFont(Font.DEFAULT, true, Auxiliares.getFontSizeGrid());
}
public static Font getFontTab() {
return Font.getFont(Font.DEFAULT, false, Auxiliares.getFontSizeTab());
}
}
| [
"[email protected]"
] | |
2db67f659568adbd0b744e75a6f9a5c3ae46f36d | 58df55b0daff8c1892c00369f02bf4bf41804576 | /src/hd.java | 7f8afcfc58d6f5825fb4e0218031fb1aa68c3ff4 | [] | no_license | gafesinremedio/com.google.android.gm | 0b0689f869a2a1161535b19c77b4b520af295174 | 278118754ea2a262fd3b5960ef9780c658b1ce7b | refs/heads/master | 2020-05-04T15:52:52.660697 | 2016-07-21T03:39:17 | 2016-07-21T03:39:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 213 | java | import android.graphics.Bitmap;
public final class hd
extends hs
{
Bitmap a;
Bitmap b;
boolean c;
}
/* Location:
* Qualified Name: hd
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"[email protected]"
] | |
c209de2ac2d783447270572bb152e96c992264dd | b73100051e1a758929ccbdb1b4412d23a9e484ca | /app/src/main/java/com/myunimaps/myunimaps/PolyConnector.java | 8dd75ef1453227fb651c98e35dafaf3411d6a4bb | [] | no_license | TylerAlexanderTX/MyUniMaps | b57b2e5b8105b309026f1b36e6b4ce098f34682b | 20086d71374df42ea0cce2bc5c7f9c82b4dedd2e | refs/heads/master | 2021-01-10T15:19:47.205929 | 2015-12-01T01:04:58 | 2015-12-01T01:04:58 | 47,156,147 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,841 | java | package com.myunimaps.myunimaps;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
/**
* Created by TY on 3/18/2015.
*/
public class PolyConnector {
public JSONArray GetAllPolys()
{
// URL for getting all customers
String url = "http://myunimap.com/getAllparking.php";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
//Log Errors Here
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
| [
"Tyler Alexander"
] | Tyler Alexander |
f1b32502754155cb647939ff6222abfc1e663cd0 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_a365e6fd912ee6b372625e4f8e4143deae986544/SpyglassApp/2_a365e6fd912ee6b372625e4f8e4143deae986544_SpyglassApp_t.java | 725236ba886f091937b96870ffe03321a03c265b | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,793 | java | /*
* ---------------------------------------------------------------------- This file is part of the
* WSN visualization framework SpyGlass. Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de)
* project SpyGlass is free software; you can redistribute it and/or modify it under the terms of
* the BSD License. Refer to spyglass-licence.txt file in the root of the SpyGlass source tree for
* further details. ------------------------------------------------------------------------
*/
package de.uniluebeck.itm.spyglass;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.DeviceData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import de.uniluebeck.itm.spyglass.core.Spyglass;
import de.uniluebeck.itm.spyglass.gui.UIController;
import de.uniluebeck.itm.spyglass.gui.actions.ExitSpyglassAction;
import de.uniluebeck.itm.spyglass.gui.actions.LoadConfigurationAction;
import de.uniluebeck.itm.spyglass.gui.actions.OpenPreferencesAction;
import de.uniluebeck.itm.spyglass.gui.actions.PlayPlayPauseAction;
import de.uniluebeck.itm.spyglass.gui.actions.PlaySelectInputAction;
import de.uniluebeck.itm.spyglass.gui.actions.RecordRecordAction;
import de.uniluebeck.itm.spyglass.gui.actions.RecordSelectOutputAction;
import de.uniluebeck.itm.spyglass.gui.actions.StoreConfigurationAction;
import de.uniluebeck.itm.spyglass.gui.actions.ZoomAction;
import de.uniluebeck.itm.spyglass.gui.actions.ZoomCompleteMapAction;
import de.uniluebeck.itm.spyglass.gui.view.AppWindow;
import de.uniluebeck.itm.spyglass.gui.view.DrawingArea;
import de.uniluebeck.itm.spyglass.util.SpyglassLoggerFactory;
// ------------------------------------------------------------------------------
// --
/**
* Application class for wrapping the Spyglass core class and it's user interface/GUI. It
* instantiate and injects the core classes that are needed to run the application.
*/
public class SpyglassApp extends ApplicationWindow {
private static Logger log = SpyglassLoggerFactory.getLogger(SpyglassApp.class);
private Spyglass spyglass;
private UIController uic;
private static Shell shell;
private AppWindow appWindow;
// -------------------------------------------------------------------------
/**
* @throws Exception
* @throws IOException
*
*/
public SpyglassApp(final Shell shell) throws Exception {
super(shell);
spyglass = new Spyglass();
this.setBlockOnOpen(true);
addStatusLine();
addToolBar(SWT.None);
addMenuBar();
}
// -------------------------------------------------------------------------
/**
* @throws Exception
* @throws IOException
*
*/
public static void main(final String[] args) {
// SWT stuff
final DeviceData data = new DeviceData();
data.tracking = true;
data.debug = true;
final Display display = new Display(data);
shell = new Shell(display);
SpyglassApp app = null;
try {
app = new SpyglassApp(shell);
app.open();
} catch (final Exception e) {
log.error(e,e);
} finally {
if (app != null) {
app.shutdown();
}
}
}
@Override
protected MenuManager createMenuManager() {
final MenuManager man = super.createMenuManager();
final MenuManager fileMenu = createFileMenu();
final MenuManager mapMenu = createMapMenu();
final MenuManager sourceMenu = createSourceMenu();
final MenuManager recordMenu = createRecordMenu();
man.add(fileMenu);
man.add(mapMenu);
man.add(sourceMenu);
man.add(recordMenu);
return man;
}
@Override
protected Control createContents(final Composite parent) {
// Model
SpyglassEnvironment.setIShellPlugin(false);
appWindow = new AppWindow(spyglass, getShell());
// Control
uic = new UIController(spyglass, appWindow);
new ToolbarHandler(getToolBarManager(), spyglass, appWindow);
spyglass.start();
return parent;
}
@Override
protected void configureShell(final Shell shell) {
super.configureShell(shell);
shell.setText("Spyglass");
shell.setSize(SpyglassEnvironment.getWindowSizeX(),
SpyglassEnvironment.getWindowSizeY());
shell.addControlListener(new ControlAdapter() {
@Override
public void controlResized(final ControlEvent e) {
log.info("Shell resized.");
try {
SpyglassEnvironment.setWindowSizeX(shell.getSize().x);
SpyglassEnvironment.setWindowSizeY(shell.getSize().y);
} catch (final IOException e1) {
log.error(e1,e1);
}
}
});
}
public DrawingArea getDrawingArea() {
return appWindow.getGui().getDrawingArea();
}
public void shutdown() {
if (uic != null) {
uic.shutdown();
}
if (spyglass != null) {
spyglass.shutdown();
}
}
private MenuManager createSourceMenu() {
final MenuManager sourceMenu = new MenuManager("&Source");
sourceMenu.add(new PlaySelectInputAction(shell, spyglass));
sourceMenu.add(new PlayPlayPauseAction(spyglass));
return sourceMenu;
}
private MenuManager createRecordMenu() {
final MenuManager recordMenu = new MenuManager("&Record");
recordMenu.add(new RecordSelectOutputAction(spyglass));
recordMenu.add(new RecordRecordAction(spyglass));
return recordMenu;
}
private MenuManager createMapMenu() {
final MenuManager mapMenu = new MenuManager("&Map");
mapMenu.add(new ZoomAction(this, ZoomAction.Type.ZOOM_IN));
mapMenu.add(new ZoomAction(this, ZoomAction.Type.ZOOM_OUT));
mapMenu.add(new ZoomCompleteMapAction(this, spyglass));
return mapMenu;
}
private MenuManager createFileMenu() {
final MenuManager fileMenu = new MenuManager("&File");
fileMenu.add(new LoadConfigurationAction(spyglass));
fileMenu.add(new StoreConfigurationAction(spyglass));
fileMenu.add(new Separator());
fileMenu.add(new OpenPreferencesAction(shell, spyglass));
fileMenu.add(new Separator());
fileMenu.add(new ExitSpyglassAction(this));
return fileMenu;
}
}
| [
"[email protected]"
] | |
c9a1fda17cb3b7664b5e657e122e3e62221e83a0 | 5c1a685df44ef7366a2a8e04b36e6dcb5513bc21 | /app/src/main/java/com/pranshuDatta/androidweatherapp/entity/LocationObject.java | 166d41cdee0394e5a40034d4ec4c5e3e0ea77d8f | [] | no_license | pranshudatta25/TheWeatherApp | 23460135c7ba0b3f11d92348d2b55b30e393465a | a103f13c5eaf319d5fbd76f09cfa265957bbcdc4 | refs/heads/master | 2020-07-30T08:27:45.952994 | 2019-09-22T13:51:27 | 2019-09-22T13:51:27 | 210,155,205 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 600 | java | package com.pranshuDatta.androidweatherapp.entity;
public class LocationObject {
private int id;
private String locationCity;
private String weatherInformation;
public LocationObject(int id, String locationCity, String weatherInformation) {
this.id = id;
this.locationCity = locationCity;
this.weatherInformation = weatherInformation;
}
public String getLocationCity() {
return locationCity;
}
public String getWeatherInformation() {
return weatherInformation;
}
public int getId() {
return id;
}
}
| [
"[email protected]"
] | |
805327150f10c17aa7446a4c2d228533239da39a | 162045517fe2be5fcc7161f8c18f5a318944bde1 | /trunk/webapi/src/main/java/com/ry/project/bussiness/domain/response/teacher/LeavemessageChild.java | 2ce74e8f6b226f1f315c3c493d9410bb6b674a7f | [] | no_license | zhangjihai520/gzzbk | 45fe870310c13c0b7fdddbcfbbc273b0aa787cab | 4322d57a10539116ae2a494abd1f674c4ce215ac | refs/heads/master | 2023-03-04T15:36:58.725799 | 2021-02-18T09:04:46 | 2021-02-18T09:04:46 | 339,990,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 617 | java | package com.ry.project.bussiness.domain.response.teacher;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
/**
* @Auther: 幸仁强
* @Date: 2020/4/16 15:34
* @Description: 返回实体对象基类
*/
@Data
@Accessors(chain = true)
public class LeavemessageChild {
private String id;
private String userName;
private String userFace;
private String repalyId;
private String content;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
}
| [
"[email protected]"
] | |
bfcb5dc1d542a539a7f87a57378ea90602469571 | fa6693a5b51e517236399532e18ecad3040b5e25 | /src/test/java/com/liesbethdekeyzer/crm/demo/DemoApplicationTests.java | 16c8ad9ae196c1890564b5e94aaf0177545b6a2a | [] | no_license | Liesbethdekeyzer/CRM | 1cf931fc2aef0c27314f9a4f61b4be20ec9b1d13 | 6e2a5b09bd7391a9d9185d55e8d41b3ec19bf2c3 | refs/heads/master | 2021-07-26T01:25:30.904826 | 2017-11-05T10:46:35 | 2017-11-05T10:46:35 | 109,119,959 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 344 | java | package com.liesbethdekeyzer.crm.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"[email protected]"
] | |
84be7759f9d807e6f44e1a111e715ce03b0885b2 | 118975c2d0e3441ad6c9a2ea09deda187e7507ca | /concurrency/src/main/java/com/xiattong/concurrency/unit3/NoVisibility.java | a14f892c6dfaf0f6d8ed98e3f40dabe0129808e7 | [] | no_license | xiattong/spring-basic | b2e24fa637e2d3ca2c46cd52e9dd6a893d8b10dd | 16195654a9b5b3eb438284d9987c7825e06dc4d6 | refs/heads/master | 2022-06-26T00:02:03.562515 | 2022-04-15T15:36:02 | 2022-04-15T15:36:02 | 243,045,698 | 0 | 0 | null | 2022-06-17T03:03:56 | 2020-02-25T16:18:44 | Java | UTF-8 | Java | false | false | 543 | java | package com.xiattong.concurrency.unit3;
/**
* @Author: xiattong
* @Date: 2020/2/28 9:07
*/
public class NoVisibility {
private static boolean ready = false;
private static int number = 0;
public static class ReaderThread extends Thread{
public void run(){
while(!ready){
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) {
new ReaderThread().start();
number = 10;
ready = true;
}
}
| [
"[email protected]"
] | |
76f083d3673bd010e700e0e753204c6d7ce55ecc | 8f56a684fd259321ab7328d0ef91b6cf57eef5ce | /GameProject/app/src/main/java/uoft/csc207/gameproject/scoreboard/Scoreboard.java | a25ab650f0162d6569bf6ec39a4480e690e595a5 | [] | no_license | rain169170/CSC207-Android-Mobile-Application | 08a2703fca7a23f1adde5137317d4fbd4553e7af | bcf8f77d1e4dd4cd62e503ca905eff2e4f3e2789 | refs/heads/master | 2022-12-14T00:17:36.439163 | 2020-09-11T03:50:28 | 2020-09-11T03:50:28 | 294,582,567 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,679 | java | package uoft.csc207.gameproject.scoreboard;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the scoreboard of a game.
*/
public class Scoreboard {
/**
* Represents the size of each scoreboard, i.e. the number of entries (username, score)
* allowed in one scoreboard.
*/
private static final int SCOREBOARD_SIZE = 5;
private String name;
private List<Score> scoreList;
/**
* Construct a new scoreboard with name only. The list of scores will be an empty arraylist.
*/
Scoreboard(String name) {
this(name, null);
}
/**
* Construct a new scoreboard with name and list of scores.
*/
Scoreboard(String name, List<Score> scoreList) {
this.name = name;
if (scoreList == null) {
this.scoreList = new ArrayList<>();
} else {
this.scoreList = scoreList;
}
}
/**
* Return the name of the scoreboard.
*/
public String getName() {
return name;
}
/**
* Set the name of the scoreboard to the desired name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Return the list of scores shown on the scoreboard.
*/
public List<Score> getScoreList() {
return scoreList;
}
/**
* Update the scoreboard by adding a new score entry to the scoreboard. Maintain the size
* of the scoreboard within the allowed size.
*/
void update(Score score) {
if (score.getScore() < 0) {
return;
}
int index = 0;
for (int i = 0; i < scoreList.size(); i++) {
Score item = scoreList.get(i);
if (score.getScore() >= item.getScore()) {
index = i;
}
}
scoreList.add(index, score);
if (scoreList.size() > SCOREBOARD_SIZE) {
scoreList.remove(scoreList.size() - 1);
}
}
}
| [
"[email protected]"
] | |
11def26b342ba022494cf5fdc087802c9c7ce3b0 | 14e8c5853c8dd3d8b4a233ddaee4fb4d7aa310ad | /src/main/java/ru/job4j/loop/PrimeNumber.java | 26fc3afc5fa3c344fc83238f166d4f4991f6b3be | [] | no_license | Sinitsina/job4j_syntax-core | af82dad0ee3566dae554043b9c61d9291adecb5d | 73e07c92b9b5c939198031fdc68f3fa8f5ad6ffc | refs/heads/master | 2023-03-31T15:09:49.200465 | 2021-04-03T14:56:40 | 2021-04-03T14:56:40 | 267,080,699 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package ru.job4j.loop;
public class PrimeNumber {
public int calc(int finish) {
int count = 0;
for (int number = 2; number <= finish; number++) {
if (CheckPrimeNumber.check(number)) {
count++;
}
}
return count;
}
}
| [
"[email protected]"
] | |
da3a0ecdd3a03619217beaf385cfb85282fc96c1 | 3131e524a962e62ef1b1cf66bd91abfbad2b49ad | /src/main/java/com/aimprosoft/camed/compiler/extensions/DbLookupList.java | 7f01bfd507e8cb23d6c0c87037cc9478fb2a35c7 | [] | no_license | mikleee/camed | 7efb4a4fb19fe4d62df6a575f814bb6f9cea28c1 | 2d8795cafdbd0d15783ccb11cc4d12a3b031a8a5 | refs/heads/master | 2021-01-17T07:08:24.573450 | 2015-03-02T18:51:34 | 2015-03-02T18:51:34 | 30,844,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 919 | java | package com.aimprosoft.camed.compiler.extensions;
import org.jdom.Element;
public class DbLookupList implements ILookupList{
private String name = null;
private String value = null;
public DbLookupList(String name, String value){
this.name = name;
this.value = value;
}
public DbLookupList(Element listElement) {
name = listElement.getAttributeValue("name");
value = listElement.getValue();
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public Element toXML(){
Element element = new Element("DbLookupList",
DbLookupLists.DbLookupListsNamespace);
element.setAttribute("name", name);
element.setText(value);
return element;
}
public Element toCXF(){
return toXML();
}
@Override
public Element toDoc() {
// TODO Auto-generated method stub
return toXML();
}
public void setValue(String value) {
this.value = value;
}
}
| [
"[email protected]"
] | |
18fc9bb8dd45beafb0266c70e78660af41667528 | 8cf583828e06226c51217998e57ffc519cbe3218 | /app/src/main/java/com/leaveschool/main/DropEditText.java | 9e2f8841bd6fd632639b69b1abd2a4a932689c7c | [] | no_license | fly-bear/LeaveSchool | 41d461a572722e585708c54305a29e8c32145692 | f9a86263f5da621b85b7a7b62cd951833e9d1f65 | refs/heads/master | 2020-03-07T17:59:55.744581 | 2018-04-01T12:18:15 | 2018-04-01T12:18:15 | 127,626,179 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,238 | java | package com.leaveschool.main;
//import org.loader.dropedittext.R;
//import org.loader.dropedittext.R.drawable;
//import org.loader.dropedittext.R.id;
//import org.loader.dropedittext.R.layout;
//import org.loader.dropedittext.R.styleable;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import com.leaveschool.R;
public class DropEditText extends FrameLayout implements View.OnClickListener, OnItemClickListener {
private EditText mEditText; // 输入框
private ImageView mDropImage; // 右边的图片按钮
private PopupWindow mPopup; // 点击图片弹出popupwindow
private WrapListView mPopView; // popupwindow的布局
private int mDrawableLeft;
private int mDropMode; // flow_parent or wrap_content
private String mHit;
public DropEditText(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DropEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater.from(context).inflate(R.layout.edit_layout, this);
mPopView = (WrapListView) LayoutInflater.from(context).inflate(R.layout.pop_view, null);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DropEditText, defStyle, 0);
mDrawableLeft = ta.getResourceId(R.styleable.DropEditText_drawableRight, R.drawable.drop);
mDropMode = ta.getInt(R.styleable.DropEditText_dropMode, 0);
mHit = ta.getString(R.styleable.DropEditText_hint);
ta.recycle();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mEditText = (EditText) findViewById(R.id.dropview_edit);
mDropImage = (ImageView) findViewById(R.id.dropview_image);
mEditText.setSelectAllOnFocus(true);
// mEditText.setOnClickListener(listener);
mDropImage.setImageResource(mDrawableLeft);
if(!TextUtils.isEmpty(mHit)) {
mEditText.setHint(mHit);
}
mDropImage.setOnClickListener(this);
mPopView.setOnItemClickListener(this);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
// 如果布局发生改
// 并且dropMode是flower_parent
// 则设置ListView的宽度
if(changed && 0 == mDropMode) {
mPopView.setListWidth(getMeasuredWidth());
}
}
/**
* 设置Adapter
* @param adapter ListView的Adapter
*/
public void setAdapter(BaseAdapter adapter) {
mPopView.setAdapter(adapter);
mPopup = new PopupWindow(mPopView, 750, LinearLayout.LayoutParams.WRAP_CONTENT);
// mPopup.setBackgroundDrawable(new ColorDrawable(color.transparent));
mPopup.setFocusable(true); // 让popwin获取焦点
}
/**
* 获取输入框内的内容
* @return String content
*/
public String getText() {
return mEditText.getText().toString();
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.dropview_image) {
if(mPopup.isShowing()) {
mPopup.dismiss();
return;
}
mPopup.showAsDropDown(this, 0, 5);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mEditText.setText(mPopView.getAdapter().getItem(position).toString());
mPopup.dismiss();
}
public void setText(String str){
mEditText.setText(str);
}
public ImageView getmDropImage() {
return mDropImage;
}
public void setmEditTextUnfouse(){
mEditText.setCursorVisible(false);
mEditText.setFocusable(false);
// mEditText.setFocusableInTouchMode(false);
}
public EditText getmEditText(){
return mEditText;
}
// private OnClickListener listener ;
//
// public void setListener(OnClickListener listener) {
// this.listener = listener;
// }
}
| [
"[email protected]"
] | |
d6047dd959f601579a4d8cd2cb47e1e04e481aa1 | 3e05dd689f17128fe2adabcea61d90ebac9dda4d | /src/p1/ForgotPassMail.java | aec243bba8ddc4302f40e74c6bc9169f8c024353 | [] | no_license | yhimg/OnlineHouseRental | e052800a24a242ed51b5f485374bec49d8f65130 | 615afd8fec76f3ad8a1bb5a6ee6d5cc7b50b1ad8 | refs/heads/master | 2021-06-19T05:46:25.388348 | 2017-07-15T09:47:42 | 2017-07-15T09:47:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,474 | java | package p1;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ForgotPassMail extends HttpServlet
{
public static String from="[email protected]";// provide the sender's email address here
public static String password="password";// provide the sender's password here
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
int j=0;
PrintWriter out=res.getWriter();
String pass = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
System.out.println("pass = " + pass);
String to=req.getParameter("email");
Connection con=DBInfo.getConnection();
String update="update login set password=? where email=?";
try
{
PreparedStatement ps=con.prepareStatement(update);
ps.setString(1, pass);
ps.setString(2, to);
j=ps.executeUpdate();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
if(j==0)
{
/*RequestDispatcher rd = req.getRequestDispatcher*/res.sendRedirect("../WrongPassword.jsp");
/*rd.include(req, res);
out.println("<center><h2><font color='red' >Email not registered. Try Again.</font></h2></center>");*/
}
else
{
String msg="Dear User, \n\t We are sending a temporary password, please login to your account\n"+"using this, and change it immediately. \n Password="+
pass+"\nThanks. \n This is an automatic generated email. please donot reply to this. as all mail will directly transferred to trash.";
//String msg=req.getParameter("msg");
String subject="Account Registration";
System.out.println("to:->"+to);
int i = 0;
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, password);
}
}
);
try
{
final MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress addressTo = new InternetAddress(to);
/*for (int j = 0; j < to.length; j++)
{
addressTo[j] = new InternetAddress(to[j]);
}*/
message.setRecipient(Message.RecipientType.BCC, addressTo);
message.setSubject(subject); //set subject
message.setText(msg); //set message
new Thread(new Runnable()
{
public void run()
{
try
{
Transport.send(message);
}
catch (Exception e){e.printStackTrace();}
}
}).start();
session = null;
i = 1;
res.sendRedirect("../PasswordSent.jsp");
}
catch (MessagingException mex)
{
mex.printStackTrace();
// return i;
}
//return i;
}
}
} | [
"[email protected]"
] | |
022108c0ad7f309825541623a40a2b092cf8bf57 | 90222726ecafa3fe3897fae20740c69d82bbe812 | /Project/src/com/Jobseek/Controller/VisionController.java | f5babbed75076c2fad5653daa68144c238a874fd | [] | no_license | VenkateshBhatOP/PGJQP_Venkatesh-bhat | 0c17b3bc8b7bd6b349c7bc35dd718af16e408ab5 | aef231d06b35c5ccd7016646819f1d7ee18337a9 | refs/heads/main | 2023-03-31T19:10:19.738974 | 2021-04-02T10:56:11 | 2021-04-02T10:56:11 | 311,357,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,412 | java | package com.Jobseek.Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class VisionController
*/
@WebServlet("/VisionController")
public class VisionController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public VisionController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
request.setAttribute("pagename", "vision");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| [
"[email protected]"
] | |
828b72089437a92d1176679840f5925f72de1085 | 7b225fba903b1af050e8dd7db7959ee0449231d8 | /backend/src/main/java/com/app/dropbox/service/GroupService.java | 6a94d3c01834913df2d8e9235fb200a893849fc7 | [] | no_license | asbharadiya/dropbox_v3 | 73911af0cd834bd6f63f5475779c954d8b9caef7 | c9fb1a459883ca1777fb191f0408bc76cc7348da | refs/heads/master | 2021-08-28T08:05:43.819072 | 2017-12-11T16:17:11 | 2017-12-11T16:17:11 | 113,811,418 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,791 | java | package com.app.dropbox.service;
import com.app.dropbox.dto.GroupDto;
import com.app.dropbox.dto.UserDto;
import com.app.dropbox.entity.Group;
import com.app.dropbox.entity.User;
import com.app.dropbox.entity.UserActivity;
import com.app.dropbox.repository.GroupRepository;
import com.app.dropbox.repository.UserActivityRepository;
import com.app.dropbox.repository.UserRepository;
import com.app.dropbox.utils.CustomException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class GroupService {
@Autowired
private UserRepository userRepository;
@Autowired
private GroupRepository groupRepository;
@Autowired
private UserActivityRepository userActivityRepository;
public void createGroup(Long userId, JSONObject jsonData) throws Exception {
if(jsonData.getString("name") == null || jsonData.getString("name").length() == 0){
throw new CustomException("Required fields missing",400);
}
Group g = new Group();
g.setName(jsonData.getString("name"));
User u = userRepository.findOne(userId);
g.setOwner(u);
groupRepository.save(g);
UserActivity act = new UserActivity();
act.setAction("New group created");
act.setCreatedDate(new Date());
act.setOwner(u);
userActivityRepository.save(act);
}
public void updateGroup(JSONObject jsonData) throws Exception {
if(jsonData.getString("name") == null || jsonData.getString("name").length() == 0 || jsonData.getLong("groupId") == 0){
throw new CustomException("Required fields missing",400);
}
Group g = groupRepository.findOne(jsonData.getLong("groupId"));
g.setName(jsonData.getString("name"));
groupRepository.save(g);
}
public List<GroupDto> getGroups(Long userId) throws Exception {
User user = userRepository.findOne(userId);
List<GroupDto> groups = groupRepository.getGroupsByOwner(user);
return groups;
}
public GroupDto getGroupById(Long id) throws Exception {
Group group = groupRepository.findOne(id);
GroupDto dto = new GroupDto();
dto.setId(group.getId());
dto.setName(group.getName());
Set<UserDto> membersDto = new HashSet<>();
for(User u:group.getMembers()){
UserDto udto = new UserDto();
udto.setId(u.getId());
udto.setUsername(u.getFirstName()+" "+u.getLastName());
udto.setEmail(u.getEmail());
membersDto.add(udto);
}
dto.setMembers(membersDto);
return dto;
}
public void addRemoveMemberGroup(JSONObject jsonData) throws Exception {
if(jsonData.getString("action") == null || jsonData.getString("action").length() == 0 || jsonData.getLong("groupId") == 0 || jsonData.getLong("memberId") == 0){
throw new CustomException("Required fields missing",400);
}
Group g = groupRepository.findOne(jsonData.getLong("groupId"));
User u = userRepository.findOne(jsonData.getLong("memberId"));
Set<User> members = g.getMembers();
if(jsonData.getString("action").equals("ADD")){
members.add(u);
} else {
members.remove(u);
}
g.setMembers(members);
groupRepository.save(g);
}
public void deleteGroup(JSONObject jsonData) throws Exception {
if(jsonData.getLong("groupId") == 0){
throw new CustomException("Required fields missing",400);
}
groupRepository.delete(jsonData.getLong("groupId"));
}
}
| [
"[email protected]"
] | |
780960879e101b990464451211ae0ae6363f1dc7 | 41c8a2a004f042fbaf8cbf7a1439a5a9c043cb00 | /Order-8005-Hystrix/src/main/java/com/wanggang/springcloud/Order8005Application.java | cc41c379f420ebcba0a83a160a280d2771286099 | [] | no_license | ayst-wg/SpringCloudDome | 9265d3bb082338f0318225c8da36b5acb7ff0695 | dab077585dca9ed2cf6a700358a9e1351966ebb4 | refs/heads/master | 2022-12-20T04:35:57.225850 | 2020-10-05T15:24:35 | 2020-10-05T15:24:35 | 297,930,201 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,609 | java | package com.wanggang.springcloud;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
/**
* @ClassName : Order8005Application
* @Description : Order8005Application
* @Author : wanggang
* @Date: 2020-09-29 10:29
* @Version 1.0
**/
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class Order8005Application {
public static void main(String[] args) {
SpringApplication.run(Order8005Application.class,args);
}
/**
* 此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
* ServletRegistrationBean因为SpringBoot的默认路径不是 “/hystrix.stream"
* 只要在自己的项目里配置上下的servlet就可以了
*/
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet() ;
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
| [
"[email protected]"
] | |
6d7472e0d378ccc588ea2ccbb376b4aa37349fc6 | 3b2227e88636e15c758b7f47271d400f7ba27a6d | /enumerator/VideoType.java | aacc357664b4f164d669e98304f36670fba8210d | [] | no_license | Vinicius181090382/AP2-rafael | 81d9c7d0ba4423421dcb771d940fc2d200eb10bd | 39fbdee4ab0ea023439b67722f4492d32f40cbaa | refs/heads/master | 2022-10-23T11:43:04.571107 | 2020-06-09T00:39:53 | 2020-06-09T00:39:53 | 270,863,123 | 0 | 0 | null | 2020-06-09T00:34:14 | 2020-06-09T00:21:26 | Java | UTF-8 | Java | false | false | 804 | java | package org.comeia.project.enumerator;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonValue;
@JsonFilter("attributeFilter")
public enum VideoType {
MP4("Tipo Padrão"),
WMV("Recomendado pelo Sistema");
public final String displayName;
private VideoType(String displayName) {
this.displayName = displayName;
}
@JsonCreator
public static VideoType forValue(String value) {
return VideoType.valueOf(value);
}
@JsonValue
public HashMap<String, String> jsonValue() {
HashMap<String, String> map = new HashMap<>();
map.put("name", this.name());
map.put("displayName", this.displayName);
return map;
}
}
| [
"[email protected]"
] | |
16250a9baa81d3e5bace02c2269f2df999963016 | 707a03743ca43dd727519dc07319a71b989f94c9 | /ecsite/src/com/internousdev/ecsite/action/HomeAction.java | 591caa5b33e6d765495fe448f37cb089cedb317e | [] | no_license | workspace-mastubara/test | 5aa7866bf799e2604f6ddddbf6f62fdeb9a9ca87 | 71f7a7a64790dd2e9a72887ee33921394345f870 | refs/heads/master | 2022-04-12T15:58:17.047674 | 2020-03-16T20:49:55 | 2020-03-16T20:49:55 | 221,867,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 967 | java | package com.internousdev.ecsite.action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.internousdev.ecsite.dao.BuyItemDAO;
import com.internousdev.ecsite.dto.BuyItemDTO;
import com.opensymphony.xwork2.ActionSupport;
public class HomeAction extends ActionSupport implements SessionAware{
private Map<String, Object>session;
public String execute(){
String result = "login";
if(session.containsKey("login_user_id")){
BuyItemDAO buyItemDAO = new BuyItemDAO();
BuyItemDTO buyItemDTO = buyItemDAO.getBuyItemInfo();
session.put("id", buyItemDTO.getId());
session.put("buyItem_name", buyItemDTO.getItemName());
session.put("buyItem_price", buyItemDTO.getItemPrice());
result = SUCCESS;
}
return result;
}
public Map<String, Object> getSession(){
return this.session;
}
public void setSession(Map<String, Object> session){
this.session = session;
}
}
| [
"[email protected]"
] | |
b525beb8ab2f623053703c991a511b12b849ca72 | 387638ea842e5ebba44603a725b1e19b3b6e9f57 | /facebook/app/src/main/java/com/example/facebook/adaptor/SlidingImage_Adapter.java | 36502e8ae8807b7216d77b7adcb14956361ef70f | [] | no_license | SimranKSah98/Facebook | e48d9e3b9920f75f8c50d61fb786abf3df8cdf30 | d1b95ec49cac328c012bd9d9da391252ebb6b642 | refs/heads/master | 2020-12-22T08:24:16.555817 | 2020-02-01T11:59:47 | 2020-02-01T11:59:47 | 236,724,982 | 0 | 0 | null | 2020-02-03T04:58:51 | 2020-01-28T11:59:45 | Java | UTF-8 | Java | false | false | 1,723 | java | package com.example.facebook.adaptor;
import android.content.Context;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.viewpager.widget.PagerAdapter;
import com.bumptech.glide.Glide;
import com.example.facebook.R;
import com.example.facebook.pojo.Ads;
import java.util.List;
public class SlidingImage_Adapter extends PagerAdapter {
private String[] urls;
List<Ads> list;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context, List<Ads>movies) {
this.context = context;
this.list=movies;
inflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image1);
Glide.with(imageView.getContext()).load(list.get(position).getImageUrl()).into(imageView);
view.addView(imageLayout, 0);
return imageLayout;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
}
| [
"[email protected]"
] | |
1c2f5fe08db8790abfa7f65b4c34b193069c7773 | 30d6753c4886b8c028d5e3979c8a780f60ff250f | /app/src/main/java/com/qbb/qchina/homepager/model/HomeRecommendModel.java | 4821737f9744f5ca61a974482c5e86150ed7d5fb | [] | no_license | bingbing9527/QChina | f326861b1064229945a90310f8cc2d99ec3eb9c8 | b192fd642bd15acbc4834f1723d887d9dcdadbf7 | refs/heads/master | 2021-01-21T23:05:06.617023 | 2017-06-23T06:35:53 | 2017-06-23T06:35:54 | 95,090,977 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,189 | java | package com.qbb.qchina.homepager.model;
import com.qbb.qchina.core.mvp.MVPModel;
import com.qbb.qchina.homepager.bean.HomeContentListBean;
import com.qbb.qchina.homepager.bean.HomeRecommendBean;
import com.qbb.qchina.http.api.Api;
import com.qbb.qchina.http.net.rx.BaseFunction;
import com.qbb.qchina.http.net.rx.BaseObserver;
import com.qbb.qchina.http.net.BaseResponse;
import com.qbb.qchina.http.net.RetrofitServiceManager;
import java.util.List;
import java.util.Map;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
* 创建日期:2017/6/21 14:51
*
* @author Qian Bing Bing
* 类说明:请求类别后请求第一条分类下的内容
*/
public abstract class HomeRecommendModel extends MVPModel<HomeRecommendBean> {
private ShowHomeContentTypeListener mshowHomeContentTypeListener;
public void requestNet(Map<String, String> map) {
RetrofitServiceManager.getInstance().create(Api.class).getHomeContentType(map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Consumer<BaseResponse<List<HomeContentListBean>>>() {
@Override
public void accept(BaseResponse<List<HomeContentListBean>> listBaseResponse) throws Exception {
if (mshowHomeContentTypeListener != null) {
mshowHomeContentTypeListener.showHomeContentType(listBaseResponse.data);
}
}
})
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
if (mshowHomeContentTypeListener != null) {
mshowHomeContentTypeListener.showHomeContentTypeError(throwable);
}
}
})
.observeOn(Schedulers.io())
.flatMap(new BaseFunction<List<HomeContentListBean>,HomeRecommendBean>() {
@Override
public ObservableSource<BaseResponse<HomeRecommendBean>> doNextRequest(List<HomeContentListBean>listBaseResponse) {
if (listBaseResponse.size() < 0) {
return null;
}
return RetrofitServiceManager.getInstance().create(Api.class).getHomeRecommend(listBaseResponse.get(1).url);
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseObserver<HomeRecommendBean>() {
@Override
public void doSubscribe(Disposable d) {
showSubscribe(d);
}
@Override
public void doSuccess(HomeRecommendBean homeRecommendBean) {
if (homeRecommendBean == null) {
showEmpy();
}else{
showSuccess(homeRecommendBean);
}
}
@Override
public void doFaile(String message) {
showFaile(message);
}
@Override
public void doError(Throwable e) {
showError(e);
}
@Override
public void doComplete() {
showComplete();
}
});
}
public void setShowHomeContentTypeListener(ShowHomeContentTypeListener mshowHomeContentTypeListener) {
this.mshowHomeContentTypeListener = mshowHomeContentTypeListener;
}
public interface ShowHomeContentTypeListener {
void showHomeContentType(List<HomeContentListBean> homeContentTypeList);
void showHomeContentTypeError(Throwable Throwable);
}
}
| [
"[email protected]"
] | |
a8ab0227134468117ef0cb4217062bd9d629f66e | 0b9d35abb5666ace293282f7bcc38265088d5566 | /app/src/main/java/pl/edu/agh/facelivenessdetection/handler/FlashHandler.java | fa0640402619fcd85e3a6dfa173547cf2004b637 | [] | no_license | ra-v97/face-sample-liveness-detector | a95142004d46d385e85dc5b9d43154fc0ddc06f9 | 02639b29ad4f270a4efc8353b511262cc19837de | refs/heads/master | 2023-04-24T14:31:28.703122 | 2021-05-16T17:37:27 | 2021-05-16T17:37:27 | 313,446,929 | 1 | 0 | null | 2021-01-19T14:54:14 | 2020-11-16T22:51:17 | Java | UTF-8 | Java | false | false | 1,080 | java | package pl.edu.agh.facelivenessdetection.handler;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;
import pl.edu.agh.facelivenessdetection.MainActivity;
public class FlashHandler extends Handler {
private final WeakReference<MainActivity> mainActivityReference;
public FlashHandler(MainActivity activity) {
mainActivityReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
final MainActivity activity = mainActivityReference.get();
String status = msg.getData().getString("STATUS");
if (status != null) {
if (status.equals("ON")) {
activity.startFrontFlashEmulator();
} else if (status.equals("OFF")) {
activity.stopFrontFlashEmulator();
}
} else {
String text = msg.getData().getString("BUTTON_TEXT");
int color = Integer.parseInt(msg.getData().getString("BUTTON_COLOR"));
activity.setButton(text, color);
}
}
}
| [
"[email protected]"
] | |
e58b38f3e777759a3182a3bbbfd1d4a103df170c | 2869fc39e2e63d994d5dd8876476e473cb8d3986 | /pet_back/src/main/java/com/lvmama/pet/sweb/shop/shopProduct/NewListProductAction.java | 3acdd9128a3ec0ece7b1d2ca5f8ebe4443ce6a4f | [] | no_license | kavt/feiniu_pet | bec739de7c4e2ee896de50962dbd5fb6f1e28fe9 | 82963e2e87611442d9b338d96e0343f67262f437 | refs/heads/master | 2020-12-25T17:45:16.166052 | 2016-06-13T10:02:42 | 2016-06-13T10:02:42 | 61,026,061 | 0 | 0 | null | 2016-06-13T10:02:01 | 2016-06-13T10:02:01 | null | UTF-8 | Java | false | false | 13,156 | java | package com.lvmama.pet.sweb.shop.shopProduct;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.lvmama.comm.BackBaseAction;
import com.lvmama.comm.pet.po.shop.ShopLog;
import com.lvmama.comm.pet.po.shop.ShopProduct;
import com.lvmama.comm.pet.po.shop.ShopProductCondition;
import com.lvmama.comm.pet.po.shop.ShopProductCoupon;
import com.lvmama.comm.pet.service.shop.ShopCooperationCouponService;
import com.lvmama.comm.pet.service.shop.ShopLogService;
import com.lvmama.comm.pet.service.shop.ShopProductService;
import com.lvmama.comm.pet.vo.Page;
import com.lvmama.comm.utils.DateUtil;
import com.lvmama.comm.utils.pic.UploadCtrl;
import com.lvmama.comm.vo.Constant;
/**
* 产品的相关操作增删改查
* @author YuanXueBo
*
*/
@Results({
@Result(name = "list", location = "/WEB-INF/pages/back/shop/shopProduct/index.jsp"),
@Result(name = "editShopProudct",location="/WEB-INF/pages/back/shop/shopProduct/editShopProudct.jsp" ),
@Result(name = "toViewLog",location="/WEB-INF/pages/back/shop/shopProduct/viewLog.jsp" )
})
public class NewListProductAction extends BackBaseAction {
/**
* 序列值
*/
private static final long serialVersionUID = 498073296144921559L;
/**
* 产品管理的逻辑层
*/
private ShopProductService shopProductService;
/**
* 产品列表
*/
private List<ShopProduct> productList = new ArrayList<ShopProduct>();
/**
* 查询条件
*/
private String productCode;
private String productName;
private String changeType;
private String productType;
private String isValid;
private String query;
/**
* POJO对象
*/
private ShopProduct shopProduct;
/**
* 优惠券标识
*/
private Long couponId;
/**
* 主键
*/
private Long productId;
/**
* 上传的图片列表
*/
private File[] fileData;
/**
* 上传图片的文件名
*/
private String[] fileDataFileName;
/**
* 兑换限制
*/
private Boolean isCheckEmail;
private Boolean isCheckOrder;
private Boolean isCheckNum;
private String num;
/**
* 产品日志列表
*/
private List<ShopLog> logList;
/**
* 日志逻辑层
*/
private ShopLogService shopLogService;
/**
* 合作网站优惠券接口
*/
private ShopCooperationCouponService shopCooperationCouponService;
/**
* 查询
* @return
* @throws Exception
*/
@Action(value="/shop/shopProduct/queryProductList")
public String doQuery() throws Exception{
Long totalRecords=0l;
pagination = Page.page(10, page);
if(!"N".equals(query)){
Map<String,Object> searchConds = new HashMap<String,Object>();
if (StringUtils.isNotBlank(productCode)) {
searchConds.put("productCode", productCode);
}
if (StringUtils.isNotBlank(productName)) {
searchConds.put("productName", productName);
}
if (StringUtils.isNotBlank(changeType)) {
searchConds.put("changeType", changeType);
}
if (StringUtils.isNotBlank(productType)) {
searchConds.put("productType", productType);
}
if (StringUtils.isNotBlank(isValid)) {
searchConds.put("isValid", isValid);
}
totalRecords=shopProductService.count(searchConds);
searchConds.put("_startRow", pagination.getStartRows());
searchConds.put("_endRow", pagination.getEndRows());
productList = shopProductService.query(searchConds);
}
pagination.setTotalResultSize(totalRecords);
pagination.setUrl(getReqUrl());
return "list";
}
/**
* 打开新增修改页面
*
* @return
*/
@Action(value="/shop/shopProduct/addOrModifyShopProduct")
public String addOrModifyShopProduct(){
if (null == productId) {
shopProduct = new ShopProduct();
} else {
shopProduct = shopProductService.queryByPk(productId);
if (Constant.SHOP_PRODUCT_TYPE.COUPON.name().equals(shopProduct.getProductType())) {
this.couponId = ((ShopProductCoupon) shopProduct).getCouponId();
}
//取出限制条件
List<ShopProductCondition> shopProductConditions=shopProduct.getShopProductConditions();
if(shopProductConditions!=null && shopProductConditions.size()>0){
for(ShopProductCondition shopProductCondition:shopProductConditions){
if(Constant.SHOP_PRODUCT_CONDITION.CHECK_EXCHANGE_EMAIL.getCode().equals(shopProductCondition.getConditionX())){
isCheckEmail=true;
}else if(Constant.SHOP_PRODUCT_CONDITION.CHECK_EXCHANGE_ORDER.getCode().equals(shopProductCondition.getConditionX())){
isCheckOrder=true;
}else if(Constant.SHOP_PRODUCT_CONDITION.CHECK_EXCHANGE_NUM.getCode().equals(shopProductCondition.getConditionX())){
isCheckNum=true;
num=shopProductCondition.getConditionY();
}
}
}
Map<String, Object> parametes = new HashMap<String, Object>();
parametes.put("objectId", productId);
parametes.put("objectType", "SHOP_PRODUCT");
}
return "editShopProudct";
}
/**
* 保存或更新
* @return
*/
@Action(value="/shop/shopProduct/savaOrUpdateShopProduct",results=@Result(name="toList",location="/shop/shopProduct/queryProductList.do",type="redirect",params={"productCode","${productCode}","productName","${productName}","changeType","${changeType}","productType","${productType}","isValid","${isValid}"}))
public String savaOrUpdateShopProduct()throws Exception{
//设置结束时间
if(shopProduct.getEndTime()!=null){
shopProduct.setEndTime(DateUtil.getDayEnd(shopProduct.getEndTime()));
}
if (null != fileData && null != fileDataFileName) {
shopProduct.setPictures(savaPic());
}
if (Constant.SHOP_PRODUCT_TYPE.COUPON.name().equals(shopProduct.getProductType())) {
ShopProductCoupon cp = new ShopProductCoupon();
org.springframework.beans.BeanUtils.copyProperties(shopProduct, cp);
cp.setCouponId(this.couponId);
productId=shopProductService.insertOrUpdateShopProduct(cp, getSessionUserName());
} else {
//如何是合作网站优惠券则更新库存
if(Constant.SHOP_PRODUCT_TYPE.COOPERATION_COUPON.name().equals(shopProduct.getProductType())){
Long count=0l;
if(shopProduct.getProductId()!=null){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("productId", shopProduct.getProductId());
parameters.put("used", "N");//未使用
count=shopCooperationCouponService.count(parameters);
}
shopProduct.setStocks(count);
}
productId=shopProductService.insertOrUpdateShopProduct(shopProduct, getSessionUserName());
}
return "toList";
}
/**
* 取反积分商城的上线状态,即原本上线的更新为下线,下线的变为上线
*
*/
@Action(value="/shop/shopProduct/editValidStatus")
public void editShopProductValidStatus() {
Map<String, Object> param = new HashMap<String, Object>();
shopProduct = shopProductService.queryByPk(productId);
if (null == shopProduct) {
param.put("success", false);
param.put("errorMessage", "找不到相应的积分产品");
} else {
if ("Y".equals(shopProduct.getIsValid())) {
shopProduct.setIsValid("N");
} else {
shopProduct.setIsValid("Y");
}
//更新
productId=shopProductService.insertOrUpdateShopProduct(shopProduct, getSessionUserName());
param.put("success", true);
param.put("successMessage", "积分产品上/下线成功");
}
try {
getResponse().getWriter().print(JSONObject.fromObject(param));
} catch (IOException ioe) {
}
}
/**
* 查看日志
* @return
*/
@Action(value="/shop/shopProduct/viewLog")
public String viewLog(){
Map<String, Object> parametes = new HashMap<String, Object>();
parametes.put("objectId", productId);
logList = shopLogService.query(parametes);
return "toViewLog";
}
/**
* 获取图片
* @return 图片的集合
*/
@SuppressWarnings("static-access")
private String savaPic()throws Exception {
String imageUrl="";
if (null != fileData && null != fileDataFileName) {
for (int i = 0; i < fileData.length; i++) {
UploadCtrl uc = new UploadCtrl();
String fileName = "super/"
+ DateUtil.getFormatDate(new Date(), "yyyy/MM/dd")+"/"
+ fileDataFileName[i];
imageUrl += ","+uc.postToRemote(fileData[i], fileName);
}
}
if(imageUrl!=null && !"".equals(imageUrl)){
imageUrl=imageUrl.substring(1);
}
return imageUrl;
}
/**
* 获取分页参数
*
* @return
*/
@SuppressWarnings("unchecked")
private String getReqUrl() {
StringBuffer sb = new StringBuffer();
Enumeration<String> pns = getRequest().getParameterNames();
while (pns.hasMoreElements()) {
String pn = pns.nextElement();
if ("page".equalsIgnoreCase(pn)) {
continue;
}
if ("productName".equalsIgnoreCase(pn)) {
try {
sb.append(pn + "=" + new String(getRequest().getParameter(pn).getBytes("ISO8859-1"),"UTF-8") + "&");
} catch (Exception e) {
}
continue;
}
if ("productCode".equalsIgnoreCase(pn)) {
try {
sb.append(pn + "=" + new String(getRequest().getParameter(pn).getBytes("ISO8859-1"),"UTF-8") + "&");
} catch (Exception e) {
}
continue;
}
sb.append(pn + "=" + getRequest().getParameter(pn) + "&");
}
return "/pet_back/shop/shopProduct/queryProductList.do?" + sb.toString() + "page=";
}
public void setShopProductService(ShopProductService shopProductService) {
this.shopProductService = shopProductService;
}
public List<ShopProduct> getProductList() {
return productList;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
if(getRequest().getMethod().equals("GET")){
try {
this.productCode = new String(productCode.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e);
}
}else{
this.productCode=productCode;
}
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
if(getRequest().getMethod().equals("GET")){
try {
this.productName = new String(productName.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(e);
}
}else{
this.productName=productName;
}
}
public String getChangeType() {
return changeType;
}
public void setChangeType(String changeType) {
this.changeType = changeType;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getIsValid() {
return isValid;
}
public void setIsValid(String isValid) {
this.isValid = isValid;
}
public ShopProduct getShopProduct() {
return shopProduct;
}
public void setShopProduct(ShopProduct shopProduct) {
this.shopProduct = shopProduct;
}
public Long getCouponId() {
return couponId;
}
public void setCouponId(Long couponId) {
this.couponId = couponId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public File[] getFileData() {
return fileData;
}
public void setFileData(File[] fileData) {
this.fileData = fileData;
}
public String[] getFileDataFileName() {
return fileDataFileName;
}
public void setFileDataFileName(String[] fileDataFileName) {
this.fileDataFileName = fileDataFileName;
}
public Boolean getIsCheckEmail() {
return isCheckEmail;
}
public void setIsCheckEmail(Boolean isCheckEmail) {
this.isCheckEmail = isCheckEmail;
}
public Boolean getIsCheckOrder() {
return isCheckOrder;
}
public void setIsCheckOrder(Boolean isCheckOrder) {
this.isCheckOrder = isCheckOrder;
}
public Boolean getIsCheckNum() {
return isCheckNum;
}
public void setIsCheckNum(Boolean isCheckNum) {
this.isCheckNum = isCheckNum;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public void setLogList(List<ShopLog> logList) {
this.logList = logList;
}
public List<ShopLog> getLogList() {
return logList;
}
public void setShopLogService(ShopLogService shopLogService) {
this.shopLogService = shopLogService;
}
public void setShopCooperationCouponService(
ShopCooperationCouponService shopCooperationCouponService) {
this.shopCooperationCouponService = shopCooperationCouponService;
}
}
| [
"[email protected]"
] | |
d7cccbf632a927d09de3f4a7f30a0bb0e3c44b32 | 566754f63c0d665af01bdad8814873468f8be888 | /android/learn/binder/l2/AudioBinder/AudioClient/src/com/hybroad/client/AudioClientActivity.java | cc1f5a2452689048c5353c04bdbbf96fd5c69730 | [
"MIT"
] | permissive | qrsforever/workspace | 7f7b0363649b73e96526745f85a22e70b1c749c9 | 53c7ce7ca7da62c9fbb3d991ae9e4e34d07ece5f | refs/heads/master | 2022-05-04T18:58:41.562544 | 2020-05-25T04:07:00 | 2020-05-25T04:07:00 | 82,469,335 | 2 | 0 | MIT | 2022-04-12T21:54:15 | 2017-02-19T15:36:43 | Jupyter Notebook | UTF-8 | Java | false | false | 1,909 | java | package com.hybroad.client;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.hybroad.aidl.IQAudioService;
public class AudioClientActivity extends Activity implements OnClickListener {
IQAudioService mAudioService = null;
Button btnSet;
Button btnGet;
TextView tvShow = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSet = (Button)this.findViewById(R.id.set_vol);
btnGet = (Button)this.findViewById(R.id.get_vol);
tvShow = (TextView)this.findViewById(R.id.show_value);
btnSet.setOnClickListener(this);
btnGet.setOnClickListener(this);
mAudioService = QAudioManager.getService();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.set_vol:
try {
int value = (int)(Math.random()*100 + 1);
mAudioService.setVolume(value);
if (tvShow != null)
tvShow.setText("set value: " + value);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.get_vol:
try {
int value = mAudioService.getVolume();
if (tvShow != null)
tvShow.setText("get value: " + value);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}
| [
"[email protected]"
] | |
8b6a77dd9691a7f6cfa0410ce228fbe107c2e7be | 0ba1eba86727f7c0c98ac32a08668a28b1923f81 | /L2.2-mech/src/main/java/frontend/AuthServiceImpl.java | a192093a9f564e3a9c54bbba1caf259a53353294 | [] | no_license | vitaly-chibrikov/tp_java_2014_09 | b6b9f8143f63e5e4a48fa4228135c547a47f2522 | f4697208c31944c54643ec367edd15054decf775 | refs/heads/master | 2021-01-20T10:32:51.822919 | 2014-12-24T14:01:12 | 2014-12-24T14:01:12 | 23,702,336 | 5 | 4 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | package frontend;
import base.AuthService;
import java.util.HashMap;
import java.util.Map;
/**
* @author v.chibrikov
*/
public class AuthServiceImpl implements AuthService {
private Map<String, String> userSessions = new HashMap<>();
public String getUserName(String sessionId) {
return userSessions.get(sessionId);
}
public void saveUserName(String sessionId, String name) {
userSessions.put(sessionId, name);
}
}
| [
"[email protected]"
] | |
2e3811eb4efd4329f095ba041d384bcbef48d5ef | 3754166c92a411c6a8777ec4c7c646d70e527ad7 | /src/main/java/org/apache/commons/validator/routines/CurrencyValidator.java | bb94fe094fc7fadc04274b92d11e0287e15288f0 | [
"Apache-2.0"
] | permissive | vincentruan/gwt-commons-validator | 810686e6faec3fe8b3fe7c3a8a62870e19c727f3 | d14f97337a4cd5c1d40117adf71a78f7fa8039b3 | refs/heads/master | 2020-12-26T00:35:26.022400 | 2015-12-09T23:23:32 | 2015-12-09T23:23:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,836 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.text.DecimalFormat;
import java.text.Format;
import com.google.gwt.core.shared.GwtIncompatible;
/**
* <p><b>Currency Validation</b> and Conversion routines (<code>java.math.BigDecimal</code>).</p>
*
* <p>This is one implementation of a currency validator that has the following features:</p>
* <ul>
* <li>It is <i>lenient</i> about the the presence of the <i>currency symbol</i></li>
* <li>It converts the currency to a <code>java.math.BigDecimal</code></li>
* </ul>
*
* <p>However any of the <i>number</i> validators can be used for <i>currency</i> validation.
* For example, if you wanted a <i>currency</i> validator that converts to a
* <code>java.lang.Integer</code> then you can simply instantiate an
* <code>IntegerValidator</code> with the appropriate <i>format type</i>:</p>
*
* <p><code>... = new IntegerValidator(false, IntegerValidator.CURRENCY_FORMAT);</code></p>
*
* <p>Pick the appropriate validator, depending on the type (e.g Float, Double, Integer, Long etc)
* you want the currency converted to. One thing to note - only the CurrencyValidator
* implements <i>lenient</i> behaviour regarding the currency symbol.</p>
*
* @version $Revision: 1713331 $
* @since Validator 1.3.0
*/
@GwtIncompatible("incompatible class")
public class CurrencyValidator extends BigDecimalValidator {
private static final long serialVersionUID = -4201640771171486514L;
private static final CurrencyValidator VALIDATOR = new CurrencyValidator();
/** DecimalFormat's currency symbol */
private static final char CURRENCY_SYMBOL = '\u00A4';
/**
* Return a singleton instance of this validator.
* @return A singleton instance of the CurrencyValidator.
*/
public static BigDecimalValidator getInstance() {
return VALIDATOR;
}
/**
* Construct a <i>strict</i> instance.
*/
public CurrencyValidator() {
this(true, true);
}
/**
* Construct an instance with the specified strict setting.
*
* @param strict <code>true</code> if strict
* <code>Format</code> parsing should be used.
* @param allowFractions <code>true</code> if fractions are
* allowed or <code>false</code> if integers only.
*/
public CurrencyValidator(boolean strict, boolean allowFractions) {
super(strict, CURRENCY_FORMAT, allowFractions);
}
/**
* <p>Parse the value with the specified <code>Format</code>.</p>
*
* <p>This implementation is lenient whether the currency symbol
* is present or not. The default <code>NumberFormat</code>
* behaviour is for the parsing to "fail" if the currency
* symbol is missing. This method re-parses with a format
* without the currency symbol if it fails initially.</p>
*
* @param value The value to be parsed.
* @param formatter The Format to parse the value with.
* @return The parsed value if valid or <code>null</code> if invalid.
*/
protected Object parse(String value, Format formatter) {
// Initial parse of the value
Object parsedValue = super.parse(value, formatter);
if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
return parsedValue;
}
// Re-parse using a pattern without the currency symbol
DecimalFormat decimalFormat = (DecimalFormat)formatter;
String pattern = decimalFormat.toPattern();
if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) {
StringBuilder buffer = new StringBuilder(pattern.length());
for (int i = 0; i < pattern.length(); i++) {
if (pattern.charAt(i) != CURRENCY_SYMBOL) {
buffer.append(pattern.charAt(i));
}
}
decimalFormat.applyPattern(buffer.toString());
parsedValue = super.parse(value, decimalFormat);
}
return parsedValue;
}
}
| [
"[email protected]"
] | |
5e994f21cccfbcaf558f70b65efbc44ddff62dfc | 0921960d8b6e7942948be92abf7f7cd251aa8e44 | /InterviewPrep_1points3acres/Indeed Onsite记录/Git Commit.java | d490f421bd01e90175a0dada436519cdce432214 | [] | no_license | jiamin-he/LC | f9afc0dd98a3eb847a878e13810c1c944f3cc73f | b6950b68201b94cf2bc4a455210a2a60011736ea | refs/heads/master | 2018-10-20T15:42:01.413539 | 2018-10-05T17:42:41 | 2018-10-05T17:42:41 | 112,674,896 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,212 | java | /* =============================================================================
Question Description
=============================================================================*/
Given a git commit (wiki:...), each commit has an id. Find all the commits
that we have.
/* =============================================================================
code
=============================================================================*/
class GitNode{
int id;
List<GitNode> parents;
public GitNode(int id){
this.id = id;
this.parents = new ArrayList<>();
}
}
public class Git_Commit {
//其实是找到了所有的parents,所以假设拿到的是最新的gitNode
//只有这种难度,才能大部分人都秒做吧。
public List<GitNode> findAllCommits(GitNode node){
List<GitNode> res = new ArrayList<>();
Queue<GitNode> queue = new LinkedList<>();
Set<GitNode> visited = new HashSet<>(); //去重
queue.offer(node);
visited.add(node);
while (!queue.isEmpty()){
GitNode cur = queue.poll();
res.add(cur);
for (GitNode par: cur.parents){
if (!visited.contains(par)){
queue.offer(par);
visited.add(par);
}
}
}
return res;
}
}
/* =============================================================================
Follow Up
=============================================================================*/
找到两个commit的最近公共parent commit。而且被要求优化,因为是follow up,所以到时候时间肯定
剩下不多,面试时候要直接出最优解。
/* =============================================================================
Follow Up code
=============================================================================*/
public GitNode findLCA(GitNode node1, GitNode node2){
if (node1 == null || node2 == null) return null;
Queue<GitNode> q1 = new LinkedList<>();
q1.offer(node1);
Queue<GitNode> q2 = new LinkedList<>();
q2.offer(node2);
Set<GitNode> s1 = new HashSet<>();
Set<GitNode> s2 = new HashSet<>();
s1.add(node1);
s2.add(node2);
// int len1 = 1, len2 = 1; //万一是要求最短路径长度呢。
//while里面是&&,因为一旦其中一个终结那也不用搜了。
while (!q1.isEmpty() && !q2.isEmpty()){
//每个BFS都是一层一层的扫
int size1 = q1.size();
while (size1-- > 0){
GitNode cur1 = q1.poll();
for (GitNode par1 : cur1.parents) {
if (s2.contains(par1)){
return par1;
}
if (!s1.contains(par1)){
q1.offer(par1);
s1.add(par1);
}
}
}
int size2 = q2.size();
while (size2-- > 0){
GitNode cur2 = q2.poll();
for (GitNode par2 : cur2.parents) {
if (s1.contains(par2)){
return par2;
}
if (!s2.contains(par2)){
q2.offer(par2);
s2.add(par2);
}
}
}
}
return null;
}
public static void main(String[] args) {
Git_Commit test = new Git_Commit();
/*
*
* 5 <- 4 <- 2
* \ \
* \ <- 3 <- 1
* */
GitNode g1 = new GitNode(1);
GitNode g2 = new GitNode(2);
GitNode g3 = new GitNode(3);
GitNode g4 = new GitNode(4);
GitNode g5 = new GitNode(5);
g1.parents.add(g3);
g1.parents.add(g4);
g2.parents.add(g4);
g3.parents.add(g5);
g4.parents.add(g5);
GitNode res = test.findLCA(g2, g3);
System.out.println(res.id);
}
/* =============================================================================
题目内容:
=============================================================================*/
给出一个Git的commit,找出所有的parents。每个节点都有一个或多个parent。
另外每个commit都是带着ID的。就是没太懂它是输出所有的commit还是要求逐层打印。
第二题就是找到两个commit的公共祖先。
Git的commit是可以分叉的也可以合并,所以这题其实是个图。
想来真是好久没弄github了。
其实就是BFS和双向BFS,注意好对复杂度的分析吧。优化就是双向BFS吧。
好像不太对。
/* =============================================================================
地里面经总结
=============================================================================*/
<A> git commit的题,也是面经题。第一问给一个commit(node),BFS输出所有commits (nodes)。
第二问,两个commits (nodes),找到他们的最近的公共parent,就是先BFS一个,
然后用map记录下其各个parent到这个commit(node)的距离,然后BFS第二个commit(node),碰到在map里的node,
就算一个总距离,然后更新最短距离和的点,最后最短距离和的点就是结果了,写完面试官也表示很满意。
这个注意解释下BFS的复杂度为什么是O(V+E),他会问为什么不是O(V)之类的。
<B> git version。找到全部commits,让实现bfs。然后让找两个commit最早的公共commit,
先bfs搜索其中一个commit的所有ancestor,用hashmap存一下,然后bfs搜索第二个commit的祖先。
这里有两个地方可以提前结束搜索,提出来应该很好。
<C> 是git commit,follow-up是个lowest common anscester,写第一问的时候竟然脑残出了个小bug,
在面试官提示下改了,不知道影响不影响结果阿,
<D> Git commit. 第一题:BFS找出parents。第二题:找共同祖先。
<E> 图的题目,给了一堆节点,每个节点有个parent,先是找所有路径。很简单秒做,
然后follow up是给两个点找最小公共祖先,两遍bfs也很简单做了出来。但是小哥各种问时间复杂度什么的,绕蒙了。。
<F> 第二题是给两个graph中的node,找出这两个node的最近公共祖先,这里最近公共祖先的定义是距离这两个node的path和最小,
还是用bfs做,followup了一下怎么优化。
<G> 第一道是graph的逐层打印,和tree的逐层打印相似。
<H> 一个有向图,但是有环,用BFS进行按层打印, 已知图中两个点,输入参数只有这两个点,返回他俩的最低公共祖先,仍然存在环。
public Node getNode(Node n1, Node n2);
<I> git version,从新到旧扫描,就是有向图的BFS,
follow up是给出图里的两个源节点,找距离这两个原点的最近的公共节点,分别从这两个节点BFS就行。
<J> 现在更新一下input,说的更清楚一点,第一题第一问input是一个parent pointer的node,
def __init__(self,id): self.parent = [] self.id = id.
| [
"[email protected]"
] | |
16b13eae7985957186eb65787274f15133bf58d4 | 5f8eaaf3eb179903a0b1c376d154e3e0fedeecd3 | /security-demo/src/main/java/com.shl.security/controller/UserController.java | 7bd01052a09d8a1e31d35783a3852e70760231b3 | [] | no_license | guaB/shl-platfrom | 08160899c9760293a1bca13018578021856f76fa | ce3bb5cf423602b1b3bfe402348ad9b89328513d | refs/heads/master | 2022-07-14T08:01:01.662729 | 2019-12-23T15:20:59 | 2019-12-23T15:20:59 | 223,301,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 791 | java | package com.shl.security.controller;
import com.shl.security.model.ResultWrapper;
import com.shl.security.model.User;
import com.shl.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @description:
* @author: songhonglei
* @date: 2019-11-20
*/
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/users/{class}")
public ResultWrapper<List<User>> getUsers(@PathVariable("class") Integer clazz) {
return ResultWrapper.success(userService.getUsers(clazz));
}
}
| [
"[email protected]"
] | |
cdca21671253d537f4b7b0d29e1bae00d3ffc4fb | c3dd767ffad9413d3abe443eee93a37f46e06c33 | /src/projects/wsn/nodes/timers/WsnMessageTimer.java | c8b8bc9df807bdd3762eba8e8e821335c0186414 | [
"BSD-3-Clause"
] | permissive | gabrsar/Leach---Sinalgo | f74a09725b61d96d51c058fec2dbdd7c971607cd | c11fde7011f77d1d0e40a30420c090969bb633f7 | refs/heads/master | 2016-09-05T12:51:24.455162 | 2015-10-18T22:15:06 | 2015-10-18T22:15:06 | 29,468,329 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 396 | java | package projects.wsn.nodes.timers;
import projects.wsn.nodes.messages.WsnMsg;
import projects.wsn.nodes.nodeImplementations.SimpleNode;
import sinalgo.nodes.timers.Timer;
public class WsnMessageTimer extends Timer {
private WsnMsg message = null;
public WsnMessageTimer(WsnMsg message) {
this.message = message;
}
public void fire() {
((SimpleNode) node).broadcast(message);
}
}
| [
"[email protected]"
] | |
e6fd6a124382f4da7fb5e4c962394d6e4ed23d07 | 68f95aeb981c33e0a1fccf8ff9aa671bfd71af33 | /app/src/main/java/abhijit/osdm2/ui/login/SetNewPassword.java | e8db2ca0317e0ee7b0eeec4fee96d3965110d929 | [] | no_license | abhijit2322/Android_app_privacypolicy | 0595cbb9f327e9ab21576002fbbadcffe900641c | e24c0136c1eff6a4bdeaf7e23de667ed23c0537a | refs/heads/master | 2021-05-24T11:38:10.765766 | 2020-04-07T04:54:37 | 2020-04-07T04:54:37 | 253,541,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,132 | java | package abhijit.osdm2.ui.login;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import abhijit.osdm2.MainActivity;
import abhijit.osdm2.R;
import abhijit.osdm2.models.Admin;
import abhijit.osdm2.rettrofitsupport.RetrofitClient;
import abhijit.osdm2.service.HerokuService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SetNewPassword extends AppCompatActivity {
Button submit,back;
EditText newpass,repass;
String loginrole="";
String r_name="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_new_password);
Intent intent = getIntent();
r_name = intent.getStringExtra("flatnumber");
String r_number = intent.getStringExtra("passwword");
loginrole=intent.getStringExtra("loginrole");
submit = (Button) findViewById(R.id.submit_password);
back = (Button) findViewById(R.id.back_password);
newpass=(EditText)findViewById(R.id.passeditText1);
repass=(EditText)findViewById(R.id.passeditText2);
String p =newpass.getText().toString();
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
//updateAdmintable(admintable);
// this part is working
if(newpass.getText().toString().contains(repass.getText().toString())) {
Admin admin = new Admin();
admin.setAdminname(r_name);
admin.setAdminpassword(newpass.getText().toString());
updateAdmintable(admin);
}
else
{
new AlertDialog.Builder(SetNewPassword.this)
.setTitle("Wrong password")
.setMessage("Your enter password dose not matchs")
.setCancelable(false)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Whatever...
finish();
}
}).show();
}
Intent opa = new Intent(v.getContext(), MainActivity.class);
if (loginrole != "")
opa.putExtra("loginrule", loginrole);
v.getContext().startActivity(opa);
finish();
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// your handler code here
//updateAdmintable(admintable);
}
});
}
public void updateAdmintable(Admin admin) {
String url = "https://postgres2322.herokuapp.com/admin/";
HerokuService apiService = RetrofitClient.getApiService();
apiService.updateAdminTable(admin).enqueue(new Callback<Admin>() {
@Override
public void onResponse(Call<Admin> call, Response<Admin> response) {
System.out.println("the Response >>>>>. in login activity "+response.body().toString());
System.out.println("Updated Password the Response >>>>> SUCCESS>>>>>>");
// admin_s= response.body();
// response_status=true;
}
@Override
public void onFailure(Call<Admin> call, Throwable t) {
System.out.println("This in Failure >>>>>. in login activity "+t.getMessage());
// response_status=true;
}
});
// return admin_s;
}
}
| [
"[email protected]"
] | |
9cc5a8527f7136af413dfaa04fdc218956b3b926 | ac8881298c9e366d73dc04014b108e80704a30a2 | /deposit/src/main/java/clothingmarket/PayCompleted.java | 281150577873c0e74080fa933a59b600bbdb2c1a | [] | no_license | deste3/skstore2222 | 17bace28c922966029c7b271aca48533b3d9343d | 719eab6cf9239c75e32bda0a69072909b0df6174 | refs/heads/main | 2023-03-06T07:57:55.430041 | 2021-02-17T08:33:44 | 2021-02-17T08:33:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 890 | java |
package clothingmarket;
public class PayCompleted extends AbstractEvent {
private Long id;
private Long OrderId;
private String ProductId;
private String Status;
private Integer Qty;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getOrderId() {
return OrderId;
}
public void setOrderId(Long OrderId) {
this.OrderId = OrderId;
}
public String getProductId() {
return ProductId;
}
public void setProductId(String ProductId) {
this.ProductId = ProductId;
}
public String getStatus() {
return Status;
}
public void setStatus(String Status) {
this.Status = Status;
}
public Integer getQty() {
return Qty;
}
public void setQty(Integer Qty) {
this.Qty = Qty;
}
}
| [
"[email protected]"
] | |
35840baade41a13ff107bc078bee8159c761861e | df74650a0a51874db7d55f9a437b02032f8949b9 | /src/main/java/com/softserve/itacademy/dp_153/security/TokenAuthFilter.java | daeb4e99d98e3e80e162eedba4132fd59e189f60 | [] | no_license | prolumen/SpringSequrityExample | 4c6f7a5edc9efd5d315f5ce6359cd71c8858e244 | 3559dedeb53b8e9b1d4da545338663daf6cd2311 | refs/heads/master | 2020-04-23T03:24:30.647307 | 2019-02-15T14:22:10 | 2019-02-15T14:22:10 | 170,877,712 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,176 | java | package com.softserve.itacademy.dp_153.security;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class TokenAuthFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
String token = request.getParameter("token");
TokenAuthentication tokenAuthentication = new TokenAuthentication(token);
if (token == null) {
tokenAuthentication.setAuthenticated(false);
} else {
SecurityContextHolder.getContext().setAuthentication(tokenAuthentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
| [
"[email protected]"
] | |
a4fe111f0f02c8f2d4457a53ac761f8375c7c08f | c2114242ea033b9eed2d538316ea5ecf8c254d42 | /src/br/com/carlosrafaelgn/fplay/ActivityBrowserRadio.java | 09674509581252b0bfc7d29ff543d7cc2f1e078d | [
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause-Views"
] | permissive | zxiu/FPlayAndroid | 3c0c4555d47c7ce66a35e15997750c5ac5984c5c | d6647976200b2641fa821a17ffb8e62bbeec227c | refs/heads/master | 2021-01-09T09:37:38.068264 | 2014-11-20T10:28:29 | 2014-11-20T10:28:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,464 | java | //
// FPlayAndroid is distributed under the FreeBSD License
//
// Copyright (c) 2013-2014, Carlos Rafael Gimenes das Neves
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
// https://github.com/carlosrafaelgn/FPlayAndroid
//
package br.com.carlosrafaelgn.fplay;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.database.DataSetObserver;
import android.net.http.AndroidHttpClient;
import android.text.InputType;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import br.com.carlosrafaelgn.fplay.activity.MainHandler;
import br.com.carlosrafaelgn.fplay.list.FileSt;
import br.com.carlosrafaelgn.fplay.list.RadioStation;
import br.com.carlosrafaelgn.fplay.list.RadioStationList;
import br.com.carlosrafaelgn.fplay.playback.Player;
import br.com.carlosrafaelgn.fplay.ui.BgButton;
import br.com.carlosrafaelgn.fplay.ui.BgColorStateList;
import br.com.carlosrafaelgn.fplay.ui.BgListView;
import br.com.carlosrafaelgn.fplay.ui.RadioStationView;
import br.com.carlosrafaelgn.fplay.ui.SongAddingMonitor;
import br.com.carlosrafaelgn.fplay.ui.UI;
import br.com.carlosrafaelgn.fplay.ui.drawable.ColorDrawable;
import br.com.carlosrafaelgn.fplay.ui.drawable.TextIconDrawable;
import br.com.carlosrafaelgn.fplay.util.SafeURLSpan;
public final class ActivityBrowserRadio extends ActivityBrowserView implements View.OnClickListener, DialogInterface.OnClickListener, DialogInterface.OnCancelListener, BgListView.OnBgListViewKeyDownObserver, SpinnerAdapter {
private TextView sep2;
private BgListView list;
private RadioStationList radioStationList;
private RelativeLayout panelSecondary, panelLoading;
private RadioButton chkGenre, chkTerm;
private ColorStateList defaultTextColors;
private Spinner btnGenre;
private EditText txtTerm;
private BgButton btnGoBack, btnFavorite, btnSearch, btnGoBackToPlayer, btnAdd, btnPlay;
private boolean loading, isAtFavorites;
@Override
public CharSequence getTitle() {
return getText(R.string.add_radio);
}
private void updateButtons() {
if (!isAtFavorites != (btnFavorite.getVisibility() == View.VISIBLE)) {
if (isAtFavorites) {
btnFavorite.setVisibility(View.GONE);
btnSearch.setVisibility(View.GONE);
btnGoBack.setNextFocusRightId(R.id.list);
UI.setNextFocusForwardId(btnGoBack, R.id.list);
} else {
btnFavorite.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.VISIBLE);
btnGoBack.setNextFocusRightId(R.id.btnFavorite);
UI.setNextFocusForwardId(btnGoBack, R.id.btnFavorite);
}
}
final int s = radioStationList.getSelection();
if ((s >= 0) != (btnAdd.getVisibility() == View.VISIBLE)) {
if (s >= 0) {
btnAdd.setVisibility(View.VISIBLE);
sep2.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.VISIBLE);
btnGoBack.setNextFocusLeftId(R.id.btnPlay);
btnGoBackToPlayer.setNextFocusRightId(R.id.btnAdd);
UI.setNextFocusForwardId(btnGoBackToPlayer, R.id.btnAdd);
} else {
btnAdd.setVisibility(View.GONE);
sep2.setVisibility(View.GONE);
btnPlay.setVisibility(View.GONE);
btnGoBack.setNextFocusLeftId(R.id.btnGoBackToPlayer);
btnGoBackToPlayer.setNextFocusRightId(R.id.btnGoBack);
UI.setNextFocusForwardId(btnGoBackToPlayer, R.id.btnGoBack);
}
}
}
private void addPlaySelectedItem(final boolean play) {
if (radioStationList.getSelection() < 0)
return;
try {
final RadioStation radioStation = radioStationList.getItemT(radioStationList.getSelection());
if (radioStation.m3uUri == null || radioStation.m3uUri.length() < 0) {
UI.toast(getApplication(), R.string.error_file_not_found);
return;
}
Player.songs.addingStarted();
SongAddingMonitor.start(getHostActivity());
(new Thread("Checked Radio Station Adder Thread") {
@Override
public void run() {
AndroidHttpClient client = null;
HttpResponse response = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) {
Player.songs.addingEnded();
return;
}
client = AndroidHttpClient.newInstance("Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36 Debian");
response = client.execute(new HttpGet(radioStation.m3uUri));
final StatusLine statusLine = response.getStatusLine();
final int s = statusLine.getStatusCode();
if (s == HttpStatus.SC_OK) {
is = response.getEntity().getContent();
isr = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(isr, 1024);
ArrayList<String> lines = new ArrayList<String>(8);
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && line.charAt(0) != '#' &&
(line.regionMatches(true, 0, "http://", 0, 7) ||
line.regionMatches(true, 0, "https://", 0, 8)))
lines.add(line);
}
if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) {
Player.songs.addingEnded();
return;
}
if (lines.size() == 0) {
Player.songs.addingEnded();
MainHandler.toast(R.string.error_gen);
} else {
//instead of just using the first available address, let's use
//one from the middle ;)
Player.songs.addFiles(new FileSt[] { new FileSt(lines.get(lines.size() >> 1), radioStation.title, null, 0) }, null, 1, play, false, true);
}
} else {
Player.songs.addingEnded();
MainHandler.toast((s >= 400 && s < 500) ? R.string.error_file_not_found : R.string.error_gen);
}
} catch (Throwable ex) {
Player.songs.addingEnded();
MainHandler.toast(ex);
} finally {
try {
if (client != null)
client.close();
} catch (Throwable ex) {
}
try {
if (is != null)
is.close();
} catch (Throwable ex) {
}
try {
if (isr != null)
isr.close();
} catch (Throwable ex) {
}
try {
if (br != null)
br.close();
} catch (Throwable ex) {
}
br = null;
isr = null;
is = null;
client = null;
response = null;
System.gc();
}
}
}).start();
} catch (Throwable ex) {
Player.songs.addingEnded();
UI.toast(getApplication(), ex.getMessage());
}
}
@Override
public void loadingProcessChanged(boolean started) {
if (UI.browserActivity != this)
return;
loading = started;
if (panelLoading != null)
panelLoading.setVisibility(started ? View.VISIBLE : View.GONE);
if (list != null)
list.setCustomEmptyText(getText(started ? R.string.loading : (isAtFavorites ? R.string.no_favorites : R.string.no_stations)));
if (!started)
updateButtons();
}
@Override
public View createView() {
return new RadioStationView(Player.getService());
}
@Override
public void processItemButtonClick(int position, boolean add) {
final RadioStation station = radioStationList.getItemT(position);
if (station.isFavorite)
radioStationList.addFavoriteStation(station);
else
radioStationList.removeFavoriteStation(station);
}
@Override
public void processItemClick(int position) {
//UI.doubleClickMode is ignored for radio stations!
if (radioStationList.getSelection() == position) {
addPlaySelectedItem(true);
} else {
radioStationList.setSelection(position, true);
updateButtons();
}
}
@Override
public void processItemLongClick(int position) {
if (radioStationList.getSelection() != position) {
radioStationList.setSelection(position, true);
updateButtons();
}
}
private static int getValidGenre(int genre) {
return ((genre < 0) ? 0 : ((genre >= RadioStationList.GENRES.length) ? (RadioStationList.GENRES.length - 1) : genre));
}
private static String getGenreString(int genre) {
return RadioStationList.GENRES[getValidGenre(genre)];
}
private void doSearch() {
if (Player.radioSearchTerm != null && Player.radioSearchTerm.length() < 1)
Player.radioSearchTerm = null;
if (Player.lastRadioSearchWasByGenre || Player.radioSearchTerm == null)
radioStationList.fetchIcecast(getApplication(), getGenreString(Player.radioLastGenre), null);
else
radioStationList.fetchIcecast(getApplication(), null, Player.radioSearchTerm);
updateButtons();
}
@Override
public boolean onBgListViewKeyDown(BgListView bgListView, int keyCode, KeyEvent event) {
int p;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (btnSearch.getVisibility() == View.VISIBLE)
btnSearch.requestFocus();
else
btnGoBack.requestFocus();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
btnGoBackToPlayer.requestFocus();
return true;
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_SPACE:
p = radioStationList.getSelection();
if (p >= 0)
processItemClick(p);
return true;
}
return false;
}
@Override
public void onClick(View view) {
if (view == btnGoBack) {
if (isAtFavorites) {
isAtFavorites = false;
doSearch();
} else {
finish(0, view, true);
}
} else if (view == btnFavorite) {
isAtFavorites = true;
radioStationList.cancel();
radioStationList.fetchFavorites(getApplication());
updateButtons();
} else if (view == btnSearch) {
final Context ctx = getHostActivity();
final LinearLayout l = (LinearLayout)UI.createDialogView(ctx, null);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
chkGenre = new RadioButton(ctx);
chkGenre.setText(R.string.genre);
chkGenre.setChecked(Player.lastRadioSearchWasByGenre);
chkGenre.setOnClickListener(this);
chkGenre.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp);
chkGenre.setLayoutParams(p);
p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.topMargin = UI._DLGsppad;
btnGenre = new Spinner(ctx);
btnGenre.setContentDescription(ctx.getText(R.string.genre));
btnGenre.setLayoutParams(p);
p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.topMargin = UI._DLGsppad << 1;
chkTerm = new RadioButton(ctx);
chkTerm.setText(R.string.search_term);
chkTerm.setChecked(!Player.lastRadioSearchWasByGenre);
chkTerm.setOnClickListener(this);
chkTerm.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp);
chkTerm.setLayoutParams(p);
p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.topMargin = UI._DLGsppad;
txtTerm = new EditText(ctx);
txtTerm.setContentDescription(ctx.getText(R.string.search_term));
txtTerm.setText(Player.radioSearchTerm == null ? "" : Player.radioSearchTerm);
txtTerm.setOnClickListener(this);
txtTerm.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp);
txtTerm.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
txtTerm.setSingleLine();
txtTerm.setLayoutParams(p);
p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.topMargin = UI._DLGsppad;
p.bottomMargin = UI._DLGsppad;
final TextView lbl = new TextView(ctx);
lbl.setAutoLinkMask(0);
lbl.setLinksClickable(true);
//http://developer.android.com/design/style/color.html
lbl.setLinkTextColor(new BgColorStateList(UI.isAndroidThemeLight() ? 0xff0099cc : 0xff33b5e5));
lbl.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._14sp);
lbl.setGravity(Gravity.CENTER_HORIZONTAL);
lbl.setText(SafeURLSpan.parseSafeHtml(getText(R.string.by_dir_xiph_org)));
lbl.setMovementMethod(LinkMovementMethod.getInstance());
lbl.setLayoutParams(p);
l.addView(chkGenre);
l.addView(btnGenre);
l.addView(chkTerm);
l.addView(txtTerm);
l.addView(lbl);
btnGenre.setAdapter(this);
btnGenre.setSelection(getValidGenre(Player.radioLastGenre));
defaultTextColors = txtTerm.getTextColors();
UI.prepareDialogAndShow((new AlertDialog.Builder(ctx))
.setTitle(getText(R.string.search))
.setView(l)
.setPositiveButton(R.string.search, this)
.setNegativeButton(R.string.cancel, this)
.setOnCancelListener(this)
.create());
} else if (view == btnGoBackToPlayer) {
finish(-1, view, false);
} else if (view == btnAdd) {
addPlaySelectedItem(false);
} else if (view == btnPlay) {
addPlaySelectedItem(true);
} else if (view == chkGenre || view == btnGenre) {
chkGenre.setChecked(true);
chkTerm.setChecked(false);
} else if (view == chkTerm || view == txtTerm) {
chkGenre.setChecked(false);
chkTerm.setChecked(true);
} else if (view == list) {
if (!isAtFavorites && !loading && (radioStationList == null || radioStationList.getCount() == 0))
onClick(btnFavorite);
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == AlertDialog.BUTTON_POSITIVE) {
Player.lastRadioSearchWasByGenre = chkGenre.isChecked();
Player.radioLastGenre = btnGenre.getSelectedItemPosition();
Player.radioSearchTerm = txtTerm.getText().toString().trim();
doSearch();
}
chkGenre = null;
btnGenre = null;
chkTerm = null;
txtTerm = null;
defaultTextColors = null;
}
@Override
public void onCancel(DialogInterface dialog) {
onClick(dialog, AlertDialog.BUTTON_NEGATIVE);
}
@Override
protected boolean onBackPressed() {
if (UI.backKeyAlwaysReturnsToPlayerWhenBrowsing) {
finish(-1, null, false);
return true;
}
if (!isAtFavorites)
return false;
onClick(btnGoBack);
return true;
}
@Override
protected void onCreate() {
UI.browserActivity = this;
radioStationList = new RadioStationList(getText(R.string.tags).toString(), "-", getText(R.string.no_description).toString(), getText(R.string.no_tags).toString());
}
@SuppressWarnings("deprecation")
@Override
protected void onCreateLayout(boolean firstCreation) {
setContentView(R.layout.activity_browser_radio);
UI.smallTextAndColor((TextView)findViewById(R.id.lblLoading));
list = (BgListView)findViewById(R.id.list);
list.setOnKeyDownObserver(this);
list.setScrollBarType((UI.browserScrollBarType == BgListView.SCROLLBAR_INDEXED) ? BgListView.SCROLLBAR_LARGE : UI.browserScrollBarType);
list.setCustomEmptyText(getText(R.string.loading));
list.setEmptyListOnClickListener(this);
radioStationList.setObserver(list);
panelLoading = (RelativeLayout)findViewById(R.id.panelLoading);
btnGoBack = (BgButton)findViewById(R.id.btnGoBack);
btnGoBack.setOnClickListener(this);
btnGoBack.setIcon(UI.ICON_GOBACK);
btnFavorite = (BgButton)findViewById(R.id.btnFavorite);
btnFavorite.setOnClickListener(this);
btnFavorite.setIcon(UI.ICON_FAVORITE_ON);
btnSearch = (BgButton)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
btnSearch.setIcon(UI.ICON_SEARCH);
panelSecondary = (RelativeLayout)findViewById(R.id.panelSecondary);
btnGoBackToPlayer = (BgButton)findViewById(R.id.btnGoBackToPlayer);
btnGoBackToPlayer.setTextColor(UI.colorState_text_reactive);
btnGoBackToPlayer.setOnClickListener(this);
btnGoBackToPlayer.setCompoundDrawables(new TextIconDrawable(UI.ICON_RIGHT, UI.color_text, UI.defaultControlContentsSize), null, null, null);
btnGoBackToPlayer.setDefaultHeight();
btnAdd = (BgButton)findViewById(R.id.btnAdd);
btnAdd.setTextColor(UI.colorState_text_reactive);
btnAdd.setOnClickListener(this);
btnAdd.setIcon(UI.ICON_ADD, true, false);
sep2 = (TextView)findViewById(R.id.sep2);
RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(UI.strokeSize, UI.defaultControlContentsSize);
rp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
rp.addRule(RelativeLayout.LEFT_OF, R.id.btnPlay);
rp.leftMargin = UI._8dp;
rp.rightMargin = UI._8dp;
sep2.setLayoutParams(rp);
sep2.setBackgroundDrawable(new ColorDrawable(UI.color_highlight));
btnPlay = (BgButton)findViewById(R.id.btnPlay);
btnPlay.setTextColor(UI.colorState_text_reactive);
btnPlay.setOnClickListener(this);
btnPlay.setIcon(UI.ICON_PLAY, true, false);
UI.prepareControlContainer(findViewById(R.id.panelControls), false, true);
UI.prepareControlContainer(panelSecondary, true, false);
if (UI.isLargeScreen)
UI.prepareViewPaddingForLargeScreen(list, 0, 0);
UI.prepareEdgeEffectColor(getApplication());
updateButtons();
doSearch();
}
@Override
protected void onPause() {
SongAddingMonitor.stop();
radioStationList.saveFavorites(getApplication());
radioStationList.setObserver(null);
}
@Override
protected void onResume() {
UI.browserActivity = this;
radioStationList.setObserver(list);
SongAddingMonitor.start(getHostActivity());
if (loading != radioStationList.isLoading())
loadingProcessChanged(radioStationList.isLoading());
}
@Override
protected void onOrientationChanged() {
if (UI.isLargeScreen && list != null)
UI.prepareViewPaddingForLargeScreen(list, 0, 0);
}
@Override
protected void onCleanupLayout() {
list = null;
panelLoading = null;
panelSecondary = null;
btnGoBack = null;
btnFavorite = null;
btnSearch = null;
btnGoBackToPlayer = null;
btnAdd = null;
sep2 = null;
btnPlay = null;
}
@Override
protected void onDestroy() {
UI.browserActivity = null;
radioStationList.cancel();
radioStationList = null;
}
@Override
public int getCount() {
return RadioStationList.GENRES.length;
}
@Override
public Object getItem(int position) {
return getGenreString(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView txt = (TextView)convertView;
if (txt == null) {
txt = new TextView(getApplication());
txt.setPadding(UI._8dp, UI._4dp, UI._8dp, UI._4dp);
txt.setTypeface(UI.defaultTypeface);
txt.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp);
txt.setTextColor(defaultTextColors);
}
txt.setText(getGenreString(position));
return txt;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView txt = (TextView)convertView;
if (txt == null) {
txt = new TextView(getApplication());
txt.setPadding(UI._DLGdppad, UI._DLGsppad, UI._DLGdppad, UI._DLGsppad);
txt.setTypeface(UI.defaultTypeface);
txt.setTextSize(TypedValue.COMPLEX_UNIT_PX, UI._DLGsp);
txt.setTextColor(defaultTextColors);
}
txt.setText(getGenreString(position));
return txt;
}
}
| [
"[email protected]"
] | |
af90ca9b9135c9b34521a8b856e1524fc8c3cf24 | b8fdef4d32eda0e7942af45b9dee127dc2a35446 | /src/main/Launcher.java | 9cc47133c10ecd2759c34341a148d23637921f61 | [] | no_license | cnam-java/exo-cours | 3ad3fff0e3c3e0a5d256c2a1e3551de90127d8a7 | bcb8bb198f5c4d72a847e7841fe74f07b367ab92 | refs/heads/master | 2021-01-22T05:23:57.352089 | 2017-02-11T14:05:35 | 2017-02-11T14:05:35 | 81,656,322 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,785 | java | package main;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import DAO.DAO;
import DAO.DAOAccount;
import DAO.DAOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class Launcher {
private static final Logger LOG = Logger.getLogger(Launcher.class.getName());
private Launcher() {
// Useless
}
public static void main(String[] args) {
PropertyConfigurator.configure("log4J.properties");
LOG.info("Chargement de l'objet...");
DAO<Account> accountDAO = new DAOAccount();
try{
Account a = accountDAO.find(1);
LOG.info(a.getFirst_name());
} catch (DAOException e){
LOG.error("Error during loading DAO user", e);
}
// System.out.println("Bienvenue ! Vous désirez :\n1-Enregistrer un compte.\n2-Afficher les comptes.\nEntrez votre choix (1 ou 2) :\n");
// Scanner sc = new Scanner(System.in);
// int choix = sc.nextInt();
// try{
// operationsAccount(choix);
// } catch (AccountException e){
// e.printStackTrace();
// }
//final Account a1 = new Account (0,"Gaël","CHENEVIER",2042.5);
//try {
//insertAccount(a1);
// System.out.println(chargerCompte(1));
// System.out.println(chargerCompte(2));
//} catch (AccountException e) {
// e.printStackTrace();
//}
}
//
// private static void operationsAccount(int choix) throws AccountException{
// Scanner sc = new Scanner(System.in);
// String nom;
// String prenom;
// double montant;
// switch(choix){
// case 1 : System.out.println("Vous avez choisi : Enregistrer un compte.\n");
// System.out.println("Veuillez entrer un nom :\n");
// nom = sc.nextLine();
// System.out.println("Veuillez entrer un prénom:\n");
// prenom = sc.nextLine();
// System.out.println("Veuillez entrer le montant sur le compte:\n");
// montant = sc.nextDouble();
// //Account a = new Account(0,prenom,nom,montant);
// //insertAccount(a);
// break;
// case 2: System.out.println("Vous avez choisi : Afficher les comptes.\n");
// System.out.println("Les comptes sont les suivants :\n");
// chargerCompte();
// break;
// default: System.out.println("Vous deviez rentrer 1 ou 2...\n");
//
// }
// }
//
// private static void insertAccount(Account a) throws AccountException {
// final String sql = "INSERT INTO `accounts` VALUES (NULL,?,?,?)";
// Connection c = null;
// PreparedStatement st = null;
// ResultSet r = null;
// try {
// c = DriverManager.getConnection("jdbc:mysql://localhost/cnam?useSSL=false", "root", "root");
// st = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// st.setString(1, a.first_name);
// st.setString(2, a.last_name);
// st.setDouble(3, a.amount);
// st.executeUpdate();
//
// r = st.getGeneratedKeys();
//
// if (r.next()) {
// a.id = r.getInt(1);
// }else{
// throw new AccountException("Error during account insertion.");
// }
// } catch (SQLException e) {
// throw new AccountException("Error during account insertion.", e);
// } finally {
// try {
// if (r != null)
// r.close();
// if (st != null)
// st.close();
// if (c != null)
// c.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// }
//
// //private static Account chargerCompte(int id) throws AccountException {
// private static void chargerCompte() throws AccountException {
// Connection c = null;
// PreparedStatement st = null;
// ResultSet r = null;
// ArrayList<Account> accounts = new ArrayList<Account>();
// try {
// Class.forName("com.mysql.jdbc.Driver");
// c = DriverManager.getConnection("jdbc:mysql://localhost/cnam?useSSL=false", "root", "root");
// st = c.prepareStatement("SELECT * FROM `accounts`");
// //st = c.prepareStatement("SELECT * FROM `accounts` WHERE `id` = ? ");
// //st.setInt(1, id);
// r = st.executeQuery();
// //if (r.next()) {
// // return new Account(r.getInt(1), r.getString(2), r.getString(3), r.getDouble(4));
// //}
// while (r.next()) {
// System.out.println((r.getInt(1)+", "+ r.getString(2)+", "+ r.getString(3)+", "+ r.getDouble(4)+"."));
// }
// throw new AccountException("Erreur aucun utilisateur.");
// } catch (ClassNotFoundException e) {
// throw new AccountException("Erreur sql connector not found.", e);
// } catch (SQLException e) {
// throw new AccountException("Erreur in sql request.", e);
// } finally {
// try {
// if (r != null)
// r.close();
// if (st != null)
// st.close();
// if (c != null)
// c.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// }
}
| [
"[email protected]"
] | |
9a078033fa23e7d62350b390370a950dcafba8ae | 0535e036f25791cead2f5521188d60e0f389b2e2 | /src/java/Pojo/TbPais.java | 9e41d73344fd26f839f6c8c4f53b895fdc5b6e51 | [] | no_license | lujoca12/JSFIntelcomex | 65da0fafde9e56fd75e50c1feaa0c3dd04f63fe9 | 37b62e479aac508f93135692f2cb66c6b2b83201 | refs/heads/master | 2020-04-12T09:39:48.167212 | 2016-09-24T01:40:16 | 2016-09-24T01:40:16 | 64,801,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,325 | java | package Pojo;
// Generated 17-sep-2016 17:20:14 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
/**
* TbPais generated by hbm2java
*/
public class TbPais implements java.io.Serializable {
private String id;
private String nombre;
private String nacionalidad;
private Set tbProvincias = new HashSet(0);
public TbPais() {
}
public TbPais(String id) {
this.id = id;
}
public TbPais(String id, String nombre, String nacionalidad, Set tbProvincias) {
this.id = id;
this.nombre = nombre;
this.nacionalidad = nacionalidad;
this.tbProvincias = tbProvincias;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getNacionalidad() {
return this.nacionalidad;
}
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
public Set getTbProvincias() {
return this.tbProvincias;
}
public void setTbProvincias(Set tbProvincias) {
this.tbProvincias = tbProvincias;
}
}
| [
"server@DESKTOP-5G3JRHM"
] | server@DESKTOP-5G3JRHM |
bce7d5020dc1998dc391bb8c656f3aed3a5214d2 | 433bc378f26b5b5403815cbdb03fcf592cc30f60 | /app/src/main/java/com/example/vloboda/dynamicentityeditor/dal/DataContextImpl.java | b5c467d397099e88a9ea591ba2d4d153e21a41bd | [
"MIT"
] | permissive | viloboda/DynamicEditor | 00318e38ee4348f0d6609b40a342840bd5157f03 | d3798176bb45dbd03bda57e141732bdd719549ee | refs/heads/master | 2020-03-14T23:13:01.391384 | 2018-05-29T05:33:04 | 2018-05-29T05:33:04 | 131,839,947 | 2 | 3 | null | null | null | null | UTF-8 | Java | false | false | 11,495 | java | package com.example.vloboda.dynamicentityeditor.dal;
import android.content.ContentValues;
import android.database.Cursor;
import org.sqlite.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.util.Log;
import com.example.dal.DataContentValues;
import com.example.dal.DataContext;
import com.example.dal.DataContextException;
import com.example.dal.DataCursor;
import java.io.IOException;
import java.util.HashMap;
public class DataContextImpl implements DataContext {
private final SQLiteDatabase sqliteDatabase;
private boolean hasOpendTransaction;
public DataContextImpl(SQLiteDatabase sqliteDatabase) {
this.sqliteDatabase = sqliteDatabase;
}
@Override
public DataCursor executeCursor(String sql, Object... arguments) {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
return new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs));
}
@Override
public boolean exists(String sql, Object... arguments) throws DataContextException {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
try (DataCursor cursor = new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs))) {
return cursor.moveToNext();
} catch (IOException e) {
throw new DataContextException(e);
}
}
@Override
public Integer executeInt(String sql, Object... arguments) throws DataContextException {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
try (DataCursor cursor = new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs))) {
if (cursor.moveToNext()) {
return cursor.getInt(0);
}
return null;
} catch (IOException e) {
throw new DataContextException(e);
}
}
@Override
public Long executeLong(String sql, Object... arguments) throws DataContextException {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
try (DataCursor cursor = new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs))) {
if (cursor.moveToNext()) {
return cursor.getLong(0);
}
return null;
} catch (IOException e) {
throw new DataContextException(e);
}
}
@Override
public String executeString(String sql, Object... arguments) throws DataContextException {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
try (DataCursor cursor = new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs))) {
if (cursor.moveToNext()) {
return cursor.getString(0);
}
return null;
} catch (IOException e) {
throw new DataContextException(e);
}
}
@Override
public byte[] executeBlob(String sql, Object... arguments) throws DataContextException {
String[] stringArgs = convertToStringsArguments(arguments);
logQuery(sql, stringArgs);
try (DataCursor cursor = new DataCursorImpl(sqliteDatabase.rawQuery(sql, stringArgs))) {
if (cursor.moveToNext()) {
return cursor.getBlob(0);
}
return null;
} catch (IOException e) {
throw new DataContextException(e);
}
}
private String[] convertToStringsArguments(Object[] arguments) {
String[] stringArgs = arguments == null ? null : new String[arguments.length];
if(stringArgs != null) {
for(int i = 0; i < stringArgs.length; i++) {
stringArgs[i] = String.valueOf(arguments[i]);
}
}
return stringArgs;
}
@Override
public void executeSql(String sql) {
logQuery(sql, null);
sqliteDatabase.execSQL(sql);
}
@Override
public void executeSql(String sql, String[] parameters) {
logQuery(sql, parameters);
sqliteDatabase.execSQL(sql, parameters);
}
@Override
public int delete(String table, String whereClause, Object... whereArgs) {
String[] stringArgs = convertToStringsArguments(whereArgs);
logQuery("DELETE FROM " + table + " " + whereClause, stringArgs);
return sqliteDatabase.delete(table, whereClause, stringArgs);
}
@Override
public int update(String table, DataContentValues values, String whereClause, Object... whereArgs) {
String[] stringArgs = convertToStringsArguments(whereArgs);
ContentValues parameters = getContentValues(values);
logQuery("UPDATE " + table, stringArgs);
return sqliteDatabase.update(table, parameters, whereClause, stringArgs);
}
@Nullable
private ContentValues getContentValues(DataContentValues values) {
ContentValues parameters = null;
if(values != null) {
parameters = new ContentValues(values.size());
HashMap<String, Object> innerValues = values.getValues();
for (String key: innerValues.keySet()) {
Object innerValue = innerValues.get(key);
if(innerValue == null) {
parameters.putNull(key);
continue;
}
if(innerValue.getClass() == String.class) {
parameters.put(key, (String)innerValue);
continue;
}
if(innerValue.getClass() == Integer.class) {
parameters.put(key, (Integer)innerValue);
continue;
}
if(innerValue.getClass() == Byte.class) {
parameters.put(key, (Byte)innerValue);
continue;
}
if(innerValue.getClass() == Short.class) {
parameters.put(key, (Short)innerValue);
continue;
}
if(innerValue.getClass() == Long.class) {
parameters.put(key, (Long)innerValue);
continue;
}
if(innerValue.getClass() == Float.class) {
parameters.put(key, (Float)innerValue);
continue;
}
if(innerValue.getClass() == Double.class) {
parameters.put(key, (Double)innerValue);
continue;
}
if(innerValue.getClass() == Boolean.class) {
parameters.put(key, (Boolean)innerValue);
continue;
}
if(innerValue.getClass() == byte[].class) {
parameters.put(key, (byte[])innerValue);
continue;
}
if(innerValue.getClass() == byte[].class) {
parameters.put(key, (byte[])innerValue);
continue;
}
throw new IllegalArgumentException("Unknown parameter type " + key);
}
}
return parameters;
}
public long insert(String table, DataContentValues values) {
logQuery("INSERT INTO " + table, null);
return sqliteDatabase.insertOrThrow(table, null, getContentValues(values));
}
public long insertOrReplace(String table, DataContentValues values)
{
return sqliteDatabase.insertWithOnConflict(table, null, getContentValues(values), 5);
}
public void beginTransaction() {
hasOpendTransaction = true;
sqliteDatabase.beginTransaction();
}
public void commitTransaction() {
hasOpendTransaction = false;
sqliteDatabase.setTransactionSuccessful();
sqliteDatabase.endTransaction();
}
@Override
public void close() throws IOException {
if(hasOpendTransaction) {
sqliteDatabase.endTransaction();
}
sqliteDatabase.close();
}
private void logQuery(String sql, String[] stringArgs) {
Log.d("DC", "query = " + sql);
if (stringArgs != null) {
Log.d("DC", "params:");
int index = 0;
for(String arg: stringArgs) {
Log.d("DC", " p" + index++ + " = " + arg);
}
}
}
class DataCursorImpl implements DataCursor {
private Cursor sqliteCursor;
public DataCursorImpl(Cursor sqliteCursor) {
this.sqliteCursor = sqliteCursor;
}
@Override
public int getCount() {
return sqliteCursor.getCount();
}
@Override
public boolean moveToNext() {
return sqliteCursor.moveToNext();
}
@Override
public long getLong(String columnName) {
return sqliteCursor.getLong(sqliteCursor.getColumnIndex(columnName));
}
@Override
public Long getNulLong(String columnName) {
int index = sqliteCursor.getColumnIndex(columnName);
return sqliteCursor.isNull(index) ? null : sqliteCursor.getLong(index);
}
@Override
public String getString(String columnName) {
int index = sqliteCursor.getColumnIndex(columnName);
return sqliteCursor.isNull(index) ? null : sqliteCursor.getString(index);
}
@Override
public byte[] getBlob(String columnName) {
return sqliteCursor.getBlob(sqliteCursor.getColumnIndex(columnName));
}
@Override
public int getInt(String columnName) {
return sqliteCursor.getInt(sqliteCursor.getColumnIndex(columnName));
}
@Override
public int getInt(int columnIndex) {
return sqliteCursor.getInt(columnIndex);
}
@Override
public boolean isNull(String columnName) {
int columnIndex = sqliteCursor.getColumnIndex(columnName);
if (columnIndex < 0) {
return true;
}
return sqliteCursor.isNull(sqliteCursor.getColumnIndex(columnName));
}
@Override
public boolean getBoolean(String columnName) {
return getInt(columnName) == 1;
}
@Override
public Boolean getNulBoolean(String columnName) {
int index = sqliteCursor.getColumnIndex(columnName);
return sqliteCursor.isNull(index) ? null : getInt(columnName) == 1;
}
@Override
public Long getLong(int columnIndex) {
return sqliteCursor.getLong(columnIndex);
}
@Override
public String getString(int columnIndex) {
return sqliteCursor.getString(columnIndex);
}
@Override
public byte[] getBlob(int columnIndex) {
return sqliteCursor.getBlob(columnIndex);
}
@Override
public void close() throws IOException {
sqliteCursor.close();
}
}
}
| [
"[email protected]"
] | |
612ae6697953fdf349c97b920dbc5aa217c43cd6 | db15f75c284fe3df64bf4eb7b9e40bc516c9fed1 | /src/main/java/com/TrackApp/TrackApp/services/reposervices/UserRepoServicesImp.java | 3d5f2f6e24a83fea73f3cd451cfa382c12b9cefd | [] | no_license | OanaChis/TrackApp | 6de106f3c8d0f77cbe2cba6205dc95625de8018c | 8de73f7dadcb861b7d718a54386d601c7c191746 | refs/heads/master | 2021-01-21T21:06:16.918419 | 2017-06-19T17:41:52 | 2017-06-19T17:41:52 | 94,775,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,789 | java | package com.TrackApp.TrackApp.services.reposervices;
import com.TrackApp.TrackApp.domain.User;
import com.TrackApp.TrackApp.repository.UserRepository;
import com.TrackApp.TrackApp.services.UserService;
import com.TrackApp.TrackApp.services.security.EncryptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* Created by oana_ on 6/14/2017.
*/
@Service
@Transactional(readOnly = true)
public class UserRepoServicesImp implements UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
private EncryptionService encryptionService;
// some error here , no encryptionService bean was found , to check
@Autowired
public void setEncryptionService(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
@Override
public List<?> listAll() {
List<User> users = new ArrayList<>();
userRepository.findAll().forEach(users :: add);
return users;
}
@Override
public User getById(Integer id) {
return userRepository.findOne(id);
}
@Override
@Transactional(readOnly = false)
public User saveOrUpdate(User domainObject) {
return userRepository.save(domainObject);
}
@Override
@Transactional(readOnly = false)
public void delete(Integer id) {
userRepository.delete(id);
}
@Override
public User findByUsername(String userName) {
return userRepository.findByUserName(userName);
}
}
| [
"[[email protected]]"
] | |
13cb3818f9cda29563b2ccef5716573014d52a45 | b17df9aec923a994daee44732aa2e33a6ad2143c | /126_mcxiaoke_android-next/src1/com/mcxiaoke/next/io/StringBuilderWriter.java | 5c65e0aa0a0594069035e524105242994974d572 | [] | no_license | duytient31/ExtractionFiles | f1a4a7f48c1acd5987267d22c47ba60dc55e8fc4 | 18eafb494421b0f225b4b6017e9e17da65843517 | refs/heads/master | 2022-01-17T10:37:31.544309 | 2019-06-10T05:16:37 | 2019-06-10T05:16:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,512 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mcxiaoke.next.io;
import java.io.Serializable;
import java.io.Writer;
/**
* {@link java.io.Writer} implementation that outputs to a {@link StringBuilder}.
* <p/>
* <strong>NOTE:</strong> This implementation, as an alternative to
* <code>java.io.StringWriter</code>, provides an <i>un-synchronized</i>
* (i.e. for use in a single thread) implementation for better performance.
* For safe usage with multiple {@link Thread}s then
* <code>java.io.StringWriter</code> should be used.
*
* @version $Id: StringBuilderWriter.java 1304052 2012-03-22 20:55:29Z ggregory $
* @since 2.0
*/
public class StringBuilderWriter extends Writer implements Serializable {
private final StringBuilder builder;
/**
* Construct a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
/**
* Construct a new {@link StringBuilder} instance with the specified capacity.
*
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilderWriter(int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Construct a new instance with the specified {@link StringBuilder}.
*
* @param builder The String builder
*/
public StringBuilderWriter(StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
}
/**
* Write a portion of a character array to the {@link StringBuilder}.
*
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(char[] value, int offset, int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Write a String to the {@link StringBuilder}.
*
* @param value The value to write
*/
@Override
public void write(String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Append a single character to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(char value) {
builder.append(value);
return this;
}
/**
* Append a character sequence to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(CharSequence value) {
builder.append(value);
return this;
}
/**
* Append a portion of a character sequence to the {@link StringBuilder}.
*
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(CharSequence value, int start, int end) {
builder.append(value, start, end);
return this;
}
/**
* Return the underlying builder.
*
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
*
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| [
"[email protected]"
] | |
50bd741b5834a1093ba207dde56661f0bb0f725d | 7a08de1ea53d7e9a43f59b983cdd0fba252489a4 | /src/io/github/podshot/WorldWar/events/guns/BombDiffuser.java | 834fc9ae99a45ddd12367131b3915c0f2bc69f69 | [] | no_license | Podshot/World-War | 4589b4f2c6c89fb44f5b79e87b77254b9f263a18 | b55d5c1714a5cfaf8d0b11c58d75f5ef416a404a | refs/heads/master | 2021-01-17T14:09:39.401476 | 2017-03-11T13:02:45 | 2017-03-11T13:02:45 | 18,708,955 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,418 | java | package io.github.podshot.WorldWar.events.guns;
import io.github.podshot.WorldWar.api.interfaces.IGun;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.stirante.MoreProjectiles.event.ItemProjectileHitEvent;
public class BombDiffuser implements Listener, IGun {
@Override
@EventHandler
public void onFireGun(PlayerInteractEvent e) {
// TODO Auto-generated method stub
}
@Override
@EventHandler
public void onGunReload(PlayerInteractEvent e) {
// TODO Auto-generated method stub
}
public int getMagSize() {
// TODO Auto-generated method stub
return 0;
}
public ItemStack getGun() {
ItemStack bombD = new ItemStack(Material.MONSTER_EGG);
bombD.setDurability((short) 91);
ItemMeta imBombD = bombD.getItemMeta();
imBombD.setDisplayName("Bomb Diffuser");
bombD.setItemMeta(imBombD);
return bombD;
}
@Override
@EventHandler
public void onBulletHit(ItemProjectileHitEvent e) {
// TODO Auto-generated method stub
}
@Override
public double getPlayerDamage() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double getAnimalDamage() {
// TODO Auto-generated method stub
return 0;
}
}
| [
"[email protected]"
] | |
766e62fa275c2c3e886d5234f643472e4a71b263 | c42c6ebc72bbd139f7061bd7b4319f247910085b | /src/main/java/pmsocspsc/modules/pms/entity/PmItemAttachEntity.java | bc138c2a08de5feea93a33455bb7c7f5d65200e5 | [] | no_license | eat-chicken-tonight/pmsocspscs | c39552e5f177fb5371477ec6cd696a35e99d764a | 1386ff1e27698a4a289b12aaa655787954360e77 | refs/heads/master | 2022-11-14T03:54:05.501844 | 2020-05-28T02:08:59 | 2020-05-28T02:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 759 | java | package pmsocspsc.modules.pms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 附件表
*
* @author mikey
* @email [email protected]
* @date 2019-11-27 17:34:06
*/
@Data
@TableName("pm_item_attach")
public class PmItemAttachEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Integer attachId;
/**
* 项目立项id
*/
private Integer itemInfoId;
/**
* 附件名称
*/
private String attachName;
/**
* 附件存放路径
*/
private String attachPath;
/**
* 是否删除
*/
private Integer attachIsDel;
}
| [
"[email protected]"
] | |
1e3aa5ba5dc9056f4e334805509e7c397f815890 | 5ebf0d4cc6e74e54d0eb6943797844e6adc3e69e | /Study/src/arraysTwoDimension/TwoDimensionArray.java | a7f91a177d1c25a39426b13bde9636775e1a8cb5 | [] | no_license | anjukumaris/java-_Program | 8da491f369b411ff5b85dc3ba8216bce6ea45fb7 | f7b42b109f4c4a0cf68e411086565184b1ed6874 | refs/heads/main | 2023-02-25T16:22:04.877226 | 2021-01-30T06:33:27 | 2021-01-30T06:33:27 | 334,338,684 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 841 | java | package arraysTwoDimension;
import java.util.Scanner;
public class TwoDimensionArray {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter row Limit::");
int row=sc.nextInt();
System.out.println("Enter Colomn Limit::");
int col=sc.nextInt();
int[][] num=new int[row][col];
System.out.println("Enter Elements:::");
for(int i=0;i<row;i++) {
for (int j = 0; j < col; j++) {
num[i][j] = sc.nextInt();
}
}
System.out.println(" Elements in Two Dimensional array are::");
for(int i=0;i<num.length;i++){
for(int j=0;j<num[i].length;j++){
System.out.print(num[i][j]+"\t");
}
System.out.println();
}
}
}
| [
"[email protected]"
] | |
2c2bfbb8e3f2e4b463c45682ea1ae97c821c9c61 | 96004f675b8a3764973ae56cb0a381e5fa520429 | /aeaihr/src/com/agileai/hr/module/system/handler/SecurityUserQueryHandler.java | 8f6553df3e920e3e5734019a9c7bfefe511d2ea1 | [
"BSD-3-Clause"
] | permissive | ice-stream/attendance | a19cb688d81c1a915c7bbdd4a404fb679717a7dc | 384abef0f1e5d14c98482511dc158b2ecc20ac21 | refs/heads/master | 2020-04-22T11:08:59.573922 | 2019-02-12T14:13:48 | 2019-02-12T14:13:48 | 170,329,542 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,180 | java | package com.agileai.hr.module.system.handler;
import java.util.List;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.PickFillModelHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.hr.module.system.service.SecurityUserGRManage;
import com.agileai.util.StringUtil;
public class SecurityUserQueryHandler
extends PickFillModelHandler {
public SecurityUserQueryHandler() {
super();
this.serviceId = buildServiceId(SecurityUserGRManage.class);
}
protected void processPageAttributes(DataParam param) {
initMappingItem("USER_STATE",
FormSelectFactory.create("SYS_VALID_TYPE")
.getContent());
}
protected void initParameters(DataParam param) {
}
public ViewRenderer prepareDisplay(DataParam param){
SecurityUserGRManage securityUserGRManage=(SecurityUserGRManage) this.lookupService(this.getServiceId());
mergeParam(param);
initParameters(param);
this.setAttributes(param);
List<DataRow> rsList = securityUserGRManage.queryPickFillRecords(param);
this.setRsList(rsList);
processPageAttributes(param);
return new LocalRenderer(getPage());
}
public ViewRenderer doSaveUserAction(DataParam param){
SecurityUserGRManage securityUserGRManage=(SecurityUserGRManage) this.lookupService(this.getServiceId());
String rspText = SUCCESS;
String userIds = param.get("USER_ID");
String rgId = param.getString("RG_ID");
if(StringUtil.isNullOrEmpty(userIds)){
userIds = param.get("targetValue");
}
String[] userIdArray = userIds.split(",");
for(int i=0;i<userIdArray.length;i++){
String userId = userIdArray[i];
String urgId = KeyGenerator.instance().genKey();
securityUserGRManage.createURGMContentRecord(urgId,userId,rgId);
}
return new AjaxRenderer(rspText);
}
}
| [
"[email protected]"
] | |
8d8d252397f58b1c70c0837cea41c58d063a309c | 87b41b97df9e3a2d1258c6a84265db6f20eb5683 | /src/model/entities/Seller.java | a6f6f89655b4a527de3eb64cfc5a490660a7169c | [] | no_license | Danielcosmo/workshop-javaFx-JDBC | 9abdeadd338f4ceaa3de484d5ec1dd382b956513 | ec66732ebc7dcf37fd29111ea8db36abc8215151 | refs/heads/master | 2022-09-19T15:30:28.797528 | 2020-06-05T00:29:33 | 2020-06-05T00:29:33 | 266,898,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,980 | java | package model.entities;
import java.util.Date;
public class Seller {
private Integer id;
private String name;
private String email;
private Date birthDate;
private Double baseSalary;
private Department department;
public Seller() {
}
public Seller(Integer id, String name, String email, Date birthDate, Double baseSalary, Department department) {
this.id = id;
this.name = name;
this.email = email;
this.birthDate = birthDate;
this.baseSalary = baseSalary;
this.department = department;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Double getBaseSalary() {
return baseSalary;
}
public void setBaseSalary(Double baseSalary) {
this.baseSalary = baseSalary;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Seller other = (Seller) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return "Seller [id=" + id + ", name=" + name + ", email=" + email + ", birthDate=" + birthDate + ", baseSalary="
+ baseSalary + ", department=" + department + "]";
}
}
| [
"[email protected]"
] | |
e0adc628165d69ae5ed088c4080bc37b74909e2a | 816be070347a11ae472b3a369001de39500e8a37 | /JavaLib/src/com/lostcode/javalib/entities/components/physical/Body.java | e15946251fcbc0b031eb6c048f989a45a19fb7fe | [
"MIT"
] | permissive | LostCodeStudios/JavaLib | 553d8638ebc0454bddb3a3c1b31466f5be0af868 | 71c98f1b6ef44eceafe3ea0314ca5d40d0c60ab6 | refs/heads/master | 2021-01-01T18:41:46.698154 | 2015-01-25T17:38:50 | 2015-01-25T17:38:50 | 11,191,973 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,585 | java | package com.lostcode.javalib.entities.components.physical;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Shape;
import com.lostcode.javalib.entities.Entity;
import com.lostcode.javalib.entities.EntityWorld;
import com.lostcode.javalib.entities.components.ComponentManager;
import com.lostcode.javalib.utils.LogManager;
/**
* Component wrapper for a Box2D {@link com.badlogic.gdx.physics.box2d.Body
* Body}.
*
* @author Natman64
*
*/
public class Body implements Transform, Velocity {
// region Fields/Initialization
private EntityWorld entityWorld;
private com.badlogic.gdx.physics.box2d.Body body;
/**
* Constructs a Body without using BodyDef or FixtureDef.
*
* @param world
* The EntityWorld.
* @param e
* The entity that contains this Body.
* @param bodyType
* The type of this Body.
* @param shape
* The body's shape.
* @param position
* The body's initial position.
*/
public Body(EntityWorld world, Entity e, BodyType bodyType, Shape shape,
Vector2 position) {
entityWorld = world;
BodyDef bodyDef = new BodyDef();
bodyDef.type = bodyType;
bodyDef.position.set(position);
body = world.getBox2DWorld().createBody(bodyDef);
body.setUserData(e);
LogManager.debug("Physics", "Body Created");
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
body.createFixture(fixtureDef);
}
/**
* Creates a Body without any attached fixtures.
*
* @param world
* The EntityWorld.
* @param e
* The entity that contains this Body.
* @param bodyType
* The type of this Body.
* @param position
* The body's initial position.
*/
public Body(EntityWorld world, Entity e, BodyType bodyType, Vector2 position) {
entityWorld = world;
BodyDef bodyDef = new BodyDef();
bodyDef.type = bodyType;
bodyDef.position.set(position);
body = world.getBox2DWorld().createBody(bodyDef);
body.setUserData(e);
LogManager.debug("Physics", "Body Created");
}
/**
* Constructs a body component.
*
* @param world
* The EntityWorld.
* @param e
* The entity that will own this body.
* @param bodyDef
* The definition of the body to be created.
* @param fixtureDef
* The definition of the body's fixture.
*/
public Body(EntityWorld world, Entity e, BodyDef bodyDef,
FixtureDef fixtureDef) {
this(world, e, bodyDef);
body.createFixture(fixtureDef);
}
/**
* Constructs a body component without a fixture definition.
*
* @param world
* The EntityWorld.
* @param e
* The entity that will own this body.
* @param bodyDef
* The definition of the body to be created.
*/
public Body(EntityWorld world, Entity e, BodyDef bd) {
entityWorld = world;
body = world.getBox2DWorld().createBody(bd);
body.setUserData(e);
LogManager.debug("Physics", "Body Created");
}
// endregion
// region Accessors
/**
* @return The Box2D body.
*/
public com.badlogic.gdx.physics.box2d.Body getBody() {
return body;
}
// endregion
// region Transform Implementation
@Override
public Vector2 getPosition() {
Vector2 pos = body.getPosition().cpy();
return pos;
}
@Override
public void setPosition(Vector2 position) {
body.setTransform(position, body.getAngle());
}
@Override
public float getRotation() {
return body.getAngle();
}
@Override
public void setRotation(float rotation) {
body.setTransform(getPosition(), rotation);
}
@Override
public Vector2 getOrigin() {
return body.getWorldCenter();
}
// endregion
// region Velocity Implementation
@Override
public Vector2 getLinearVelocity() {
return body.getLinearVelocity();
}
@Override
public void setLinearVelocity(Vector2 linearVelocity) {
body.setLinearVelocity(linearVelocity);
}
@Override
public float getAngularVelocity() {
return body.getAngularVelocity();
}
@Override
public void setAngularVelocity(float angularVelocity) {
body.setAngularVelocity(angularVelocity);
}
// endregion
// region Events
@Override
public void onAdd(ComponentManager container) {
}
@Override
public void onRemove(ComponentManager container) {
entityWorld.getBox2DWorld().destroyBody(body);
LogManager.debug("Physics", "Body Destroyed");
}
// endregion
}
| [
"[email protected]"
] | |
62fd40fd393e05aad868ae89087641726b49387e | 0fee5c6daea8501b7b0fe7fa21aa1fe61ecffdb0 | /app/src/main/java/com/nadhif/onbeng/DataRecycler.java | 5993bb136f0b693bdaabd8f81e45141baca1ad86 | [
"MIT"
] | permissive | utqinadhif/onbeng-android | 6c749a12981cec1d81efeedd63a802fa736776c0 | f18db4f822dd1b8a735f6ec6a0f5324cb0ec4f2e | refs/heads/master | 2021-01-21T13:04:08.207421 | 2019-03-16T01:58:42 | 2019-03-16T01:58:42 | 49,701,508 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,649 | java | package com.nadhif.onbeng;
/**
* Created by nadhif on 21/01/2016.
*/
public class DataRecycler {
String id, logoBengkel, nameBengkel, dateOrder, statusOrder, statusOrderText, damageOrder, detail_bengkel, detail_order;
public DataRecycler(String id, String logoBengkel, String nameBengkel, String dateOrder, String statusOrder, String statusOrderText, String damageOrder, String detail_bengkel, String detail_order) {
this.id = id;
this.logoBengkel = logoBengkel;
this.nameBengkel = nameBengkel;
this.dateOrder = dateOrder;
this.statusOrder = statusOrder;
this.statusOrderText = statusOrderText;
this.damageOrder = damageOrder;
this.detail_bengkel = detail_bengkel;
this.detail_order = detail_order;
}
public String getId() {
return id;
}
public String getLogoBengkel() {
return logoBengkel;
}
public String getNameBengkel() {
return nameBengkel;
}
public String getDateOrder() {
return dateOrder;
}
public String getStatusOrder() {
return statusOrder;
}
public String getStatusOrderText() {
return statusOrderText;
}
public String getDamageOrder() {
return damageOrder;
}
public String getDetail_bengkel() {
return detail_bengkel;
}
public String getDetail_order() {
return detail_order;
}
public void setStatusOrderText(String statusOrderText) {
this.statusOrderText = statusOrderText;
}
public void setStatusOrder(String statusOrder) {
this.statusOrder = statusOrder;
}
}
| [
"[email protected]"
] | |
c2292315954ff1ef93b764f91557a1b559d0c098 | c04ce0ab66baa15d4d8fbaf220e9b5c042ab800c | /libpretixsync/src/test/java/eu/pretix/libpretixsync/db/BaseDatabaseTest.java | f454a4346b6d152c21de2252bbbdb7d1416d0734 | [
"Apache-2.0"
] | permissive | MaxMagazin/libpretixsync | 34a6189a153ed43853b50ee57017650b3bd2342d | 7b2f01b6b4b541cd894a0bc44856ae9c7afbce25 | refs/heads/dev | 2020-03-27T05:30:20.959022 | 2018-10-02T17:35:54 | 2018-10-16T15:32:07 | 146,026,325 | 0 | 0 | Apache-2.0 | 2018-10-08T12:39:53 | 2018-08-24T18:27:19 | Java | UTF-8 | Java | false | false | 2,438 | java | package eu.pretix.libpretixsync.db;
import eu.pretix.libpretixsync.db.*;
import io.requery.Persistable;
import io.requery.cache.EntityCacheBuilder;
import io.requery.sql.Configuration;
import io.requery.sql.ConfigurationBuilder;
import io.requery.sql.EntityDataStore;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Formatter;
import java.util.Random;
public abstract class BaseDatabaseTest {
@Rule
public TestName name = new TestName();
protected EntityDataStore<Persistable> dataStore;
private Connection connection;
private static String byteArray2Hex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
return formatter.toString();
}
@Before
public void setUpDataStore() throws SQLException, NoSuchAlgorithmException {
byte[] randomBytes = new byte[32]; // length is bounded by 7
new Random().nextBytes(randomBytes);
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getMethodName().getBytes());
md.update(randomBytes);
String dbname = byteArray2Hex(md.digest());
SQLiteDataSource dataSource = new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:file:" + dbname + "?mode=memory&cache=shared");
SQLiteConfig config = new SQLiteConfig();
config.setDateClass("TEXT");
dataSource.setConfig(config);
dataSource.setEnforceForeignKeys(true);
Migrations.migrate(dataSource, true);
connection = dataSource.getConnection();
Configuration configuration = new ConfigurationBuilder(dataSource, Models.DEFAULT)
.useDefaultLogging()
.setEntityCache(new EntityCacheBuilder(Models.DEFAULT)
.useReferenceCache(false)
.useSerializableCache(false)
.build())
.build();
dataStore = new EntityDataStore<>(configuration);
}
@After
public void tearDownDataStore() throws Exception {
dataStore.close();
connection.close();
}
} | [
"[email protected]"
] | |
049d8f9dcd87184b3f02c0aef375dbd0a0b1fb7a | 949136b52184bf681a6e72307f83c9a326456e46 | /src/aln/Supply/Supply.java | 260572386e36717e187de932ee1daac3344d8f49 | [] | no_license | amalfushi/ALNInventory | b3efb6de71acf2e9043d5cc7005fdb240c6caf55 | 5ac680e167d21fcec51f2596d4407e2025a2c581 | refs/heads/master | 2021-05-09T16:50:45.304545 | 2018-03-19T04:56:29 | 2018-03-19T04:56:29 | 119,123,958 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,887 | java | package aln.Supply;
public abstract class Supply {
private String category;
private String subCategory;
private String name;
private int currentCount;
private int desiredCount;
private double price;
private String vendor;
private double threshold;
public Supply(String category, String subCategory, String name, int currentCount, int desiredCount, double price, String vendor) {
this.category = category;
this.subCategory = subCategory;
this.name = name;
this.currentCount = currentCount;
this.desiredCount = desiredCount;
this.price = price;
this.threshold = .34;
}
public Supply(){
this("", "", "", 0, 0, 0.00, "");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setSubCategory(String subCategory) {
this.subCategory = subCategory;
}
public String getSubCategory() {
return subCategory;
}
public int getCurrentCount() {
return currentCount;
}
public void setCurrentCount(Double d) {
int i = d.intValue();
this.currentCount = i;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getDesiredCount() {
return desiredCount;
}
public void setDesiredCount(Double d) {
int i = d.intValue();
this.desiredCount = i;
}
public void adjustCurrentCount(int adjustment) {
currentCount = adjustment;
}
public String getVendor() {
return vendor;
}
public String getOtherDetail(){
return null;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public double getThreshold() {
return threshold;
}
public void setThreshold(double threshold) {
this.threshold = threshold;
}
public Boolean checkForReorder(){
//if(currentCount==0 ){
// return true;
//}
return ((double)currentCount/(double)desiredCount <= threshold);
}
public int orderQuantity(){
return desiredCount-currentCount;
}
@Override
public String toString() {
String helper = "";
helper += category;
helper += " " + name;
helper += " " + currentCount;
helper += " " + desiredCount;
helper += " " + price;
helper += " " + vendor;
return helper;
}
@Override
public int hashCode() {
return (13*category.hashCode()) + name.hashCode();
}
}
| [
"[email protected]"
] | |
d2120f9d50921babdebcf95a7513eb3c26a589c2 | fbba623ad761b7a3d07c3658a63a1dc38a86ccb9 | /app/src/main/java/com/zjw/apps3pluspro/sql/dbmanager/SportModleInfoUtils.java | 2c95478428d4d9a39749527b967541542f654c3c | [] | no_license | sengeiou/App3plusPro | ac7eea04857321138e7b2608a700787f93cf6506 | becaee95b8c5c38c5a524b41e6bc159e75eb9fc5 | refs/heads/main | 2023-01-30T03:13:41.672933 | 2020-12-14T02:30:29 | 2020-12-14T02:30:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,098 | java | package com.zjw.apps3pluspro.sql.dbmanager;
import android.content.Context;
import com.zjw.apps3pluspro.application.BaseApplication;
import com.zjw.apps3pluspro.module.home.sport.DeviceSportManager;
import com.zjw.apps3pluspro.sql.entity.SportModleInfo;
import com.zjw.apps3pluspro.sql.gen.SportModleInfoDao;
import com.zjw.apps3pluspro.utils.NewTimeUtils;
import com.zjw.apps3pluspro.utils.log.MyLog;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
import java.util.TimeZone;
/**
* Created by zjw on 2017/12/6.
*/
public class SportModleInfoUtils {
private final String TAG = SportModleInfoUtils.class.getSimpleName();
private DaoManager mManager;
public SportModleInfoUtils(Context context) {
mManager = DaoManager.getInstance();
mManager.init(context);
}
/**
* 插入一条数据
*
* @param info
* @return boolean
*/
public boolean MyUpdateData(SportModleInfo info) {
boolean flag = false;
List<SportModleInfo> info_list = queryToTime(info.getUser_id(), info.getTime());
if (info_list.size() >= 1) {
MyLog.i(TAG, "有,更新数据");
if (info_list.get(0).getMap_data() != null
&& info_list.get(0).getMap_data().equals(info.getMap_data())
&& info_list.get(0).getSport_duration() != null
&& info_list.get(0).getSport_duration().equals(info.getSport_duration())) {
MyLog.i(TAG, "有,数据重复不处理");
} else {
// MyLog.i(TAG, "有,数据不重复,更新数据");
// info.set_id(info_list.get(0).get_id());
// flag = updateData(info);
}
} else {
MyLog.i(TAG, "没有,插入一条");
flag = insertData(info);
}
return flag;
}
/**
* 插入多条数据,在子线程操作
*
* @param infoList
* @return
*/
public boolean insertInfoList(final List<SportModleInfo> infoList) {
boolean flag = false;
try {
mManager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (SportModleInfo info : infoList) {
MyLog.i(TAG, "插入多条数据 = " + info.toString());
MyUpdateData(info);
}
DeviceSportManager.Companion.getInstance().uploadMoreSportData();
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 查询所有最新的一条数据
*
* @param user_id
* @return
*/
public SportModleInfo MyQueryToAll(String user_id) {
List<SportModleInfo> info_list = queryAllTime(user_id);
if (info_list.size() >= 1) {
MyLog.i(TAG, "有,更新数据");
SportModleInfo info = info_list.get(0);
return info;
} else {
return null;
}
}
/**
* 删除所有记录
*
* @return
*/
public boolean deleteAllData() {
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().deleteAll(SportModleInfo.class);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 删除一条记录
*
* @param info
* @return
*/
public boolean deleteDataToDate(SportModleInfo info) {
boolean flag = false;
try {
//按照id删除
mManager.getDaoSession().delete(info);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
//==================基础方法==============
/**
* 插入数据
*
* @param info
* @return
*/
public boolean insertData(SportModleInfo info) {
if (info.getDataSourceType() == 0) {
info.setRecordPointIdTime(NewTimeUtils.getLongTime(info.getTime(), NewTimeUtils.TIME_YYYY_MM_DD_HHMMSS));
int timeZone = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (3600 * 1000);
info.setRecordPointTimeZone(timeZone);
}
info.setDeviceMac(BaseApplication.getBleDeviceTools().get_ble_mac());
info.setWarehousing_time(String.valueOf(System.currentTimeMillis()));
MyLog.i(TAG, "插入数据 = info = " + info.toString());
boolean flag = mManager.getDaoSession().getSportModleInfoDao().insert(info) == -1 ? false : true;
return flag;
}
/**
* 更新一条数据(系统ID)
*
* @param info
* @return
*/
public boolean updateData(SportModleInfo info) {
info.setWarehousing_time(String.valueOf(System.currentTimeMillis()));
boolean flag = false;
try {
mManager.getDaoSession().update(info);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 根据用户ID 和 时间点
*
* @param user_id
* @return
*/
public List<SportModleInfo> queryToTime(String user_id, String time) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(user_id), SportModleInfoDao.Properties.Time.eq(time)).list();
}
/**
* 根据用户ID 查询所有的-降序
*
* @param user_id
* @return
*/
public List<SportModleInfo> queryAllTime(String user_id) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(user_id))
//降序
.orderDesc(SportModleInfoDao.Properties.RecordPointIdTime)
.list();
}
public List<SportModleInfo> queryByRecordPointDataId(String user_id, String recordPointDataId) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(user_id), SportModleInfoDao.Properties.RecordPointDataId.eq(recordPointDataId)).list();
}
public List<SportModleInfo> queryByRecordPointIdTime(String user_id, long recordPointIdTime) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(user_id), SportModleInfoDao.Properties.RecordPointIdTime.eq(recordPointIdTime)).list();
}
public List<SportModleInfo> queryByTime(long startTime, long endTime) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(BaseApplication.getUserId()))
.where(SportModleInfoDao.Properties.RecordPointIdTime.ge(startTime))
.where(SportModleInfoDao.Properties.RecordPointIdTime.le(endTime))
.where(SportModleInfoDao.Properties.RecordPointSportType.notEq("9"))
.where(SportModleInfoDao.Properties.RecordPointSportType.notEq("10"))
.orderDesc(SportModleInfoDao.Properties.RecordPointIdTime)
.list();
}
public List<SportModleInfo> queryNoUploadData(int dataSourceType) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.User_id.eq(BaseApplication.getUserId()))
.where(SportModleInfoDao.Properties.DataSourceType.eq(dataSourceType))
.whereOr(SportModleInfoDao.Properties.Sync_state.isNull(), SportModleInfoDao.Properties.Sync_state.eq("0"))
.orderDesc(SportModleInfoDao.Properties.RecordPointIdTime)
.limit(10)
.list();
}
public void updateNoUploadData(List<SportModleInfo> sportModleInfoList) {
for (SportModleInfo sportModleInfo : sportModleInfoList) {
sportModleInfo.setSync_state("1");
}
mManager.getDaoSession().getSportModleInfoDao().updateInTx(sportModleInfoList);
}
public List<SportModleInfo> queryByServerId(long serverId) {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder.where(SportModleInfoDao.Properties.ServiceId.eq(serverId))
.limit(1)
.orderDesc(SportModleInfoDao.Properties.RecordPointIdTime)
.list();
}
public List<SportModleInfo> queryOldSportData() {
QueryBuilder<SportModleInfo> queryBuilder = mManager.getDaoSession().queryBuilder(SportModleInfo.class);
return queryBuilder
.where(SportModleInfoDao.Properties.User_id.eq(BaseApplication.getUserId()))
.where(SportModleInfoDao.Properties.DataSourceType.eq(""))
.where(SportModleInfoDao.Properties.RecordPointIdTime.eq(""))
.list();
}
public void updateOldSportData(List<SportModleInfo> sportModleInfoList) {
for (SportModleInfo sportModleInfo : sportModleInfoList) {
if (sportModleInfo.getDataSourceType() == 0) {
sportModleInfo.setRecordPointIdTime(NewTimeUtils.getLongTime(sportModleInfo.getTime(), NewTimeUtils.TIME_YYYY_MM_DD_HHMMSS));
int timeZone = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / (3600 * 1000);
sportModleInfo.setRecordPointTimeZone(timeZone);
}
}
mManager.getDaoSession().getSportModleInfoDao().updateInTx(sportModleInfoList);
}
} | [
"[email protected]"
] | |
5bc939bc39c2b95289d2a4df887c48e5ec5b47ca | 4505e3e21447c803e5f23d2d40abf182e6d0ed78 | /analysis/src/main/java/edu/stanford/nlp/sequences/SequenceGibbsSampler.java | 47ae11b25445ae1c081d319204b0341cb1f667da | [] | no_license | photon3710/es_test | 76e182267412db5d0ef20cbb97a4d34f1079b98b | 83f9f67906ef9c9ce60c5532f804f7d947dfa56b | refs/heads/master | 2021-01-21T16:44:07.347016 | 2015-07-30T09:15:14 | 2015-07-30T09:15:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,096 | java | package edu.stanford.nlp.sequences;
import edu.stanford.nlp.ie.EmpiricalNERPriorBIO;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.math.ArrayMath;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.util.concurrent.MulticoreWrapper;
import edu.stanford.nlp.util.concurrent.ThreadsafeProcessor;
import java.io.PrintStream;
import java.util.*;
//debug
// TODO: change so that it uses the scoresOf() method properly
/**
* A Gibbs sampler for sequence models. Given a sequence model implementing the SequenceModel
* interface, this class is capable of
* sampling sequences from the distribution over sequences that it defines. It can also use
* this sampling procedure to find the best sequence.
*
* @author grenager
*/
public class SequenceGibbsSampler implements BestSequenceFinder {
// a random number generator
private static Random random = new Random(2147483647L);
public static int verbose = 0;
private List document;
private int numSamples;
private int sampleInterval;
private int speedUpThreshold = -1;
private SequenceListener listener;
private static final int RANDOM_SAMPLING = 0;
private static final int SEQUENTIAL_SAMPLING = 1;
private static final int CHROMATIC_SAMPLING = 2;
//debug
EmpiricalNERPriorBIO priorEn, priorCh = null;
public boolean returnLastFoundSequence = false;
private int samplingStyle;
// determines how many parallel threads to run in chromatic sampling
private int chromaticSize;
private List<List<Integer>> partition;
public static int[] copy(int[] a) {
int[] result = new int[a.length];
System.arraycopy(a, 0, result, 0, a.length);
return result;
}
public static int[] getRandomSequence(SequenceModel model) {
int[] result = new int[model.length()];
for (int i = 0; i < result.length; i++) {
int[] classes = model.getPossibleValues(i);
result[i] = classes[random.nextInt(classes.length)];
}
return result;
}
/**
* Finds the best sequence by collecting numSamples samples, scoring them, and then choosing
* the highest scoring sample.
*
* @return the array of type int representing the highest scoring sequence
*/
public int[] bestSequence(SequenceModel model) {
int[] initialSequence = getRandomSequence(model);
return findBestUsingSampling(model, numSamples, sampleInterval, initialSequence);
}
/**
* Finds the best sequence by collecting numSamples samples, scoring them, and then choosing
* the highest scoring sample.
*
* @return the array of type int representing the highest scoring sequence
*/
public int[] findBestUsingSampling(SequenceModel model, int numSamples, int sampleInterval, int[] initialSequence) {
List samples = collectSamples(model, numSamples, sampleInterval, initialSequence);
int[] best = null;
double bestScore = Double.NEGATIVE_INFINITY;
for (int i = 0; i < samples.size(); i++) {
int[] sequence = (int[]) samples.get(i);
double score = model.scoreOf(sequence);
if (score > bestScore) {
best = sequence;
bestScore = score;
System.err.println("found new best (" + bestScore + ")");
System.err.println(ArrayMath.toString(best));
}
}
return best;
}
public int[] findBestUsingAnnealing(SequenceModel model, CoolingSchedule schedule) {
int[] initialSequence = getRandomSequence(model);
return findBestUsingAnnealing(model, schedule, initialSequence);
}
public int[] findBestUsingAnnealing(SequenceModel model, CoolingSchedule schedule, int[] initialSequence) {
if (verbose > 0) System.err.println("Doing annealing");
listener.setInitialSequence(initialSequence);
List result = new ArrayList();
// so we don't change the initial, or the one we just stored
int[] sequence = copy(initialSequence);
int[] best = null;
double bestScore = Double.NEGATIVE_INFINITY;
double score = Double.NEGATIVE_INFINITY;
// if (!returnLastFoundSequence) {
// score = model.scoreOf(sequence);
// }
Set<Integer> positionsChanged = null;
if (speedUpThreshold > 0)
positionsChanged = Generics.newHashSet();
for (int i = 0; i < schedule.numIterations(); i++) {
double temperature = schedule.getTemperature(i);
if (speedUpThreshold <= 0) {
score = sampleSequenceForward(model, sequence, temperature, null); // modifies tagSequence
} else {
if (i < speedUpThreshold) {
score = sampleSequenceForward(model, sequence, temperature, null); // modifies tagSequence
for (int j = 0; j < sequence.length; j++) {
if (sequence[j] != initialSequence[j])
positionsChanged.add(j);
}
} else {
score = sampleSequenceForward(model, sequence, temperature, positionsChanged); // modifies tagSequence
}
}
result.add(sequence);
if (returnLastFoundSequence) {
best = sequence;
} else {
// score = model.scoreOf(sequence);
//System.err.println(i+" "+score+" "+Arrays.toString(sequence));
if (score > bestScore) {
best = sequence;
bestScore = score;
}
}
if (i % 50 == 0) {
if (verbose > 1) System.err.println("itr " + i + ": " + bestScore + "\t");
}
if (verbose > 0) System.err.print(".");
}
if (verbose > 1) {
System.err.println();
printSamples(result, System.err);
}
if (verbose > 0) System.err.println("done.");
//return sequence;
return best;
}
/**
* Collects numSamples samples of sequences, from the distribution over sequences defined
* by the sequence model passed on construction.
* All samples collected are sampleInterval samples apart, in an attempt to reduce
* autocorrelation.
*
* @return a List containing the sequence samples, as arrays of type int, and their scores
*/
public List<int[]> collectSamples(SequenceModel model, int numSamples, int sampleInterval) {
int[] initialSequence = getRandomSequence(model);
return collectSamples(model, numSamples, sampleInterval, initialSequence);
}
/**
* Collects numSamples samples of sequences, from the distribution over sequences defined
* by the sequence model passed on construction.
* All samples collected are sampleInterval samples apart, in an attempt to reduce
* autocorrelation.
*
* @return a Counter containing the sequence samples, as arrays of type int, and their scores
*/
public List<int[]> collectSamples(SequenceModel model, int numSamples, int sampleInterval, int[] initialSequence) {
if (verbose > 0) System.err.print("Collecting samples");
listener.setInitialSequence(initialSequence);
List<int[]> result = new ArrayList<int[]>();
int[] sequence = initialSequence;
for (int i = 0; i < numSamples; i++) {
sequence = copy(sequence); // so we don't change the initial, or the one we just stored
sampleSequenceRepeatedly(model, sequence, sampleInterval); // modifies tagSequence
result.add(sequence); // save it to return later
if (verbose > 0) System.err.print(".");
System.err.flush();
}
if (verbose > 1) {
System.err.println();
printSamples(result, System.err);
}
if (verbose > 0) System.err.println("done.");
return result;
}
/**
* Samples the sequence repeatedly, making numSamples passes over the entire sequence.
*/
public double sampleSequenceRepeatedly(SequenceModel model, int[] sequence, int numSamples) {
sequence = copy(sequence); // so we don't change the initial, or the one we just stored
listener.setInitialSequence(sequence);
double returnScore = Double.NEGATIVE_INFINITY;
for (int iter = 0; iter < numSamples; iter++) {
returnScore = sampleSequenceForward(model, sequence);
}
return returnScore;
}
/**
* Samples the sequence repeatedly, making numSamples passes over the entire sequence.
* Destructively modifies the sequence in place.
*/
public double sampleSequenceRepeatedly(SequenceModel model, int numSamples) {
int[] sequence = getRandomSequence(model);
return sampleSequenceRepeatedly(model, sequence, numSamples);
}
/**
* Samples the complete sequence once in the forward direction
* Destructively modifies the sequence in place.
*
* @param sequence the sequence to start with.
*/
public double sampleSequenceForward(SequenceModel model, int[] sequence) {
return sampleSequenceForward(model, sequence, 1.0, null);
}
/**
* Samples the complete sequence once in the forward direction
* Destructively modifies the sequence in place.
*
* @param sequence the sequence to start with.
*/
public double sampleSequenceForward(final SequenceModel model, final int[] sequence, final double temperature, Set<Integer> onlySampleThesePositions) {
double returnScore = Double.NEGATIVE_INFINITY;
// System.err.println("Sampling forward");
if (onlySampleThesePositions != null) {
for (int pos : onlySampleThesePositions) {
returnScore = samplePosition(model, sequence, pos, temperature);
}
} else {
if (samplingStyle == SEQUENTIAL_SAMPLING) {
for (int pos = 0; pos < sequence.length; pos++) {
returnScore = samplePosition(model, sequence, pos, temperature);
}
} else if (samplingStyle == RANDOM_SAMPLING) {
for (int itr = 0; itr < sequence.length; itr++) {
int pos = random.nextInt(sequence.length);
returnScore = samplePosition(model, sequence, pos, temperature);
}
} else if (samplingStyle == CHROMATIC_SAMPLING) {
// make copies of the sequences and merge at the end
List<Pair<Integer, Integer>> results = new ArrayList<Pair<Integer, Integer>>();
for (List<Integer> indieList : partition) {
if (indieList.size() <= chromaticSize) {
for (int pos : indieList) {
Pair<Integer, Double> newPosProb = samplePositionHelper(model, sequence, pos, temperature);
sequence[pos] = newPosProb.first();
}
} else {
MulticoreWrapper<List<Integer>, List<Pair<Integer, Integer>>> wrapper = new MulticoreWrapper<List<Integer>, List<Pair<Integer, Integer>>>(chromaticSize,
new ThreadsafeProcessor<List<Integer>, List<Pair<Integer, Integer>>>() {
@Override
public List<Pair<Integer, Integer>> process(List<Integer> posList) {
List<Pair<Integer, Integer>> allPos = new ArrayList<Pair<Integer, Integer>>(posList.size());
Pair<Integer, Double> newPosProb = null;
for (int pos : posList) {
newPosProb = samplePositionHelper(model, sequence, pos, temperature);
// returns the position to sample in first place and new label in second place
allPos.add(new Pair<Integer, Integer>(pos, newPosProb.first()));
}
return allPos;
}
@Override
public ThreadsafeProcessor<List<Integer>, List<Pair<Integer, Integer>>> newInstance() {
return this;
}
}
);
results.clear();
int interval = Math.max(1, indieList.size() / chromaticSize);
for (int begin = 0, end = 0, indieListSize = indieList.size(); end < indieListSize; begin += interval) {
end = Math.min(begin + interval, indieListSize);
wrapper.put(indieList.subList(begin, end));
while (wrapper.peek()) {
results.addAll(wrapper.poll());
}
}
wrapper.join();
while (wrapper.peek()) {
results.addAll(wrapper.poll());
}
for (Pair<Integer, Integer> posVal : results) {
sequence[posVal.first()] = posVal.second();
}
}
}
returnScore = model.scoreOf(sequence);
}
}
return returnScore;
}
/**
* Samples the complete sequence once in the backward direction
* Destructively modifies the sequence in place.
*
* @param sequence the sequence to start with.
*/
public double sampleSequenceBackward(SequenceModel model, int[] sequence) {
return sampleSequenceBackward(model, sequence, 1.0);
}
/**
* Samples the complete sequence once in the backward direction
* Destructively modifies the sequence in place.
*
* @param sequence the sequence to start with.
*/
public double sampleSequenceBackward(SequenceModel model, int[] sequence, double temperature) {
double returnScore = Double.NEGATIVE_INFINITY;
for (int pos = sequence.length - 1; pos >= 0; pos--) {
returnScore = samplePosition(model, sequence, pos, temperature);
}
return returnScore;
}
/**
* Samples a single position in the sequence.
* Destructively modifies the sequence in place.
* returns the score of the new sequence
*
* @param sequence the sequence to start with
* @param pos the position to sample.
*/
public double samplePosition(SequenceModel model, int[] sequence, int pos) {
return samplePosition(model, sequence, pos, 1.0);
}
/**
* Samples a single position in the sequence.
* Does not modify the sequence passed in.
* returns the score of the new label for the position to sample
*
* @param sequence the sequence to start with
* @param pos the position to sample.
* @param temperature the temperature to control annealing
*/
private Pair<Integer, Double> samplePositionHelper(SequenceModel model, int[] sequence, int pos, double temperature) {
double[] distribution = model.scoresOf(sequence, pos);
if (temperature != 1.0) {
if (temperature == 0.0) {
// set the max to 1.0
int argmax = ArrayMath.argmax(distribution);
Arrays.fill(distribution, Double.NEGATIVE_INFINITY);
distribution[argmax] = 0.0;
} else {
// take all to a power
// use the temperature to increase/decrease the entropy of the sampling distribution
ArrayMath.multiplyInPlace(distribution, 1.0 / temperature);
}
}
ArrayMath.logNormalize(distribution);
ArrayMath.expInPlace(distribution);
int newTag = ArrayMath.sampleFromDistribution(distribution, random);
double newProb = distribution[newTag];
return new Pair<Integer, Double>(newTag, newProb);
}
/**
* Samples a single position in the sequence.
* Destructively modifies the sequence in place.
* returns the score of the new sequence
*
* @param sequence the sequence to start with
* @param pos the position to sample.
* @param temperature the temperature to control annealing
*/
public double samplePosition(SequenceModel model, int[] sequence, int pos, double temperature) {
int oldTag = sequence[pos];
Pair<Integer, Double> newPosProb = samplePositionHelper(model, sequence, pos, temperature);
int newTag = newPosProb.first();
// System.out.println("Sampled " + oldTag + "->" + newTag);
sequence[pos] = newTag;
listener.updateSequenceElement(sequence, pos, oldTag);
return newPosProb.second();
}
public void printSamples(List samples, PrintStream out) {
for (int i = 0; i < document.size(); i++) {
HasWord word = (HasWord) document.get(i);
String s = "null";
if (word != null) {
s = word.word();
}
out.print(StringUtils.padOrTrim(s, 10));
for (int j = 0; j < samples.size(); j++) {
int[] sequence = (int[]) samples.get(j);
out.print(" " + StringUtils.padLeft(sequence[i], 2));
}
out.println();
}
}
/**
* @param document the underlying document which is a list of HasWord; a slight abstraction violation, but useful for debugging!!
*/
public SequenceGibbsSampler(int numSamples, int sampleInterval, SequenceListener listener, List document,
boolean returnLastFoundSequence, int samplingStyle, int chromaticSize, List<List<Integer>> partition, int speedUpThreshold, EmpiricalNERPriorBIO priorEn, EmpiricalNERPriorBIO priorCh) {
this.numSamples = numSamples;
this.sampleInterval = sampleInterval;
this.listener = listener;
this.document = document;
this.returnLastFoundSequence = returnLastFoundSequence;
this.samplingStyle = samplingStyle;
if (verbose > 0) {
if (samplingStyle == RANDOM_SAMPLING) {
System.err.println("Using random sampling");
} else if (samplingStyle == CHROMATIC_SAMPLING) {
System.err.println("Using chromatic sampling with " + chromaticSize + " threads");
} else if (samplingStyle == SEQUENTIAL_SAMPLING) {
System.err.println("Using sequential sampling");
}
}
this.chromaticSize = chromaticSize;
this.partition = partition;
this.speedUpThreshold = speedUpThreshold;
//debug
this.priorEn = priorEn;
this.priorCh = priorCh;
}
public SequenceGibbsSampler(int numSamples, int sampleInterval, SequenceListener listener, List document) {
this(numSamples, sampleInterval, listener, document, false, 1, 0, null, -1, null, null);
}
public SequenceGibbsSampler(int numSamples, int sampleInterval, SequenceListener listener) {
this(numSamples, sampleInterval, listener, null);
}
public SequenceGibbsSampler(int numSamples, int sampleInterval, SequenceListener listener,
int samplingStyle, int chromaticSize, List<List<Integer>> partition, int speedUpThreshold, EmpiricalNERPriorBIO priorEn, EmpiricalNERPriorBIO priorCh) {
this(numSamples, sampleInterval, listener, null, false, samplingStyle, chromaticSize, partition, speedUpThreshold, priorEn, priorCh);
}
}
| [
"[email protected]"
] | |
c4acb873ff3088c24d3396352b3783df72ee97f0 | cf1f90c5d6bae04ba68e1d81cc9a137b94635b4c | /src/test/java/CaesarTest.java | 19575ee3c944a7dcf0aa279cff103bfc885b51d9 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | lanarokip/caesar_cipher | bddc2856d084afbd3985b48b5b58a6a45ea06a71 | 8ea837f320a4ca39d621f6191f60e22c601c4943 | refs/heads/master | 2023-07-14T17:44:55.107229 | 2021-09-06T08:53:17 | 2021-09-06T08:53:17 | 402,741,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 744 | java | import org.junit.Test;
import static org.junit.Assert.*;
public class CaesarTest {
@Test
public void Caesar_inputTwo_string() {
Caesar caesar = new Caesar ("message", 8);
assertEquals("message","message");
}
@Test
public void Caesar_takesShiftKey_int(){
Caesar caesar = new Caesar ("message", 8);
assertEquals(8, caesar.getShiftKey());
}
@Test
public void Decryption_decryptMethod_text() {
Decrypt decrypt = new Decrypt("aron",5);
assertEquals("ARON", Decrypt.planTxt2("fwts", 5));
}
@Test
public void Caesar_encyptMethod_text() {
Caesar caesar = new Caesar("fwts",5);
assertEquals("FWTS", Caesar.planTxt("aron",5));
}
}
| [
"[email protected]"
] | |
ec383331935fd69ffdbc817843d2a6a16efd48f4 | 4645855fad5c2aa23048e48cbb5ac3cb955e1e8f | /alexandria/app/src/main/java/it/jaschke/alexandria/services/BookService.java | cc2b0780b06d873434bc7f62dc869362eca9e18e | [
"Apache-2.0"
] | permissive | frank-tan/Super-Duo | 864a6dc99042950126a4abc477adfd93d330bc26 | 1ae0e71361b0af25642ab2e24e3051e5d2ded93b | refs/heads/master | 2021-01-10T11:46:37.420590 | 2016-04-27T13:51:15 | 2016-04-27T13:51:15 | 44,605,853 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,611 | java | package it.jaschke.alexandria.services;
import android.app.IntentService;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import it.jaschke.alexandria.R;
import it.jaschke.alexandria.data.AlexandriaContract;
import it.jaschke.alexandria.ui.MainActivity;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
*/
public class BookService extends IntentService {
private final String LOG_TAG = BookService.class.getSimpleName();
public static final String FETCH_BOOK = "it.jaschke.alexandria.services.action.FETCH_BOOK";
public static final String DELETE_BOOK = "it.jaschke.alexandria.services.action.DELETE_BOOK";
public static final String EAN = "it.jaschke.alexandria.services.extra.EAN";
public BookService() {
super("Alexandria");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (FETCH_BOOK.equals(action)) {
final String ean = intent.getStringExtra(EAN);
fetchBook(ean);
} else if (DELETE_BOOK.equals(action)) {
final String ean = intent.getStringExtra(EAN);
deleteBook(ean);
}
}
}
/**
* Handle action Foo in the provided background thread with the provided
* parameters.
*/
private void deleteBook(String ean) {
if(ean!=null) {
getContentResolver().delete(AlexandriaContract.BookEntry.buildBookUri(Long.parseLong(ean)), null, null);
}
}
/**
* Handle action fetchBook in the provided background thread with the provided
* parameters.
*/
private void fetchBook(String ean) {
if(ean.length()!=13){
return;
}
Cursor bookEntry = getContentResolver().query(
AlexandriaContract.BookEntry.buildBookUri(Long.parseLong(ean)),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
// Handle NullPointerException
int bookCount;
if(bookEntry == null) {
bookCount = 0;
} else {
try {
bookCount = bookEntry.getCount();
} catch (NullPointerException e) {
bookCount = 0;
}
}
if(bookCount > 0){
bookEntry.close();
return;
}
if(bookEntry != null) bookEntry.close();
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String bookJsonString = null;
try {
final String FORECAST_BASE_URL = "https://www.googleapis.com/books/v1/volumes?";
final String QUERY_PARAM = "q";
final String ISBN_PARAM = "isbn:" + ean;
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, ISBN_PARAM)
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
if (buffer.length() == 0) {
return;
}
bookJsonString = buffer.toString();
} catch (Exception e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
// Handle API connection failure
if(bookJsonString == null) {
Log.e(LOG_TAG, "Failed to connect to API. Nothing returned.");
return;
}
final String ITEMS = "items";
final String VOLUME_INFO = "volumeInfo";
final String TITLE = "title";
final String SUBTITLE = "subtitle";
final String AUTHORS = "authors";
final String DESC = "description";
final String CATEGORIES = "categories";
final String IMG_URL_PATH = "imageLinks";
final String IMG_URL = "thumbnail";
try {
JSONObject bookJson = new JSONObject(bookJsonString);
JSONArray bookArray;
if(bookJson.has(ITEMS)){
bookArray = bookJson.getJSONArray(ITEMS);
}else{
Intent messageIntent = new Intent(MainActivity.MESSAGE_EVENT);
messageIntent.putExtra(MainActivity.MESSAGE_KEY,getResources().getString(R.string.not_found));
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(messageIntent);
return;
}
JSONObject bookInfo = ((JSONObject) bookArray.get(0)).getJSONObject(VOLUME_INFO);
String title = bookInfo.getString(TITLE);
String subtitle = "";
if(bookInfo.has(SUBTITLE)) {
subtitle = bookInfo.getString(SUBTITLE);
}
String desc="";
if(bookInfo.has(DESC)){
desc = bookInfo.getString(DESC);
}
String imgUrl = "";
if(bookInfo.has(IMG_URL_PATH) && bookInfo.getJSONObject(IMG_URL_PATH).has(IMG_URL)) {
imgUrl = bookInfo.getJSONObject(IMG_URL_PATH).getString(IMG_URL);
}
writeBackBook(ean, title, subtitle, desc, imgUrl);
if(bookInfo.has(AUTHORS)) {
writeBackAuthors(ean, bookInfo.getJSONArray(AUTHORS));
}
if(bookInfo.has(CATEGORIES)){
writeBackCategories(ean,bookInfo.getJSONArray(CATEGORIES) );
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error ", e);
}
}
private void writeBackBook(String ean, String title, String subtitle, String desc, String imgUrl) {
ContentValues values= new ContentValues();
values.put(AlexandriaContract.BookEntry._ID, ean);
values.put(AlexandriaContract.BookEntry.TITLE, title);
values.put(AlexandriaContract.BookEntry.IMAGE_URL, imgUrl);
values.put(AlexandriaContract.BookEntry.SUBTITLE, subtitle);
values.put(AlexandriaContract.BookEntry.DESC, desc);
getContentResolver().insert(AlexandriaContract.BookEntry.CONTENT_URI,values);
}
private void writeBackAuthors(String ean, JSONArray jsonArray) throws JSONException {
ContentValues values= new ContentValues();
for (int i = 0; i < jsonArray.length(); i++) {
values.put(AlexandriaContract.AuthorEntry._ID, ean);
values.put(AlexandriaContract.AuthorEntry.AUTHOR, jsonArray.getString(i));
getContentResolver().insert(AlexandriaContract.AuthorEntry.CONTENT_URI, values);
values= new ContentValues();
}
}
private void writeBackCategories(String ean, JSONArray jsonArray) throws JSONException {
ContentValues values= new ContentValues();
for (int i = 0; i < jsonArray.length(); i++) {
values.put(AlexandriaContract.CategoryEntry._ID, ean);
values.put(AlexandriaContract.CategoryEntry.CATEGORY, jsonArray.getString(i));
getContentResolver().insert(AlexandriaContract.CategoryEntry.CONTENT_URI, values);
values= new ContentValues();
}
}
} | [
"[email protected]"
] | |
510bc93811aa85411f56945d6053bc53dd8371e9 | a1f59af18718f5b90e9faf560859d4e212247d0a | /ponysdk/src-core/main/java/com/ponysdk/ui/terminal/WidgetType.java | abe75f6567278a207d2d8ad27ae8b718b2ee574b | [] | no_license | Smart-Trade/PonySDK | ad5591dd9dddf84d5608a3549c693a6d01115f32 | 7670fa5f4c86947283fa9954f4db0e01647b4b13 | refs/heads/master | 2021-01-15T17:21:19.356402 | 2012-09-01T13:16:57 | 2012-09-01T13:16:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,797 | java | /*
* Copyright (c) 2011 PonySDK
* Owners:
* Luciano Broussal <luciano.broussal AT gmail.com>
* Mathieu Barbier <mathieu.barbier AT gmail.com>
* Nicolas Ciaravola <nicolas.ciaravola.pro AT gmail.com>
*
* WebSite:
* http://code.google.com/p/pony-sdk/
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.ponysdk.ui.terminal;
public enum WidgetType {
ROOT_LAYOUT_PANEL,
ROOT_PANEL,
DOCK_LAYOUT_PANEL,
ABSOLUTE_PANEL,
SPLIT_LAYOUT_PANEL,
SIMPLE_PANEL,
TAB_PANEL,
SCROLL_PANEL,
FLOW_PANEL,
VERTICAL_PANEL,
HORIZONTAL_PANEL,
BUTTON,
LABEL,
FLEX_TABLE,
GRID,
TREE,
TREE_ITEM,
COMPOSITE,
DATEBOX,
TEXTBOX,
PASSWORD_TEXTBOX,
LISTBOX,
IMAGE,
ANCHOR,
CHECKBOX,
MENU_BAR,
MENU_ITEM,
MENU_ITEM_SEPARATOR,
TAB_LAYOUT_PANEL,
LAYOUT_PANEL,
SIMPLE_LAYOUT_PANEL,
STACKLAYOUT_PANEL,
HTML,
RADIO_BUTTON,
TEXT_AREA,
POPUP_PANEL,
CELLLIST,
COOKIE,
FILE_UPLOAD,
PUSH_BUTTON,
ADDON,
RICH_TEXT_AREA,
DISCLOSURE_PANEL,
DECORATED_POPUP_PANEL,
DIALOG_BOX,
SUGGESTBOX,
DECORATOR_PANEL,
ELEMENT,
SCHEDULER,
ATTACHED_POPUP_PABEL,
FOCUS_PANEL,
DATEPICKER,
SCRIPT,
PUSHER;
}
| [
"[email protected]"
] | |
33bf3d08f39107d6f4f89f931dd09b9b23eb57a4 | c4c05f99b72988c5953c27ce170689c47f60e19a | /src/code/IntFilter.java | 05f2bf524a72e8f0bae30ffdb8f456bff93c696e | [] | no_license | lukejhudson/fyp-simulation | 844dc7c9697df386dc06fa350b9c5db49b8ce577 | 9871754182f740c96b1debd9e6bcf83e93ad48ad | refs/heads/master | 2020-03-25T12:36:55.817378 | 2019-04-27T16:38:06 | 2019-04-27T16:38:06 | 143,783,503 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,854 | java | package code;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
/**
* A DocumentFilter to ensure only positive integers can be entered into a text
* field.
*
* Based on the StackOverflow answer at
* "https://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers?answertab=votes#tab-top"
*
* @author Luke
*
*/
public class IntFilter extends DocumentFilter {
/*
* Invoked prior to insertion of text into the specified Document. Allows us
* to conditionally allow insertion.
*/
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
try {
sb.append(doc.getText(0, doc.getLength()));
} catch (BadLocationException e) {
e.printStackTrace();
}
sb.insert(offset, string);
if (test(sb.toString())) {
try {
super.insertString(fb, offset, string, attr);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
/**
* @param text
* The text to test
* @return True if the text is valid (a positive integer)
*/
private boolean test(String text) {
// Allow the text to be empty
if (text.trim().isEmpty()) {
return true;
}
// Only allow up to 5 digits
if (text.trim().length() >= 6) {
return false;
}
// Leading + or - is not allowed
if (text.contains("-") || text.contains("+")) {
return false;
}
// Text must be a valid integer
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/*
* Invoked prior to replacing a region of text in the specified Document.
*/
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
try {
sb.append(doc.getText(0, doc.getLength()));
} catch (BadLocationException e) {
e.printStackTrace();
}
sb.replace(offset, offset + length, text);
if (test(sb.toString())) {
try {
super.replace(fb, offset, length, text, attrs);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
/*
* Invoked prior to removal of the specified region in the specified Document.
*/
@Override
public void remove(FilterBypass fb, int offset, int length) {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
try {
sb.append(doc.getText(0, doc.getLength()));
} catch (BadLocationException e) {
e.printStackTrace();
}
sb.delete(offset, offset + length);
if (test(sb.toString())) {
try {
super.remove(fb, offset, length);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
} | [
"[email protected]"
] | |
bc62c0d12ac8cacd15a8b90a134e1f754d1ef87d | 3772d54ab6b8b4e750f1b80ef9df8d20f48f6dce | /src/OfficeHours04_15_2020/NestedLoops.java | 05c6eafffa196f17b1e657c0916fe17c33469bb8 | [] | no_license | OnderOmer/java1 | 90599fd99b56da954455045b69ac5d2d8a66ee74 | 40aaaa810aae16633102c01b90e7d1b3538dfc4c | refs/heads/master | 2022-06-04T00:30:54.317180 | 2020-05-01T05:50:55 | 2020-05-01T05:50:55 | 258,632,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 977 | java | package OfficeHours04_15_2020;
import java.util.Arrays;
public class NestedLoops {
public static void main(String[] args) {
// 0 1
char[][] arr2D = { { 'A', 'B'} , {'C', 'D', 'E'} , {'F', 'J', 'H'} };
// 0 1 2
for(int j = 0; j < arr2D.length; j++){ // j: index nums of 1D arrays
for(int i=0; i < arr2D[j].length; i++ ){ // i: index num of elements in 1D
System.out.println( arr2D[j][i] );
}
}
System.out.println("=============================================================");
// arr2D = { { 'A', 'B'} , {'C', 'D', 'E'} , {'F', 'J', 'H'} };
// 0 1 2
for( char[] each1DArray : arr2D ){
for( char eachElement : each1DArray ){
System.out.println(eachElement);
}
}
}
} | [
"[email protected]"
] | |
60d0f7df690eb0ab7590b42efa2d99ad276c7453 | c0e37626d4dda133f46b4472f22044b494eb98c7 | /server/data/packages/STICS_SNOW-master/src/simplace/Snowdepthtrans.java | 41f7b6666130c9e7efc94e833503cc5a71e6359d | [] | no_license | cyrillemidingoyi/crop2ml | 066b77dc298fe25b207a8b77ed140407fc7d3b14 | 3188a6aab7c29adc677bf9ec0855f639631fea8f | refs/heads/master | 2023-06-28T23:08:44.368239 | 2021-07-06T13:05:45 | 2021-07-06T13:05:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | import java.io.*;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javafx.util.*;
public void Process()
{
double tSdepth = Sdepth.getValue();
double tP_Pns = P_Pns.getValue();
double tSdepth_cm = Sdepth_cm.getValue();
tSdepth_cm = tSdepth * tP_Pns;
Sdepth_cm.setValue(tSdepth_cm);
} | [
"[email protected]"
] | |
e63fa7409b0d5182e4d46f4c0d173762e40db08b | 6afa1c66e2b58aeb5368e18bf974c6e139977adc | /src/com/example/android/skeletonapp/SkeletonActivity.java | ca1d6cbdf1a8a574d3921bdd639eb685a8360e84 | [] | no_license | drewby08/GuestPinGenerator | 45f97eafae17b175e40073991143e4881c70a872 | 0d5af07b4762a2cc668e7de77425d7136b2b215b | refs/heads/master | 2021-01-17T05:28:59.835727 | 2013-01-13T22:07:50 | 2013-01-13T22:07:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,924 | java | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtai a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.skeletonapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
/**
* This class provides a basic demonstration of how to write an Android
* activity. Inside of its window, it places a single view: an EditText that
* displays and edits some internal text.
*/
public class SkeletonActivity extends Activity {
private TextView pinLabel;
private DatePicker datePicker;
public SkeletonActivity() {
}
/** Called with the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.skeleton_activity);
// Find the text editor view inside the layout, because we
// want to do various programmatic things with it.
pinLabel = (TextView) findViewById(R.id.textView1);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
// Hook up button presses to the appropriate event handler.
((Button) findViewById(R.id.button1)).setOnClickListener(clickListener);
}
/**
* Called when the activity is about to start interacting with the user.
*/
@Override
protected void onResume() {
super.onResume();
}
/**
* A call-back for when the user presses the back button.
*/
OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Integer day = 0;
Integer month = 0;
Integer year = 0;
Integer mid = 0;
day = datePicker.getDayOfMonth();
month = datePicker.getMonth();
year = datePicker.getYear();
//hash everything!
mid = day.hashCode() * (month.hashCode()+1) * year.hashCode();
Integer pin = mid.hashCode() + 1;
//add some salt
pin = pin * 523411;
String pinStr = pin.toString();
//can safely get this substring from the salt
pinLabel.setText(pinStr.substring(pinStr.length()-6, pinStr.length()-1));
}
};
//Menu Stuff
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.guest_pin_menu, menu);
return true;
}
//Detect Menu Selection
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.sendEmail:
sendMail();
return true;
case R.id.addContacts:
editContacts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendMail(){
String[] recipients;
String date;
date = datePicker.getMonth()+1+"/"+datePicker.getDayOfMonth()+"/"+datePicker.getYear();
if(EmailsActivity.emailList != null && EmailsActivity.emailList.length()>0)
{
recipients = EmailsActivity.emailList.getText().toString().split("\n");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT,"Guest Pin Changed");
intent.putExtra(Intent.EXTRA_TEXT, "The new guest door pin as of "+date+" is: "+pinLabel.getText());
startActivity(intent);
}else{
Toast toast = Toast.makeText(getApplicationContext(), "Please Enter Recipients", Toast.LENGTH_SHORT);
toast.show();
}
}
public void editContacts(){
Intent intent = new Intent(SkeletonActivity.this, EmailsActivity.class);
startActivity(intent);
}
}
| [
"[email protected]"
] | |
5acd0e4adb994590b9d88ce07f6b225c197c79a2 | 4fd08e736019049a838dec9efa74cc2190b6625f | /testdata-java8/src/main/java/basic/StreamC.java | 4d01386a7fbc0a34113b72f74517e3d6209f995a | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-other-permissive"
] | permissive | knighthunter09/spring-loaded | 50a42cc41912ede861cae942e6458b79f2a6faa0 | 658a8678a672d24e9528fb63f70fa502ca7341ea | refs/heads/master | 2020-08-03T17:47:45.312949 | 2016-06-25T00:10:51 | 2016-06-25T00:10:51 | 73,540,025 | 1 | 0 | null | 2016-11-12T08:04:24 | 2016-11-12T08:04:21 | null | UTF-8 | Java | false | false | 438 | java | package basic;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamC {
public static void main(String[] args) {
System.out.println("This is Java8");
}
public static int run() {
List<Integer> integers = Arrays.asList(1, 2, 3);
List<Integer> mapped = integers.stream().map(n -> n).collect(Collectors.toList());
return mapped.size();
}
} | [
"[email protected]"
] | |
d861fd4b7c398212f4499cae6fb259c8c6af66f2 | f0bdd28f77057ea7fa246a0dc10efb82228d8355 | /src/com/java/collections/MyListTest.java | e7ab618d6feb61674528b38230a962804a2d8089 | [] | no_license | Sindhunaik25/164158_Sindhu | a4f939f9e3607e96876f2fee228b282cbdc17662 | 210d1aa31ea98035271e22d90b7020404a34418a | refs/heads/master | 2020-04-03T19:59:41.650293 | 2019-02-14T12:27:06 | 2019-02-14T12:27:06 | 155,543,002 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 344 | java | package com.java.collections;
public class MyListTest {
public static void main(String[] args) {
MyList<Integer> list=new MyList<Integer>();
MyList<String> list1=new MyList<String>();
list.add(10);
list.add(20);
list.add(30);
System.out.println(list.get());
list1.add("Sindhu");
list1.remove("Sindhu");
}
}
| [
"[email protected]"
] | |
085756192cc7e1c19fedc0ea4f38ef4b07fe4297 | 9411b4cd53d04c4fa52792f2b2f2fccb1622072e | /core/src/com/chris_ingram/unnamed_platformer/Sprites/TileObjects/InteractiveTileObject.java | 0e9db7e7d14eafa6b73e9b485b294f8984372873 | [] | no_license | CIngram82/UnnamedPlatformer | 2158fccfae923ce059b63f04037a9732baeca12a | 217464a0d37831deac59334f86c60ae32811609e | refs/heads/master | 2021-07-19T23:53:52.705804 | 2017-10-31T00:21:47 | 2017-10-31T00:21:47 | 107,037,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,447 | java | package com.chris_ingram.unnamed_platformer.Sprites.TileObjects;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Filter;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.chris_ingram.unnamed_platformer.Screens.PlayScreen;
import com.chris_ingram.unnamed_platformer.UnnamedPlatformer;
/**
* Created by cingr on 10/15/2017.
*/
public abstract class InteractiveTileObject {
protected World world;
protected TiledMap map;
protected MapObject object;
protected Rectangle bounds;
protected Body body;
protected Fixture fixture;
protected PlayScreen screen;
public InteractiveTileObject(PlayScreen screen, MapObject object) {
this.screen = screen;
this.world = screen.getWorld();
this.map = screen.getMap();
this.object = object;
this.bounds = ((RectangleMapObject)object).getRectangle();
BodyDef bdef = new BodyDef();
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set((bounds.getX()+bounds.getWidth()/2)/ UnnamedPlatformer.PPM,(bounds.getY()+bounds.getHeight()/2)/UnnamedPlatformer.PPM);
body = world.createBody(bdef);
shape.setAsBox((bounds.getWidth()/2)/UnnamedPlatformer.PPM,(bounds.getHeight()/2)/UnnamedPlatformer.PPM);
fdef.shape = shape;
fixture = body.createFixture(fdef);
}
public abstract void onHeadHit();
public void setCategoryFilter(short filterBit){
Filter filter = new Filter();
filter.categoryBits = filterBit;
fixture.setFilterData(filter);
}
public TiledMapTileLayer.Cell getCell(){
TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1);
return layer.getCell((int)(body.getPosition().x * UnnamedPlatformer.PPM/ 16),
(int)(body.getPosition().y * UnnamedPlatformer.PPM/ 16));
}
}
| [
"[email protected]"
] | |
afff8ca07b3598ff6d3be8f2d688bb56d00da16a | e1e5bd6b116e71a60040ec1e1642289217d527b0 | /H5/L2_Scripts_com/L2_Scripts_Revision_20720_2268/dist/gameserver/data/scripts/handler/items/WorldMap.java | 20bbdcdebae323a717b97bb07cde118a23190d74 | [] | no_license | serk123/L2jOpenSource | 6d6e1988a421763a9467bba0e4ac1fe3796b34b3 | 603e784e5f58f7fd07b01f6282218e8492f7090b | refs/heads/master | 2023-03-18T01:51:23.867273 | 2020-04-23T10:44:41 | 2020-04-23T10:44:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package handler.items;
import l2s.gameserver.model.Playable;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.items.ItemInstance;
import l2s.gameserver.network.l2.s2c.ShowMinimapPacket;
import handler.items.ScriptItemHandler;
public class WorldMap extends ScriptItemHandler
{
// all the items ids that this handler knowns
private static final int[] _itemIds = { 1665, 1863, 9994 };
@Override
public boolean useItem(Playable playable, ItemInstance item, boolean ctrl)
{
if(playable == null || !playable.isPlayer())
return false;
Player player = (Player) playable;
player.sendPacket(new ShowMinimapPacket(player, item.getItemId()));
return true;
}
@Override
public final int[] getItemIds()
{
return _itemIds;
}
} | [
"[email protected]"
] | |
3454147cf0bb99172a5f29cd3c26cc1dcc27b43d | 7d090886de9d6410863a0a6d157a76d772fb8232 | /src/models/LoginModel.java | 3eddca40cbd7fbedbd538083ffb119096355d294 | [] | no_license | sharath2101352/ITM510_Finalproject | 55ec7632804da24d78ff30c4d9f38fa3fe98b94a | 4bb20f24345629dc6d44cc0b41516a84ccafac0f | refs/heads/main | 2023-01-30T20:34:50.705712 | 2020-12-13T04:09:06 | 2020-12-13T04:09:06 | 311,748,789 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,487 | java | package models;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import Dao.DBConnect;
import util.MD5Encript;
public class LoginModel extends DBConnect {
private Boolean admin;
private int id;
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setRole(String role) {
this.role = role;
}
public Boolean isAdmin() {
return admin;
}
public String role() {
return role;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
public Boolean getCredentials(String username, String password){
password = MD5Encript.passwordEncript(password);
String query = "SELECT * FROM ms_users WHERE email = ? and password = ?;";
try(PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
setId(rs.getInt("userId"));
setAdmin(rs.getString("role").equals("ADMIN"));
setRole(rs.getString("role"));
System.out.println("Admin : "+isAdmin());
return true;
}
}catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}//end class | [
"[email protected]"
] | |
63593b671b139834e03d029d9ed6c13d4abc6d10 | 0c617b546cbbc47dce2d37fb14edc16040beae41 | /Aula5/src/com/company/Main.java | 9e45cd6132799b9179136f3b20795a9dd18a3fcf | [] | no_license | Diogofbg/AD | 40e693f71176bc766327ba2e597cea933bb01c2d | ea80cde674d6bc77d3dd0eba1c82817fa922bbee | refs/heads/master | 2023-02-24T00:13:27.097828 | 2021-01-22T16:02:01 | 2021-01-22T16:02:01 | 302,430,150 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 721 | java | package com.company;
import java.awt.geom.Area;
public class Main {
public static void main(String[] args) {
Point x = new Point(10,20);
Point y = new Point(25,50);
double setDistance = x.distanceTo(y);
System.out.println(setDistance);
Point a = new Point(0,3);
Point b = new Point(0,0);
Point c = new Point(3,0);
Triangle LL = new Triangle();
Triangle L = new Triangle(a, b, c);
System.out.println(L.Area());
Point t = new Point(0,5);
Point h = new Point(1,1);
Rectangle rt = new Rectangle(new Point(0,5),5,5);
boolean contains = rt.contains(h);
System.out.println(contains);
}
}
| [
"[email protected]"
] | |
dddba76375d4d58bc82ad165c2a9abe8e61f4b6b | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/10/10_1241a31a5fdfeb9d142482f1813170e95d50110e/JFlexXref/10_1241a31a5fdfeb9d142482f1813170e95d50110e_JFlexXref_s.java | 68c1058b69c4100cb1b5dba1d294fd8e5fa915f2 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,960 | java | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
*/
package org.opensolaris.opengrok.analysis;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Set;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.history.Annotation;
import org.opensolaris.opengrok.web.Util;
/**
* Base class for Xref lexers.
*
* @author Lubos Kosco
*/
public abstract class JFlexXref {
public Writer out;
public String urlPrefix = RuntimeEnvironment.getInstance().getUrlPrefix();
public Annotation annotation;
public Project project;
protected Definitions defs;
/** EOF value returned by yylex(). */
private final int yyeof;
protected JFlexXref() {
try {
// TODO when bug #16053 is fixed, we should add a getter to a file
// that's included from all the Xref classes so that we avoid the
// reflection.
Field f = getClass().getField("YYEOF");
yyeof = f.getInt(null);
} catch (Exception e) {
// The auto-generated constructors for the Xref classes don't
// expect a checked exception, so wrap it in an AssertionError.
// This should never happen, since all the Xref classes will get
// a public static YYEOF field from JFlex.
AssertionError ae = new AssertionError("Couldn't initialize yyeof");
ae.initCause(e);
throw ae; // NOPMD (stack trace is preserved by initCause(), but
// PMD thinks it's lost)
}
}
/**
* Reinitialize the xref with new contents.
*
* @param contents a char buffer with text to analyze
* @param length the number of characters to use from the char buffer
*/
public void reInit(char[] contents, int length) {
yyreset(new CharArrayReader(contents, 0, length));
annotation = null;
}
public void setDefs(Definitions defs) {
this.defs = defs;
}
protected void appendProject() throws IOException {
if (project != null) {
out.write("&project=");
out.write(project.getDescription());
}
}
protected String getProjectPostfix() {
return project == null ? "" : ("&project=" + project.getDescription());
}
/** Get the next token from the scanner. */
public abstract int yylex() throws IOException;
/** Reset the scanner. */
public abstract void yyreset(Reader reader);
/** Get the value of {@code yyline}. */
protected abstract int getLineNumber();
/** Set the value of {@code yyline}. */
protected abstract void setLineNumber(int x);
/**
* Write xref to the specified {@code Writer}.
*
* @param out xref destination
* @throws IOException on error when writing the xref
*/
public void write(Writer out) throws IOException {
this.out = out;
setLineNumber(0);
startNewLine();
while (yylex() != yyeof) { // NOPMD while statement intentionally empty
// nothing to do here, yylex() will do the work
}
}
/**
* Terminate the current line and insert preamble for the next line. The
* line count will be incremented.
*
* @throws IOException on error when writing the xref
*/
protected void startNewLine() throws IOException {
int line = getLineNumber() + 1;
setLineNumber(line);
Util.readableLine(line, out, annotation);
}
/**
* Write a symbol and generate links as appropriate.
*
* @param symbol the symbol to write
* @param keywords a set of keywords recognized by this analyzer (no links
* will be generated if the symbol is a keyword)
* @param line the line number on which the symbol appears
* @throws IOException if an error occurs while writing to the stream
*/
protected void writeSymbol(String symbol, Set<String> keywords, int line)
throws IOException {
String[] strs = new String[1];
strs[0] = "";
if (keywords != null && keywords.contains(symbol)) {
// This is a keyword, so we don't create a link.
out.append("<b>").append(symbol).append("</b>");
} else if (defs != null && defs.hasDefinitionAt(symbol, line, strs)) {
// This is the definition of the symbol.
String type = strs[0];
String style_class = "d";
if (type.startsWith("macro")) {
style_class = "xm";
} else if (type.startsWith("argument")) {
style_class = "xa";
} else if (type.startsWith("local")) {
style_class = "xl";
} else if (type.startsWith("variable")) {
style_class = "xv";
} else if (type.startsWith("class")) {
style_class = "xc";
} else if (type.startsWith("interface")) {
style_class = "xi";
} else if (type.startsWith("namespace")) {
style_class = "xn";
} else if (type.startsWith("enum")) {
style_class = "xe";
} else if (type.startsWith("enumerator")) {
style_class = "xer";
} else if (type.startsWith("struct")) {
style_class = "xs";
} else if (type.startsWith("typedef")) {
style_class = "xt";
} else if (type.startsWith("typedefs")) {
style_class = "xts";
} else if (type.startsWith("union")) {
style_class = "xu";
} else if (type.startsWith("field")) {
style_class = "xfld";
} else if (type.startsWith("member")) {
style_class = "xmb";
} else if (type.startsWith("function")) {
style_class = "xf";
} else if (type.startsWith("method")) {
style_class = "xmt";
} else if (type.startsWith("subroutine")) {
style_class = "xsr";
}
// 1) Create an anchor for direct links. (Perhaps we should only
// do this when there's exactly one definition of the symbol in
// this file? Otherwise, we may end up with multiple anchors with
// the same name.)
out.append("<a class=\"");
out.append(style_class);
out.append("\" name=\"");
out.append(symbol);
out.append("\"/>");
// 2) Create a link that searches for all references to this symbol.
out.append("<a href=\"");
out.append(urlPrefix);
out.append("refs=");
out.append(symbol);
appendProject();
out.append("\" class=\"");
out.append(style_class);
out.append("\" ");
// May have multiple anchors with the same function name,
// store line number for accurate location used in list.jsp.
out.append("ln=\"");
out.append(Integer.toString(line));
out.append("\">");
out.append(symbol);
out.append("</a>");
} else if (defs != null && defs.occurrences(symbol) == 1) {
// This is a reference to a symbol defined exactly once in this file.
String style_class = "d";
// Generate a direct link to the symbol definition.
out.append("<a class=\"");
out.append(style_class);
out.append("\" href=\"#");
out.append(symbol);
out.append("\">");
out.append(symbol);
out.append("</a>");
} else {
// This is a symbol that is not defined in this file, or a symbol
// that is defined more than once in this file. In either case, we
// can't generate a direct link to the definition, so generate a
// link to search for all definitions of that symbol instead.
out.append("<a href=\"");
out.append(urlPrefix);
out.append("defs=");
out.append(symbol);
appendProject();
out.append("\">");
out.append(symbol);
out.append("</a>");
}
}
/**
* Write HTML escape sequence for the specified Unicode character, unless
* it's an ISO control character, in which case it is ignored.
*
* @param c the character to write
* @throws IOException if an error occurs while writing to the stream
*/
protected void writeUnicodeChar(char c) throws IOException {
if (!Character.isISOControl(c)) {
out.append("&#").append(Integer.toString((int) c)).append(';');
}
}
}
| [
"[email protected]"
] | |
d0fb8b044eb79aa358c634ae57836c48b1c3b5d2 | b02dcbf38768fafcb246773fc05169e4649d8632 | /src/main/java/com/zurcnanor/tinnovatest/vehicle/service/VehicleService.java | 99d7644ea8eec7b86d8cc11f741fc49a84b6e59e | [] | no_license | rcruz148/tinnovatest | c333c78c7e1fae61f43f37f16eacc3172d5a6d7c | 3ff92edc58a236b1b4ca5041f4fd6dfdcc75d09a | refs/heads/main | 2023-02-28T17:08:41.641778 | 2021-02-01T01:52:17 | 2021-02-01T01:52:17 | 334,800,314 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,990 | java | package com.zurcnanor.tinnovatest.vehicle.service;
import com.zurcnanor.tinnovatest.interfaces.IService;
import com.zurcnanor.tinnovatest.vehicle.domain.Vehicle;
import com.zurcnanor.tinnovatest.vehicle.dto.SearchSpecification;
import com.zurcnanor.tinnovatest.vehicle.exception.SearchingDateInvalidException;
import com.zurcnanor.tinnovatest.vehicle.exception.VehicleNotFoundException;
import com.zurcnanor.tinnovatest.vehicle.repository.VehicleRepository;
import com.zurcnanor.tinnovatest.vehicle.service.validator.VehicleValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.UUID;
import static java.time.LocalDateTime.now;
import static java.util.UUID.randomUUID;
@Service
public class VehicleService implements IService<Vehicle, UUID> {
@Autowired
private VehicleRepository repository;
@Autowired
private VehicleValidator validator;
@Override
public List<Vehicle> getAll(SearchSpecification spec) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime startDateTime, endDateTime = null;
try {
if (null != spec.getStartDate())
startDateTime = LocalDate.parse(spec.getStartDate(), formatter).atTime(LocalTime.MIN);
else
startDateTime = LocalDateTime.of(LocalDate.of(1800, 01, 01), LocalTime.MIN);
if (null != spec.getEndDate())
endDateTime = LocalDate.parse(spec.getEndDate(), formatter).atTime(LocalTime.MAX);
else
endDateTime = LocalDateTime.of(LocalDate.of(9999, 01, 01), LocalTime.MAX);
} catch (DateTimeParseException exception) {
throw new SearchingDateInvalidException(exception.getParsedString());
}
return repository.findByQuery(spec.getQ(), startDateTime, endDateTime);
}
@Override
public Vehicle getById(UUID id) {
return repository.findById(id)
.orElseThrow(VehicleNotFoundException::new);
}
@Override
public Vehicle create(Vehicle vehicle) {
validator.validate(vehicle);
vehicle.setId(randomUUID());
vehicle.setCreatedAt(now());
return repository.save(vehicle);
}
@Override
public Vehicle edit(Vehicle vehicle) {
validator.validate(vehicle);
Vehicle found = getById(vehicle.getId());
found.setName(vehicle.getName());
found.setBrand(vehicle.getBrand());
found.setDescription(vehicle.getDescription());
found.setYear(vehicle.getYear());
found.setSold(vehicle.getSold());
found.setUpdatedAt(now());
return repository.saveAndFlush(found);
}
@Override
public Vehicle update(Vehicle vehicle) {
Vehicle found = getById(vehicle.getId());
if (null != vehicle.getName() && !found.getName().equals(vehicle.getName()))
found.setName(vehicle.getName());
if (null != vehicle.getBrand() && !found.getBrand().equals(vehicle.getBrand()))
found.setBrand(vehicle.getBrand());
if (null != vehicle.getDescription() && !found.getDescription().equals(vehicle.getDescription()))
found.setDescription(vehicle.getDescription());
if (null != vehicle.getYear() && !found.getYear().equals(vehicle.getYear()))
found.setYear(vehicle.getYear());
if (null != found.getSold() && !found.getSold().equals(vehicle.getSold()))
found.setSold(vehicle.getSold());
found.setUpdatedAt(now());
validator.validate(found);
return repository.saveAndFlush(found);
}
@Override
public void deleteById(UUID id) {
repository.delete(getById(id));
}
}
| [
"[email protected]"
] | |
c3387dfa6970df024230845c104b978693e3a24c | 24636c3be1652b29c3ea405973ba0a3e34ebe502 | /org.eclipse.microservices/src/micro/impl/StepImpl.java | 749c9bc5953fd21efdc5779b20735a21aad0227a | [] | no_license | yaseenkhantanoli/MDE-Sirius_project | f43951450434ca663ac511e88ca53e7858212add | 42b58aa3778a39994b56f5507b82eb86528b8280 | refs/heads/master | 2020-03-24T04:51:08.735233 | 2018-07-26T16:41:39 | 2018-07-26T16:41:39 | 142,466,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,796 | java | /**
*/
package micro.impl;
import java.util.Collection;
import micro.Command;
import micro.MicroPackage;
import micro.Step;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Step</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link micro.impl.StepImpl#getCommands <em>Commands</em>}</li>
* </ul>
*
* @generated
*/
public class StepImpl extends NamedElementImpl implements Step {
/**
* The cached value of the '{@link #getCommands() <em>Commands</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCommands()
* @generated
* @ordered
*/
protected EList<Command> commands;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected StepImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MicroPackage.Literals.STEP;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Command> getCommands() {
if (commands == null) {
commands = new EObjectResolvingEList<Command>(Command.class, this, MicroPackage.STEP__COMMANDS);
}
return commands;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MicroPackage.STEP__COMMANDS:
return getCommands();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MicroPackage.STEP__COMMANDS:
getCommands().clear();
getCommands().addAll((Collection<? extends Command>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MicroPackage.STEP__COMMANDS:
getCommands().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MicroPackage.STEP__COMMANDS:
return commands != null && !commands.isEmpty();
}
return super.eIsSet(featureID);
}
} //StepImpl
| [
"[email protected]"
] | |
9129c2e7836fc98d42063c3bd4aad7924b5cf155 | fdf10d4e0713ca3080b9c464343f59f8c0473c17 | /multi-datasource-jpa/src/main/java/com/pcz/multi/datasource/jpa/SpringBootMultiDatasourceJpaApplication.java | 3469413af68be3f51bf40a3ec0053bd5f02c9df2 | [
"MIT"
] | permissive | picongzhi/spring-boot-demo | 4a4b3b5fdf1c8155961df272915ae9b7dfc86a21 | 4ec79dc5df9163564c32dbbc7accece7f1b83bdf | refs/heads/master | 2021-07-12T04:06:21.773857 | 2020-10-20T09:03:18 | 2020-10-20T09:03:18 | 207,985,328 | 0 | 1 | MIT | 2020-07-02T00:39:41 | 2019-09-12T06:58:07 | Java | UTF-8 | Java | false | false | 404 | java | package com.pcz.multi.datasource.jpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author picongzhi
*/
@SpringBootApplication
public class SpringBootMultiDatasourceJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMultiDatasourceJpaApplication.class, args);
}
}
| [
"[email protected]"
] | |
883a633f37671bf6914225d83199adc0940fe8e1 | ac49190345e921dded73833e24bd2ca7a0a31578 | /HW03-0036489629/tests/prob1/hr/fer/zemris/java/tecaj/hw3/prob1/Prob1Test.java | 2ad4252d6f4b934e84d0dd66d17a74d9d235dede | [] | no_license | the-JJ/FER-OPJJ | a15871cfd042662bebb1416969b2e96832c0ec07 | fce1288119b60c3a3666c09c463fdc7d208d1888 | refs/heads/master | 2021-06-01T18:00:16.700192 | 2016-09-03T10:58:24 | 2016-09-03T10:58:24 | 67,282,608 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 9,262 | java | package hr.fer.zemris.java.tecaj.hw3.prob1;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Ignore;
import org.junit.Test;
public class Prob1Test {
@Ignore
@Test
public void testNotNull() {
Lexer lexer = new Lexer("");
assertNotNull("Token was expected but null was returned.", lexer.nextToken());
}
@Ignore
@Test(expected=IllegalArgumentException.class)
public void testNullInput() {
// must throw!
new Lexer(null);
}
@Ignore
@Test
public void testEmpty() {
Lexer lexer = new Lexer("");
assertEquals("Empty input must generate only EOF token.", TokenType.EOF, lexer.nextToken().getType());
}
@Ignore
@Test
public void testGetReturnsLastNext() {
// Calling getToken once or several times after calling nextToken must return each time what nextToken returned...
Lexer lexer = new Lexer("");
Token token = lexer.nextToken();
assertEquals("getToken returned different token than nextToken.", token, lexer.getToken());
assertEquals("getToken returned different token than nextToken.", token, lexer.getToken());
}
@Ignore
@Test(expected=LexerException.class)
public void testRadAfterEOF() {
Lexer lexer = new Lexer("");
// will obtain EOF
lexer.nextToken();
// will throw!
lexer.nextToken();
}
@Ignore
@Test
public void testNoActualContent() {
// When input is only of spaces, tabs, newlines, etc...
Lexer lexer = new Lexer(" \r\n\t ");
assertEquals("Input had no content. Lexer should generated only EOF token.", TokenType.EOF, lexer.nextToken().getType());
}
@Ignore
@Test
public void testTwoWords() {
// Lets check for several words...
Lexer lexer = new Lexer(" Štefanija\r\n\t Automobil ");
// We expect the following stream of tokens
Token correctData[] = {
new Token(TokenType.WORD, "Štefanija"),
new Token(TokenType.WORD, "Automobil"),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test
public void testWordStartingWithEscape() {
Lexer lexer = new Lexer(" \\1st \r\n\t ");
// We expect the following stream of tokens
Token correctData[] = {
new Token(TokenType.WORD, "1st"),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test(expected=LexerException.class)
public void testInvalidEscapeEnding() {
Lexer lexer = new Lexer(" \\"); // this is three spaces and a single backslash -- 4 letters string
// will throw!
lexer.nextToken();
}
@Ignore
@Test(expected=LexerException.class)
public void testInvalidEscape() {
Lexer lexer = new Lexer(" \\a ");
// will throw!
lexer.nextToken();
}
@Ignore
@Test
public void testSingleEscapedDigit() {
Lexer lexer = new Lexer(" \\1 ");
// We expect the following stream of tokens
Token correctData[] = {
new Token(TokenType.WORD, "1"),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test
public void testWordWithManyEscapes() {
// Lets check for several words...
Lexer lexer = new Lexer(" ab\\1\\2cd\\3 ab\\2\\1cd\\4\\\\ \r\n\t ");
// We expect the following stream of tokens
Token correctData[] = {
new Token(TokenType.WORD, "ab12cd3"),
new Token(TokenType.WORD, "ab21cd4\\"), // this is 8-letter long, not nine! Only single backslash!
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test
public void testTwoNumbers() {
// Lets check for several numbers...
Lexer lexer = new Lexer(" 1234\r\n\t 5678 ");
Token correctData[] = {
new Token(TokenType.NUMBER, Long.valueOf(1234)),
new Token(TokenType.NUMBER, Long.valueOf(5678)),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test(expected=LexerException.class)
public void testTooBigNumber() {
Lexer lexer = new Lexer(" 12345678912123123432123 ");
// will throw!
lexer.nextToken();
}
@Ignore
@Test
public void testWordWithManyEscapesAndNumbers() {
// Lets check for several words...
Lexer lexer = new Lexer(" ab\\123cd ab\\2\\1cd\\4\\\\ \r\n\t ");
// We expect following stream of tokens
Token correctData[] = {
new Token(TokenType.WORD, "ab1"),
new Token(TokenType.NUMBER, Long.valueOf(23)),
new Token(TokenType.WORD, "cd"),
new Token(TokenType.WORD, "ab21cd4\\"), // this is 8-letter long, not nine! Only single backslash!
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test
public void testSomeSymbols() {
// Lets check for several symbols...
Lexer lexer = new Lexer(" -.? \r\n\t ## ");
Token correctData[] = {
new Token(TokenType.SYMBOL, Character.valueOf('-')),
new Token(TokenType.SYMBOL, Character.valueOf('.')),
new Token(TokenType.SYMBOL, Character.valueOf('?')),
new Token(TokenType.SYMBOL, Character.valueOf('#')),
new Token(TokenType.SYMBOL, Character.valueOf('#')),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
@Ignore
@Test
public void testCombinedInput() {
// Lets check for several symbols...
Lexer lexer = new Lexer("Janko 3! Jasmina 5; -24");
Token correctData[] = {
new Token(TokenType.WORD, "Janko"),
new Token(TokenType.NUMBER, Long.valueOf(3)),
new Token(TokenType.SYMBOL, Character.valueOf('!')),
new Token(TokenType.WORD, "Jasmina"),
new Token(TokenType.NUMBER, Long.valueOf(5)),
new Token(TokenType.SYMBOL, Character.valueOf(';')),
new Token(TokenType.SYMBOL, Character.valueOf('-')),
new Token(TokenType.NUMBER, Long.valueOf(24)),
new Token(TokenType.EOF, null)
};
checkTokenStream(lexer, correctData);
}
// Helper method for checking if lexer generates the same stream of tokens
// as the given stream.
private void checkTokenStream(Lexer lexer, Token[] correctData) {
int counter = 0;
for(Token expected : correctData) {
Token actual = lexer.nextToken();
String msg = "Checking token "+counter + ":";
assertEquals(msg, expected.getType(), actual.getType());
assertEquals(msg, expected.getValue(), actual.getValue());
counter++;
}
}
// ----------------------------------------------------------------------------------------------------------
// --------------------- Second part of tests; uncomment when everything above works ------------------------
// ----------------------------------------------------------------------------------------------------------
/*
@Ignore
@Test(expected=IllegalArgumentException.class)
public void testNullState() {
new Lexer("").setState(null);
}
@Ignore
@Test
public void testNotNullInExtended() {
Lexer lexer = new Lexer("");
lexer.setState(LexerState.EXTENDED);
assertNotNull("Token was expected but null was returned.", lexer.nextToken());
}
@Ignore
@Test
public void testEmptyInExtended() {
Lexer lexer = new Lexer("");
lexer.setState(LexerState.EXTENDED);
assertEquals("Empty input must generate only EOF token.", TokenType.EOF, lexer.nextToken().getType());
}
@Ignore
@Test
public void testGetReturnsLastNextInExtended() {
// Calling getToken once or several times after calling nextToken must return each time what nextToken returned...
Lexer lexer = new Lexer("");
lexer.setState(LexerState.EXTENDED);
Token token = lexer.nextToken();
assertEquals("getToken returned different token than nextToken.", token, lexer.getToken());
assertEquals("getToken returned different token than nextToken.", token, lexer.getToken());
}
@Ignore
@Test(expected=LexerException.class)
public void testRadAfterEOFInExtended() {
Lexer lexer = new Lexer("");
lexer.setState(LexerState.EXTENDED);
// will obtain EOF
lexer.nextToken();
// will throw!
lexer.nextToken();
}
@Ignore
@Test
public void testNoActualContentInExtended() {
// When input is only of spaces, tabs, newlines, etc...
Lexer lexer = new Lexer(" \r\n\t ");
lexer.setState(LexerState.EXTENDED);
assertEquals("Input had no content. Lexer should generated only EOF token.", TokenType.EOF, lexer.nextToken().getType());
}
@Ignore
@Test
public void testMultipartInput() {
// Test input which has parts which are tokenized by different rules...
Lexer lexer = new Lexer("Janko 3# Ivana26\\a 463abc#zzz");
checkToken(lexer.nextToken(), new Token(TokenType.WORD, "Janko"));
checkToken(lexer.nextToken(), new Token(TokenType.NUMBER, Long.valueOf(3)));
checkToken(lexer.nextToken(), new Token(TokenType.SYMBOL, Character.valueOf('#')));
lexer.setState(LexerState.EXTENDED);
checkToken(lexer.nextToken(), new Token(TokenType.WORD, "Ivana26\\a"));
checkToken(lexer.nextToken(), new Token(TokenType.WORD, "463abc"));
checkToken(lexer.nextToken(), new Token(TokenType.SYMBOL, Character.valueOf('#')));
lexer.setState(LexerState.BASIC);
checkToken(lexer.nextToken(), new Token(TokenType.WORD, "zzz"));
checkToken(lexer.nextToken(), new Token(TokenType.EOF, null));
}
private void checkToken(Token actual, Token expected) {
String msg = "Token are not equal.";
assertEquals(msg, expected.getType(), actual.getType());
assertEquals(msg, expected.getValue(), actual.getValue());
}
*/
}
| [
"[email protected]"
] | |
e184826f9da1a655575779718a74f1caefba9e4b | 9d71bef6ae4ed8df9aad357bf1fcade4643fcf51 | /src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientProtocolConfig.java | 254230938d1f240073d08047c4af3ac2bc602e28 | [] | no_license | MasonEcnu/MicroJava | 6c33e39d67835a57ae2ca5f5b3ad37aeb9e351ba | 307329f64742da456ebe9788fd9cb62cdced8a62 | refs/heads/master | 2021-03-23T03:59:50.614960 | 2020-04-30T02:06:35 | 2020-04-30T02:06:35 | 247,420,762 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,204 | java | /*
* Copyright 2019 The Netty Project
*
* The Netty Project 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 io.netty.handler.codec.http.websocketx;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler.ClientHandshakeStateEvent;
import io.netty.util.internal.ObjectUtil;
import java.net.URI;
import static io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig.DEFAULT_HANDSHAKE_TIMEOUT_MILLIS;
import static io.netty.util.internal.ObjectUtil.checkPositive;
/**
* WebSocket server configuration.
*/
public final class WebSocketClientProtocolConfig {
static final boolean DEFAULT_PERFORM_MASKING = true;
static final boolean DEFAULT_ALLOW_MASK_MISMATCH = false;
static final boolean DEFAULT_HANDLE_CLOSE_FRAMES = true;
static final boolean DEFAULT_DROP_PONG_FRAMES = true;
private final URI webSocketUri;
private final String subprotocol;
private final WebSocketVersion version;
private final boolean allowExtensions;
private final HttpHeaders customHeaders;
private final int maxFramePayloadLength;
private final boolean performMasking;
private final boolean allowMaskMismatch;
private final boolean handleCloseFrames;
private final WebSocketCloseStatus sendCloseFrame;
private final boolean dropPongFrames;
private final long handshakeTimeoutMillis;
private final long forceCloseTimeoutMillis;
private final boolean absoluteUpgradeUrl;
private WebSocketClientProtocolConfig(
URI webSocketUri,
String subprotocol,
WebSocketVersion version,
boolean allowExtensions,
HttpHeaders customHeaders,
int maxFramePayloadLength,
boolean performMasking,
boolean allowMaskMismatch,
boolean handleCloseFrames,
WebSocketCloseStatus sendCloseFrame,
boolean dropPongFrames,
long handshakeTimeoutMillis,
long forceCloseTimeoutMillis,
boolean absoluteUpgradeUrl
) {
this.webSocketUri = webSocketUri;
this.subprotocol = subprotocol;
this.version = version;
this.allowExtensions = allowExtensions;
this.customHeaders = customHeaders;
this.maxFramePayloadLength = maxFramePayloadLength;
this.performMasking = performMasking;
this.allowMaskMismatch = allowMaskMismatch;
this.forceCloseTimeoutMillis = forceCloseTimeoutMillis;
this.handleCloseFrames = handleCloseFrames;
this.sendCloseFrame = sendCloseFrame;
this.dropPongFrames = dropPongFrames;
this.handshakeTimeoutMillis = checkPositive(handshakeTimeoutMillis, "handshakeTimeoutMillis");
this.absoluteUpgradeUrl = absoluteUpgradeUrl;
}
public URI webSocketUri() {
return webSocketUri;
}
public String subprotocol() {
return subprotocol;
}
public WebSocketVersion version() {
return version;
}
public boolean allowExtensions() {
return allowExtensions;
}
public HttpHeaders customHeaders() {
return customHeaders;
}
public int maxFramePayloadLength() {
return maxFramePayloadLength;
}
public boolean performMasking() {
return performMasking;
}
public boolean allowMaskMismatch() {
return allowMaskMismatch;
}
public boolean handleCloseFrames() {
return handleCloseFrames;
}
public WebSocketCloseStatus sendCloseFrame() {
return sendCloseFrame;
}
public boolean dropPongFrames() {
return dropPongFrames;
}
public long handshakeTimeoutMillis() {
return handshakeTimeoutMillis;
}
public long forceCloseTimeoutMillis() {
return forceCloseTimeoutMillis;
}
public boolean absoluteUpgradeUrl() {
return absoluteUpgradeUrl;
}
@Override
public String toString() {
return "WebSocketClientProtocolConfig" +
" {webSocketUri=" + webSocketUri +
", subprotocol=" + subprotocol +
", version=" + version +
", allowExtensions=" + allowExtensions +
", customHeaders=" + customHeaders +
", maxFramePayloadLength=" + maxFramePayloadLength +
", performMasking=" + performMasking +
", allowMaskMismatch=" + allowMaskMismatch +
", handleCloseFrames=" + handleCloseFrames +
", sendCloseFrame=" + sendCloseFrame +
", dropPongFrames=" + dropPongFrames +
", handshakeTimeoutMillis=" + handshakeTimeoutMillis +
", forceCloseTimeoutMillis=" + forceCloseTimeoutMillis +
", absoluteUpgradeUrl=" + absoluteUpgradeUrl +
"}";
}
public Builder toBuilder() {
return new Builder(this);
}
public static Builder newBuilder() {
return new Builder(
URI.create("https://localhost/"),
null,
WebSocketVersion.V13,
false,
EmptyHttpHeaders.INSTANCE,
65536,
DEFAULT_PERFORM_MASKING,
DEFAULT_ALLOW_MASK_MISMATCH,
DEFAULT_HANDLE_CLOSE_FRAMES,
WebSocketCloseStatus.NORMAL_CLOSURE,
DEFAULT_DROP_PONG_FRAMES,
DEFAULT_HANDSHAKE_TIMEOUT_MILLIS,
-1,
false);
}
public static final class Builder {
private URI webSocketUri;
private String subprotocol;
private WebSocketVersion version;
private boolean allowExtensions;
private HttpHeaders customHeaders;
private int maxFramePayloadLength;
private boolean performMasking;
private boolean allowMaskMismatch;
private boolean handleCloseFrames;
private WebSocketCloseStatus sendCloseFrame;
private boolean dropPongFrames;
private long handshakeTimeoutMillis;
private long forceCloseTimeoutMillis;
private boolean absoluteUpgradeUrl;
private Builder(WebSocketClientProtocolConfig clientConfig) {
this(ObjectUtil.checkNotNull(clientConfig, "clientConfig").webSocketUri(),
clientConfig.subprotocol(),
clientConfig.version(),
clientConfig.allowExtensions(),
clientConfig.customHeaders(),
clientConfig.maxFramePayloadLength(),
clientConfig.performMasking(),
clientConfig.allowMaskMismatch(),
clientConfig.handleCloseFrames(),
clientConfig.sendCloseFrame(),
clientConfig.dropPongFrames(),
clientConfig.handshakeTimeoutMillis(),
clientConfig.forceCloseTimeoutMillis(),
clientConfig.absoluteUpgradeUrl());
}
private Builder(URI webSocketUri,
String subprotocol,
WebSocketVersion version,
boolean allowExtensions,
HttpHeaders customHeaders,
int maxFramePayloadLength,
boolean performMasking,
boolean allowMaskMismatch,
boolean handleCloseFrames,
WebSocketCloseStatus sendCloseFrame,
boolean dropPongFrames,
long handshakeTimeoutMillis,
long forceCloseTimeoutMillis,
boolean absoluteUpgradeUrl) {
this.webSocketUri = webSocketUri;
this.subprotocol = subprotocol;
this.version = version;
this.allowExtensions = allowExtensions;
this.customHeaders = customHeaders;
this.maxFramePayloadLength = maxFramePayloadLength;
this.performMasking = performMasking;
this.allowMaskMismatch = allowMaskMismatch;
this.handleCloseFrames = handleCloseFrames;
this.sendCloseFrame = sendCloseFrame;
this.dropPongFrames = dropPongFrames;
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
this.forceCloseTimeoutMillis = forceCloseTimeoutMillis;
this.absoluteUpgradeUrl = absoluteUpgradeUrl;
}
/**
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
*/
public Builder webSocketUri(String webSocketUri) {
return webSocketUri(URI.create(webSocketUri));
}
/**
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
*/
public Builder webSocketUri(URI webSocketUri) {
this.webSocketUri = webSocketUri;
return this;
}
/**
* Sub protocol request sent to the server.
*/
public Builder subprotocol(String subprotocol) {
this.subprotocol = subprotocol;
return this;
}
/**
* Version of web socket specification to use to connect to the server
*/
public Builder version(WebSocketVersion version) {
this.version = version;
return this;
}
/**
* Allow extensions to be used in the reserved bits of the web socket frame
*/
public Builder allowExtensions(boolean allowExtensions) {
this.allowExtensions = allowExtensions;
return this;
}
/**
* Map of custom headers to add to the client request
*/
public Builder customHeaders(HttpHeaders customHeaders) {
this.customHeaders = customHeaders;
return this;
}
/**
* Maximum length of a frame's payload
*/
public Builder maxFramePayloadLength(int maxFramePayloadLength) {
this.maxFramePayloadLength = maxFramePayloadLength;
return this;
}
/**
* Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
* with the websocket specifications. Client applications that communicate with a non-standard server
* which doesn't require masking might set this to false to achieve a higher performance.
*/
public Builder performMasking(boolean performMasking) {
this.performMasking = performMasking;
return this;
}
/**
* When set to true, frames which are not masked properly according to the standard will still be accepted.
*/
public Builder allowMaskMismatch(boolean allowMaskMismatch) {
this.allowMaskMismatch = allowMaskMismatch;
return this;
}
/**
* {@code true} if close frames should not be forwarded and just close the channel
*/
public Builder handleCloseFrames(boolean handleCloseFrames) {
this.handleCloseFrames = handleCloseFrames;
return this;
}
/**
* Close frame to send, when close frame was not send manually. Or {@code null} to disable proper close.
*/
public Builder sendCloseFrame(WebSocketCloseStatus sendCloseFrame) {
this.sendCloseFrame = sendCloseFrame;
return this;
}
/**
* {@code true} if pong frames should not be forwarded
*/
public Builder dropPongFrames(boolean dropPongFrames) {
this.dropPongFrames = dropPongFrames;
return this;
}
/**
* Handshake timeout in mills, when handshake timeout, will trigger user
* event {@link ClientHandshakeStateEvent#HANDSHAKE_TIMEOUT}
*/
public Builder handshakeTimeoutMillis(long handshakeTimeoutMillis) {
this.handshakeTimeoutMillis = handshakeTimeoutMillis;
return this;
}
/**
* Close the connection if it was not closed by the server after timeout specified
*/
public Builder forceCloseTimeoutMillis(long forceCloseTimeoutMillis) {
this.forceCloseTimeoutMillis = forceCloseTimeoutMillis;
return this;
}
/**
* Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over clear HTTP
*/
public Builder absoluteUpgradeUrl(boolean absoluteUpgradeUrl) {
this.absoluteUpgradeUrl = absoluteUpgradeUrl;
return this;
}
/**
* Build unmodifiable client protocol configuration.
*/
public WebSocketClientProtocolConfig build() {
return new WebSocketClientProtocolConfig(
webSocketUri,
subprotocol,
version,
allowExtensions,
customHeaders,
maxFramePayloadLength,
performMasking,
allowMaskMismatch,
handleCloseFrames,
sendCloseFrame,
dropPongFrames,
handshakeTimeoutMillis,
forceCloseTimeoutMillis,
absoluteUpgradeUrl
);
}
}
}
| [
"[email protected]"
] | |
693d0c3442a431e425a2e5fec13843912769c0cf | 9fc4b599b2a8433df4279fa3063619edb64089ae | /hw10-hibernate/src/main/java/ru/otus/core/service/DbServiceException.java | 77512175e9de8942b675cd23349daa2084441069 | [
"MIT"
] | permissive | hikarido/2020-03-otus-java-ananev | 9dacb72f0340b52c1fea134f2d0c7b6ac9f6b365 | 239cbb9c4eba002670e9d7cf807760db4c76efe1 | refs/heads/master | 2021-05-18T04:50:07.095792 | 2020-11-08T16:27:50 | 2020-11-08T16:27:50 | 251,116,705 | 0 | 0 | MIT | 2020-11-08T16:27:51 | 2020-03-29T19:32:31 | Java | UTF-8 | Java | false | false | 160 | java | package ru.otus.core.service;
public class DbServiceException extends RuntimeException{
public DbServiceException(Exception e) {
super(e);
}
}
| [
"[email protected]"
] | |
40e8f289a9443e70f202b2e3f98d88862251478c | b78d96a8660f90649035c7a6d6698cabb2946d62 | /solutions/ModelJoin/src/main/java/substationStandard/LNNodes/LNGroupP/PTUC.java | 20d6df9e3e37585f92cb21e5b461ec8d41381ec6 | [
"MIT"
] | permissive | suchaoxiao/ttc2017smartGrids | d7b677ddb20a0adc74daed9e3ae815997cc86e1a | 2997f1c202f5af628e50f5645c900f4d35f44bb7 | refs/heads/master | 2021-06-19T10:21:22.740676 | 2017-07-14T12:13:22 | 2017-07-14T12:13:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,494 | java | /**
*/
package substationStandard.LNNodes.LNGroupP;
import substationStandard.Dataclasses.ACD;
import substationStandard.Dataclasses.ACT;
import substationStandard.Dataclasses.ASG;
import substationStandard.Dataclasses.CSD;
import substationStandard.Dataclasses.CURVE;
import substationStandard.Dataclasses.ING;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>PTUC</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getStr <em>Str</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getOp <em>Op</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmASt <em>Tm ASt</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmACrv <em>Tm ACrv</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getStrVal <em>Str Val</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getOpDlTmms <em>Op Dl Tmms</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmMult <em>Tm Mult</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getMinOpTmms <em>Min Op Tmms</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getMaxOpTmms <em>Max Op Tmms</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getRsDlTmms <em>Rs Dl Tmms</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getConsTms <em>Cons Tms</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupP.PTUC#getAlmVal <em>Alm Val</em>}</li>
* </ul>
*
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC()
* @model
* @generated
*/
public interface PTUC extends GroupP {
/**
* Returns the value of the '<em><b>Str</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Str</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Str</em>' reference.
* @see #setStr(ACD)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_Str()
* @model required="true"
* @generated
*/
ACD getStr();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getStr <em>Str</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Str</em>' reference.
* @see #getStr()
* @generated
*/
void setStr(ACD value);
/**
* Returns the value of the '<em><b>Op</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Op</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Op</em>' reference.
* @see #setOp(ACT)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_Op()
* @model required="true"
* @generated
*/
ACT getOp();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getOp <em>Op</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Op</em>' reference.
* @see #getOp()
* @generated
*/
void setOp(ACT value);
/**
* Returns the value of the '<em><b>Tm ASt</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Tm ASt</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Tm ASt</em>' reference.
* @see #setTmASt(CSD)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_TmASt()
* @model required="true"
* @generated
*/
CSD getTmASt();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmASt <em>Tm ASt</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Tm ASt</em>' reference.
* @see #getTmASt()
* @generated
*/
void setTmASt(CSD value);
/**
* Returns the value of the '<em><b>Tm ACrv</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Tm ACrv</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Tm ACrv</em>' reference.
* @see #setTmACrv(CURVE)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_TmACrv()
* @model required="true"
* @generated
*/
CURVE getTmACrv();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmACrv <em>Tm ACrv</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Tm ACrv</em>' reference.
* @see #getTmACrv()
* @generated
*/
void setTmACrv(CURVE value);
/**
* Returns the value of the '<em><b>Str Val</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Str Val</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Str Val</em>' reference.
* @see #setStrVal(ASG)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_StrVal()
* @model required="true"
* @generated
*/
ASG getStrVal();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getStrVal <em>Str Val</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Str Val</em>' reference.
* @see #getStrVal()
* @generated
*/
void setStrVal(ASG value);
/**
* Returns the value of the '<em><b>Op Dl Tmms</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Op Dl Tmms</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Op Dl Tmms</em>' reference.
* @see #setOpDlTmms(ING)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_OpDlTmms()
* @model required="true"
* @generated
*/
ING getOpDlTmms();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getOpDlTmms <em>Op Dl Tmms</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Op Dl Tmms</em>' reference.
* @see #getOpDlTmms()
* @generated
*/
void setOpDlTmms(ING value);
/**
* Returns the value of the '<em><b>Tm Mult</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Tm Mult</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Tm Mult</em>' reference.
* @see #setTmMult(ASG)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_TmMult()
* @model required="true"
* @generated
*/
ASG getTmMult();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getTmMult <em>Tm Mult</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Tm Mult</em>' reference.
* @see #getTmMult()
* @generated
*/
void setTmMult(ASG value);
/**
* Returns the value of the '<em><b>Min Op Tmms</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Min Op Tmms</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Min Op Tmms</em>' reference.
* @see #setMinOpTmms(ING)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_MinOpTmms()
* @model required="true"
* @generated
*/
ING getMinOpTmms();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getMinOpTmms <em>Min Op Tmms</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Min Op Tmms</em>' reference.
* @see #getMinOpTmms()
* @generated
*/
void setMinOpTmms(ING value);
/**
* Returns the value of the '<em><b>Max Op Tmms</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Max Op Tmms</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Max Op Tmms</em>' reference.
* @see #setMaxOpTmms(ING)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_MaxOpTmms()
* @model required="true"
* @generated
*/
ING getMaxOpTmms();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getMaxOpTmms <em>Max Op Tmms</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Max Op Tmms</em>' reference.
* @see #getMaxOpTmms()
* @generated
*/
void setMaxOpTmms(ING value);
/**
* Returns the value of the '<em><b>Rs Dl Tmms</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rs Dl Tmms</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rs Dl Tmms</em>' reference.
* @see #setRsDlTmms(ING)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_RsDlTmms()
* @model required="true"
* @generated
*/
ING getRsDlTmms();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getRsDlTmms <em>Rs Dl Tmms</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Rs Dl Tmms</em>' reference.
* @see #getRsDlTmms()
* @generated
*/
void setRsDlTmms(ING value);
/**
* Returns the value of the '<em><b>Cons Tms</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Cons Tms</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Cons Tms</em>' reference.
* @see #setConsTms(ING)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_ConsTms()
* @model required="true"
* @generated
*/
ING getConsTms();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getConsTms <em>Cons Tms</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Cons Tms</em>' reference.
* @see #getConsTms()
* @generated
*/
void setConsTms(ING value);
/**
* Returns the value of the '<em><b>Alm Val</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Alm Val</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Alm Val</em>' reference.
* @see #setAlmVal(ASG)
* @see substationStandard.LNNodes.LNGroupP.LNGroupPPackage#getPTUC_AlmVal()
* @model required="true"
* @generated
*/
ASG getAlmVal();
/**
* Sets the value of the '{@link substationStandard.LNNodes.LNGroupP.PTUC#getAlmVal <em>Alm Val</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Alm Val</em>' reference.
* @see #getAlmVal()
* @generated
*/
void setAlmVal(ASG value);
} // PTUC
| [
"[email protected]"
] | |
a38a8e1c6fc62828384628313704f7a5df678626 | 991c009bff7b440a175363d9d397c2b48e01b536 | /src/gov/nasa/worldwind/WorldWindowGLAutoDrawable.java | 5d5b84df8d7512feda8515ca8aa32e72575b5f71 | [] | no_license | IUE/QGlobe | 39c86f05b2ad8c3c264972cfad01c62d19678e2b | f78c857c366580121c029f2d036aa2afc5709f75 | refs/heads/master | 2016-09-05T18:56:29.968147 | 2013-03-29T20:56:40 | 2013-03-29T20:56:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,812 | java | /*
* Copyright (C) 2011 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind;
import gov.nasa.worldwind.cache.GpuResourceCache;
import gov.nasa.worldwind.event.*;
import gov.nasa.worldwind.exception.WWAbsentRequirementException;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.pick.PickedObject;
import gov.nasa.worldwind.render.ScreenCreditController;
import gov.nasa.worldwind.util.*;
//import javax.swing.*;
//import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.media.opengl.*;
/**
* A non-platform specific {@link WorldWindow} class. This class can be aggregated into platform-specific classes to
* provide the core functionality of World Wind.
*
* @author Tom Gaskins
* @version $Id: WorldWindowGLAutoDrawable.java 1 2011-07-16 23:22:47Z dcollins $
*/
public class WorldWindowGLAutoDrawable extends WorldWindowImpl implements WorldWindowGLDrawable, GLEventListener
{
/**
* Default time in milliseconds that the view must remain unchanged before the {@link View#VIEW_STOPPED} message is
* sent.
*/
public static final long DEFAULT_VIEW_STOP_TIME = 1000;
private GLAutoDrawable drawable;
private boolean shuttingDown = false;
//private Timer redrawTimer;
private boolean firstInit = true;
/** Time in milliseconds that the view must remain unchanged before the {@link View#VIEW_STOPPED} message is sent. */
protected long viewStopTime = DEFAULT_VIEW_STOP_TIME;
/**
* The most recent View modelView ID.
*
* @see gov.nasa.worldwind.View#getViewStateID()
*/
protected long lastViewID;
/** Schedule task to send the {@link View#VIEW_STOPPED} message after the view stop time elapses. */
protected ScheduledFuture viewRefreshTask;
/** Construct a new <code>WorldWindowGLCanvas</code> for a specified {@link GLDrawable}. */
public WorldWindowGLAutoDrawable()
{
SceneController sc = this.getSceneController();
if (sc != null)
sc.addPropertyChangeListener(this);
}
/**
* Indicates the amount of time, in milliseconds, that the View must remain unchanged before a {@link
* View#VIEW_STOPPED} event is triggered.
*
* @return Time in milliseconds that the View must must remain unchanged before the view stopped event is
* triggered.
*/
public long getViewStopTime()
{
return this.viewStopTime;
}
/**
* Specifies the amount of time, in milliseconds, that the View must remain unchanged before a {@link
* View#VIEW_STOPPED} event is triggered.
*
* @param time Time in milliseconds that the View must must remain unchanged before the view stopped event is
* triggered.
*/
public void setViewStopTime(long time)
{
this.viewStopTime = time;
}
public void initDrawable(GLAutoDrawable glAutoDrawable)
{
if (glAutoDrawable == null)
{
String msg = Logging.getMessage("nullValue.DrawableIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.drawable = glAutoDrawable;
this.drawable.setAutoSwapBufferMode(false);
this.drawable.addGLEventListener(this);
}
public void initGpuResourceCache(GpuResourceCache cache)
{
if (cache == null)
{
String msg = Logging.getMessage("nullValue.GpuResourceCacheIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.setGpuResourceCache(cache);
}
public void endInitialization()
{
initializeCreditsController();
}
protected void initializeCreditsController()
{
new ScreenCreditController((WorldWindow) this.drawable);
}
@Override
public void shutdown()
{
this.shuttingDown = true;
this.drawable.display(); // Invokes a repaint, where the rest of the shutdown work is done.
}
protected void doShutdown()
{
super.shutdown();
this.drawable.removeGLEventListener(this);
if (this.viewRefreshTask != null)
this.viewRefreshTask.cancel(false);
this.shuttingDown = false;
}
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent)
{
if (propertyChangeEvent == null)
{
String msg = Logging.getMessage("nullValue.PropertyChangeEventIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (this.drawable != null)
this.drawable.repaint(); // Queue a JOGL repaint request.
}
public GLContext getContext()
{
return this.drawable.getContext();
}
protected String[] getRequiredOglFunctions()
{
return new String[] {"glActiveTexture", "glClientActiveTexture"};
}
protected String[] getRequiredOglExtensions()
{
return new String[] {};
}
/**
* See {@link GLEventListener#init(GLAutoDrawable)}.
*
* @param glAutoDrawable the drawable
*/
public void init(GLAutoDrawable glAutoDrawable)
{
for (String funcName : this.getRequiredOglFunctions())
{
if (!glAutoDrawable.getGL().isFunctionAvailable(funcName))
{
//noinspection ThrowableInstanceNeverThrown
this.callRenderingExceptionListeners(new WWAbsentRequirementException(funcName + " not available"));
}
}
for (String extName : this.getRequiredOglExtensions())
{
if (!glAutoDrawable.getGL().isExtensionAvailable(extName))
{
//noinspection ThrowableInstanceNeverThrown
this.callRenderingExceptionListeners(new WWAbsentRequirementException(extName + " not available"));
}
}
if (this.firstInit)
this.firstInit = false;
else
this.reinitialize(glAutoDrawable);
// this.drawable.setGL(new DebugGL(this.drawable.getGL())); // uncomment to use the debug drawable
}
@SuppressWarnings( {"UnusedParameters"})
protected void reinitialize(GLAutoDrawable glAutoDrawable)
{
// Clear the gpu resource cache if the window is reinitializing, most likely with a new gl hardware context.
if (this.getGpuResourceCache() != null)
this.getGpuResourceCache().clear();
this.getSceneController().reinitialize();
}
/**
* See {@link GLEventListener#display(GLAutoDrawable)}.
*
* @param glAutoDrawable the drawable
*
* @throws IllegalStateException if no {@link SceneController} exists for this canvas
*/
public void display(GLAutoDrawable glAutoDrawable)
{
// Performing shutdown here in order to do so with a current GL context for GL resource disposal.
if (this.shuttingDown)
{
try
{
this.doShutdown();
}
catch (Exception e)
{
Logging.logger().log(Level.SEVERE, Logging.getMessage(
"WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"), e);
}
return;
}
try
{
SceneController sc = this.getSceneController();
if (sc == null)
{
Logging.logger().severe("WorldWindowGLCanvas.ScnCntrllerNullOnRepaint");
throw new IllegalStateException(Logging.getMessage("WorldWindowGLCanvas.ScnCntrllerNullOnRepaint"));
}
// Determine if the view has changed since the last frame.
this.checkForViewChange();
Position positionAtStart = this.getCurrentPosition();
PickedObject selectionAtStart = this.getCurrentSelection();
try
{
this.callRenderingListeners(new RenderingEvent(this.drawable, RenderingEvent.BEFORE_RENDERING));
}
catch (Exception e)
{
Logging.logger().log(Level.SEVERE,
Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e);
}
int redrawDelay = this.doDisplay();
if (redrawDelay > 0)
{
//TODO BBB - need to rewrite with android timer
// if (this.redrawTimer == null)
// {
// this.redrawTimer = new Timer(redrawDelay, new ActionListener()
// {
// public void actionPerformed(ActionEvent actionEvent)
// {
// drawable.repaint();
// redrawTimer = null;
// }
// });
// redrawTimer.setRepeats(false);
// redrawTimer.start();
// }
}
try
{
this.callRenderingListeners(new RenderingEvent(this.drawable, RenderingEvent.BEFORE_BUFFER_SWAP));
}
catch (Exception e)
{
Logging.logger().log(Level.SEVERE,
Logging.getMessage("WorldWindowGLAutoDrawable.ExceptionDuringGLEventListenerDisplay"), e);
}
this.doSwapBuffers(this.drawable);
Double frameTime = sc.getFrameTime();
if (frameTime != null)
this.setValue(PerformanceStatistic.FRAME_TIME, frameTime);
Double frameRate = sc.getFramesPerSecond();
if (frameRate != null)
this.setValue(PerformanceStatistic.FRAME_RATE, frameRate);
// Dispatch the rendering exceptions accumulated by the SceneController during this frame to our
// RenderingExceptionListeners.
Iterable<Throwable> renderingExceptions = sc.getRenderingExceptions();
if (renderingExceptions != null)
{
for (Throwable t : renderingExceptions)
{
if (t != null)
this.callRenderingExceptionListeners(t);
}
}
this.callRenderingListeners(new RenderingEvent(this.drawable, RenderingEvent.AFTER_BUFFER_SWAP));
// Position and selection notification occurs only on triggering conditions, not same-state conditions:
// start == null, end == null: nothing selected -- don't notify
// start == null, end != null: something now selected -- notify
// start != null, end == null: something was selected but no longer is -- notify
// start != null, end != null, start != end: something new was selected -- notify
// start != null, end != null, start == end: same thing is selected -- don't notify
Position positionAtEnd = this.getCurrentPosition();
if (positionAtStart != null || positionAtEnd != null)
{
// call the listener if both are not null or positions are the same
if (positionAtStart != null && positionAtEnd != null)
{
if (!positionAtStart.equals(positionAtEnd))
this.callPositionListeners(new PositionEvent(this.drawable, sc.getPickPoint(),
positionAtStart, positionAtEnd));
}
else
{
this.callPositionListeners(new PositionEvent(this.drawable, sc.getPickPoint(),
positionAtStart, positionAtEnd));
}
}
PickedObject selectionAtEnd = this.getCurrentSelection();
if (selectionAtStart != null || selectionAtEnd != null)
{
this.callSelectListeners(new SelectEvent(this.drawable, SelectEvent.ROLLOVER,
sc.getPickPoint(), sc.getPickedObjectList()));
}
}
catch (Exception e)
{
Logging.logger().log(Level.SEVERE, Logging.getMessage(
"WorldWindowGLCanvas.ExceptionAttemptingRepaintWorldWindow"), e);
}
}
/**
* Determine if the view has changed since the previous frame. If the view has changed, schedule a task that will
* send a {@link View#VIEW_STOPPED} to the Model if the view does not change for {@link #viewStopTime}
* milliseconds.
*
* @see #getViewStopTime()
*/
protected void checkForViewChange()
{
long viewId = this.getView().getViewStateID();
// Determine if the view has changed since the previous frame.
if (viewId != this.lastViewID)
{
// View has changed, capture the new viewStateID
this.lastViewID = viewId;
// Cancel the previous view stop task and schedule a new one because the view has changed.
this.scheduleViewStopTask(this.getViewStopTime());
}
}
/**
* Performs the actual repaint. Provided so that subclasses may override the repaint steps.
*
* @return if greater than zero, the window should be automatically repainted again at the indicated number of
* milliseconds from this method's return.
*/
protected int doDisplay()
{
return this.getSceneController().repaint();
}
/**
* Performs the actual buffer swap. Provided so that subclasses may override the swap steps.
*
* @param drawable the window's associated drawable.
*/
protected void doSwapBuffers(GLAutoDrawable drawable)
{
drawable.swapBuffers();
}
/**
* See {@link GLEventListener#reshape(GLAutoDrawable, int, int, int, int)}.
*
* @param glAutoDrawable the drawable
*/
public void reshape(GLAutoDrawable glAutoDrawable, int x, int y, int w, int h)
{
// This is apparently necessary to enable the WWJ canvas to resize correctly with JSplitPane.
//((Component) glAutoDrawable).setMinimumSize(new Dimension(0, 0));
}
/**
* See {@link GLEventListener#displayChanged(GLAutoDrawable, boolean, boolean)}.
*
* @param glAutoDrawable the drawable
*/
public void displayChanged(GLAutoDrawable glAutoDrawable, boolean b, boolean b1)
{
Logging.logger().finest("WorldWindowGLCanvas.DisplayEventListenersDisplayChangedMethodCalled");
}
@Override
public void redraw()
{
if (this.drawable != null)
this.drawable.repaint();
}
public void redrawNow()
{
if (this.drawable != null)
this.drawable.display();
}
/**
* Schedule a task that will send a {@link View#VIEW_STOPPED} message to the Model when the task executes. If the
* task runs (is not cancelled), then the view is considered stopped. Only one view stop task is scheduled at a
* time. If this method is called again before the task executes, the task will be cancelled and a new task
* scheduled.
*
* @param delay Delay in milliseconds until the task runs.
*/
protected void scheduleViewStopTask(long delay)
{
Runnable viewStoppedTask = new Runnable()
{
public void run()
{
// Call onMessage on the EDT with a VIEW_STOP message
//BBB - call android version
// EventQueue.invokeLater(new Runnable()
// {
// public void run()
// {
WorldWindowGLAutoDrawable.this.onMessage(
new Message(View.VIEW_STOPPED, WorldWindowGLAutoDrawable.this));
// }
// });
}
};
// Cancel the previous view stop task
if (this.viewRefreshTask != null)
{
this.viewRefreshTask.cancel(false);
}
// Schedule the task for execution in delay milliseconds
this.viewRefreshTask = WorldWind.getScheduledTaskService()
.addScheduledTask(viewStoppedTask, delay, TimeUnit.MILLISECONDS);
}
/**
* {@inheritDoc}
* <p/>
* Forward the message event to the Model for distribution to the layers.
*
* @param msg Message event.
*/
@Override
public void onMessage(Message msg)
{
Model model = this.getModel();
if (model != null)
{
model.onMessage(msg);
}
}
}
| [
"[email protected]"
] | |
4c0c74bdd4ccf7677478d7ed3b5b52799cda4496 | 50ce167011ea244f092ba02f06b1604b04c90424 | /app/src/main/java/com/example/the_dagger/learnit/adapter/CategoryAdapter.java | 0bc498dd666afbf4dd06f3aff5b0c2a56c03cc77 | [] | no_license | mayank408/Learn-CODEWARS | d291022c00fb8c2dde40c5aad50fd814eaad0344 | e1c4b436d8727839d1067246c02c7a89de638521 | refs/heads/master | 2021-01-12T17:00:43.999593 | 2016-10-20T19:17:59 | 2016-10-20T19:17:59 | 71,490,291 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,594 | java | package com.example.the_dagger.learnit.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.the_dagger.learnit.R;
import com.example.the_dagger.learnit.activity.QuizActivity;
import com.example.the_dagger.learnit.model.Categories;
import com.example.the_dagger.learnit.model.SingleChoiceQuestion;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.list;
import static android.media.CamcorderProfile.get;
import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;
/**
* Created by the-dagger on 1/10/16.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
private ArrayList<Categories> listCategories;
private ArrayList<SingleChoiceQuestion> singleChoiceQuestionArrayList;
private int position;
//private final View.OnClickListener mOnClickListener = new View.OnClickListener();
private final Context context;
int answer[] = new int[10];
@Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_category_item, parent, false);
return new ViewHolder(itemView);
}
public CategoryAdapter(ArrayList<Categories> categories, Context context) {
this.listCategories = categories;
this.context = context;
}
@Override
public void onBindViewHolder(final CategoryAdapter.ViewHolder holder, final int position) {
this.position = position;
Log.e("onBindViewHolder: Ans",String.valueOf(answer ) + String.valueOf(position) );
Categories singleCategory = listCategories.get(holder.getAdapterPosition());
if (getItemCount() == -1) {
holder.title.setText("No Categories at the moment");
holder.title.setGravity(View.TEXT_ALIGNMENT_CENTER);
} else {
holder.title.setText(singleCategory.getName());
}
holder.itemView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
int i = 0;
while (i < listCategories.get(position).getQuizzes().size()) {
answer[i] = listCategories.get(position).getQuizzes().get(i).getAnswer();
i++;
}
Intent intent = new Intent(context, QuizActivity.class);
intent.putExtra("position", position);
intent.putExtra("singleAdapter", listCategories.get(position));
intent.putParcelableArrayListExtra("singleChoiceQuestion", listCategories.get(position).getQuizzes());
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return listCategories.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image =(ImageView) itemView.findViewById(R.id.background);
title = (TextView) itemView.findViewById(R.id.category_title);
}
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.