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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0b0aa3b59debefb0ec343e4d944591e75db107fe | aa1a22e06556c5a8568eb268accbe6a674af1eea | /src/main/java/com/crimespotter/api/event/model/naturaldisasterinfo/NaturalDisaster.java | 91ee5cf430b3d53f4082d0d30e6cfcb487c0f8d3 | [] | no_license | sjason19/CrimeSpotter | ae64b891c282a4a3493b4edf0773762a43685f60 | 5f14c5520d544ce3ee984f1b96056a4a5122ba24 | refs/heads/master | 2022-04-08T11:44:33.159415 | 2020-04-06T06:18:14 | 2020-04-06T06:18:14 | 245,703,669 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | package com.crimespotter.api.event.model.naturaldisasterinfo;
import com.crimespotter.api.event.model.eventinfo.Event;
public class NaturalDisaster extends Event {
private String type;
private Integer magnitude;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getMagnitude() {
return magnitude;
}
public void setMagnitude(Integer magnitude) {
this.magnitude = magnitude;
}
}
| [
"[email protected]"
] | |
b538583c652127d1c9ad367c6e40913be608a898 | c101b501033e4242dbfe1d4ff936269cc8e68037 | /app/src/androidTest/java/cl/ubb/soyubb/ExampleInstrumentedTest.java | 4bd557d7b0f681e51e40516afbae7473dc98e116 | [] | no_license | Marco-Mena/SoyUBB | 2dc5854f43627c9fda3146868fb440049637275a | 4c6dd57da1112c4fcd2cb42c94e89ead1178f530 | refs/heads/master | 2020-08-10T06:30:58.564101 | 2019-10-10T22:07:36 | 2019-10-10T22:07:36 | 214,283,141 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 742 | java | package cl.ubb.soyubb;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("cl.ubb.soyubb", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
563523abfcddccefc3c07f5e50014dee3c73a01c | e9a51e7e9bbcfd0d1b93953a85511314336504d6 | /CustomerRest/src/main/java/com/scorpion/data/entity/Store.java | d1d88988b95d90ef38d1a748c740e6df9692b635 | [] | no_license | harpreet21/Spring-Jpa | acc970fa86688095cb8a3ea6e3da1b76596d10c2 | f4424881a7ef57d6a36d93e60645a2b912561ca5 | refs/heads/master | 2021-01-11T07:07:09.998174 | 2016-11-23T21:16:02 | 2016-11-23T21:16:02 | 72,067,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,171 | java | package com.scorpion.data.entity;
// Generated 25-Oct-2016 2:51:34 PM by Hibernate Tools 5.2.0.Beta1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
/**
* Store generated by hbm2java
*/
@Entity
@Table(name = "store", catalog = "sakila", uniqueConstraints = @UniqueConstraint(columnNames = "manager_staff_id"))
public class Store implements java.io.Serializable {
private Byte storeId;
private Address address;
private Staff staff;
private Date lastUpdate;
private Set<Staff> staffs = new HashSet<Staff>(0);
private Set<Inventory> inventories = new HashSet<Inventory>(0);
private Set<Customer> customers = new HashSet<Customer>(0);
public Store() {
}
public Store(Address address, Staff staff, Date lastUpdate) {
this.address = address;
this.staff = staff;
this.lastUpdate = lastUpdate;
}
public Store(Address address, Staff staff, Date lastUpdate, Set<Staff> staffs, Set<Inventory> inventories,
Set<Customer> customers) {
this.address = address;
this.staff = staff;
this.lastUpdate = lastUpdate;
this.staffs = staffs;
this.inventories = inventories;
this.customers = customers;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "store_id", unique = true, nullable = false)
public Byte getStoreId() {
return this.storeId;
}
public void setStoreId(Byte storeId) {
this.storeId = storeId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "address_id", nullable = false)
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "manager_staff_id", unique = true, nullable = false)
public Staff getStaff() {
return this.staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_update", nullable = false, length = 19)
public Date getLastUpdate() {
return this.lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "store")
public Set<Staff> getStaffs() {
return this.staffs;
}
public void setStaffs(Set<Staff> staffs) {
this.staffs = staffs;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "store")
public Set<Inventory> getInventories() {
return this.inventories;
}
public void setInventories(Set<Inventory> inventories) {
this.inventories = inventories;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "store")
public Set<Customer> getCustomers() {
return this.customers;
}
public void setCustomers(Set<Customer> customers) {
this.customers = customers;
}
}
| [
"[email protected]"
] | |
e18e57c60304a1c7d36935330eaa57a8f4d38206 | 7b83ca3883155db04dd1255fad910dff22ef34b7 | /src/test/java/com/rk/junit/firstapp/mockito/MockitoWithExamleTest.java | 2db0d3d49cf82bece65e0e3c72c7aa13a679eb07 | [] | no_license | RavikrianGoru/junit-mock | f003b3a566639c139dcb76f65834839be79be86f | 8b395dc5960a0438f6bed6ffe0ae90558c7b444c | refs/heads/main | 2023-03-29T18:33:58.038390 | 2021-04-02T18:01:14 | 2021-04-02T18:01:14 | 354,094,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,640 | java | package com.rk.junit.firstapp.mockito;
import java.util.Iterator;
import java.util.Properties;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MockitoWithExamleTest {
@Mock
Iterator<String> i;
Comparable<String> c;
@Test
public void testMoreThanOneReturns() {
Mockito.when(i.next()).thenReturn("A").thenReturn("B").thenReturn("C");
String results = i.next() + i.next() + i.next() + i.next();
// System.out.println(results);
Assertions.assertEquals("ABCC", results);
}
@Test
public void testReturnValueBasedOnMethodParam(@Mock Comparable<String> c)
{
Mockito.when(c.compareTo("ABC")).thenReturn(1);
Mockito.when(c.compareTo("XYZ")).thenReturn(2);
Assertions.assertEquals(1, c.compareTo("ABC"));
Assertions.assertEquals(2, c.compareTo("XYZ"));
}
@Test
public void testReturnValueBasedOnMethodParam1(@Mock Comparable<Integer> c)
{
Mockito.when(c.compareTo(ArgumentMatchers.isA(Integer.class))).thenReturn(0);
Assertions.assertEquals(0, c.compareTo(Integer.valueOf(5)));
}
@Test
public void testMockitoThrows()
{
Properties prop=Mockito.mock(Properties.class);
Mockito.when(prop.get(Mockito.anyString())).thenThrow(new IllegalArgumentException("stuff"));
Throwable exception =Assertions.assertThrows(IllegalArgumentException.class, ()->prop.get("A"));
Assertions.assertEquals("stuff", exception.getMessage());
}
}
| [
"[email protected]"
] | |
b98670ad7dbb9f5e8e2ca92880c575621d82baf1 | 11d48f6d4bb1db6827095c175db9a64e27fa66f3 | /bee/src/experimental/java/com/apisense/bee/utils/accessibilitySting/AccessibilityEventWrapper.java | 27eb47c66e13b1c221269e2751d57481982f8c74 | [] | no_license | APISENSE/bee-android | c95c26851cacdd5e1f236c6190a04987a9d22c60 | 7c26f3cee77e070a1eedfbb151444191eca024e8 | refs/heads/develop | 2020-04-16T02:27:57.100776 | 2018-03-08T13:36:57 | 2018-03-08T13:36:57 | 50,584,327 | 12 | 15 | null | 2018-02-16T15:20:52 | 2016-01-28T13:21:12 | Java | UTF-8 | Java | false | false | 1,719 | java | package com.apisense.bee.utils.accessibilitySting;
import android.support.annotation.Nullable;
import android.view.accessibility.AccessibilityEvent;
import java.util.Date;
/**
* Created by mnaseri on 11/15/17.
*/
public class AccessibilityEventWrapper {
public final String eventType;
public final long eventTime;
public final String packageName;
public final String className;
public final String text;
public final String contentDescription;
public final boolean isPassword;
public final boolean isChecked;
public final boolean isFullScreen;
public AccessibilityEventWrapper(AccessibilityEvent event, @Nullable String text) {
this.eventType = AccessibilityEvent.eventTypeToString(event.getEventType());
this.eventTime = event.getEventTime();
this.packageName = String.valueOf(event.getPackageName());
this.className = String.valueOf(event.getClassName());
if (!event.getText().isEmpty())
this.text = text == null ? String.valueOf(event.getText().get(0)) : text;
else
this.text = null;
this.contentDescription = String.valueOf(event.getContentDescription());
this.isPassword = event.isPassword();
this.isChecked = event.isChecked();
this.isFullScreen = event.isFullScreen();
}
public String toString() {
Date d = new Date(eventTime);
return " packageName:" + packageName + " eventType:" + eventType + " eventTime:" + d.toString() + " className:" + className + " text:" + text + " isPassword:" +
isPassword + " isChecked:" + isChecked + " isFullScreen:" + isFullScreen + " contentDescription:" + contentDescription;
}
}
| [
"[email protected]"
] | |
38ea9968f82eab8273723e4b271ecbb914e2e77d | dd20f8b98eeb1f8fdd1c2fe4f154cde744aa5e40 | /searching/FileReaderrandsearch.java | 50157f5573449ec83fea63bfb57fd8cd605a02f5 | [] | no_license | piyushkansal279/DAAproject | 31324cbc5c59587b9d34cbf3983bbd195e60e8a2 | 2bba8e9c63bb4e17ce5e5c05472135f54300b757 | refs/heads/master | 2020-05-15T22:16:53.899368 | 2019-04-26T08:48:19 | 2019-04-26T08:48:19 | 182,522,976 | 1 | 1 | null | 2019-04-21T11:10:27 | 2019-04-21T11:10:27 | null | UTF-8 | Java | false | false | 608 | java | package projc;
import java.io.*;
import java.util.*;
//import java.io.File;
//import java.io.FileNotFoundException;
import java.io.FileReader;
//import java.io.IOException;
class Filereaderr {
public static void main(String args[])throws Exception
{
String s;
FileReader fr=new FileReader("ankit.txt");
BufferedReader br=new BufferedReader(fr);
Scanner sc=new Scanner(System.in);
int count=0;
String keyword=sc.nextLine();
while ((s=br.readLine())!=null){
if(s.contains(keyword)) {
count++;
}
}
System.out.println("found times : "+count);
}
} | [
"[email protected]"
] | |
9e6503e3043317baaecd4c97d446fe4be85ff829 | 63ba97f555e3d262e6c76be0e160e59315c4a7b7 | /src/main/java/com/j256/simplecsv/processor/CsvProcessor.java | 1d247ad62634bde28ccf34f4bddc9429c0d33834 | [
"ISC"
] | permissive | fossabot/simplecsv | 456438f7cbb9dc5033b24199f5fbafddad89f1c0 | a20652b60f5eb5bea90cb04b56a25dfc535c39b9 | refs/heads/master | 2020-03-27T16:40:38.764174 | 2018-08-30T19:49:27 | 2018-08-30T19:49:27 | 146,799,230 | 0 | 0 | ISC | 2018-08-30T19:49:22 | 2018-08-30T19:49:21 | null | UTF-8 | Java | false | false | 51,029 | java | package com.j256.simplecsv.processor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import com.j256.simplecsv.common.CsvColumn;
import com.j256.simplecsv.common.CsvField;
import com.j256.simplecsv.converter.Converter;
import com.j256.simplecsv.converter.ConverterUtils;
import com.j256.simplecsv.converter.EnumConverter;
import com.j256.simplecsv.processor.ParseError.ErrorType;
/**
* CSV reader and writer.
*
* <p>
* <b>NOTE:</b> You need to set the entity class either in the constructor or with {@link #setEntityClass(Class)} or
* {@link #withEntityClass(Class)}. Then you need to do any {@link #registerConverter(Class, Converter)} or
* {@link #withConverter(Class, Converter)} calls before the processor gets configured. You can then let the processor
* be auto-configured on the first read/write method call or call {@link #initialize()} directly (or in spring).
* </p>
*
* @param <T>
* Entity type that we are processing. It should have a public no-arg constructor so it can be created by
* this library.
*
* @author graywatson
*/
@SuppressWarnings("deprecation")
public class CsvProcessor<T> {
/**
* Default separator character for columns. This can be changed with {@link #setColumnSeparator(char)}.
*/
public static final char DEFAULT_COLUMN_SEPARATOR = ',';
/**
* Default quote character for columns to wrap them if they have special characters. This can be changed with
* {@link #setColumnQuote(char)}.
*/
public static final char DEFAULT_COLUMN_QUOTE = '"';
/**
* Default line termination string to be written at the end of CSV lines. This can be changed with
* {@link #setLineTermination(String)}.
*/
public static final String DEFAULT_LINE_TERMINATION = System.getProperty("line.separator");
private static ColumnNameMatcher stringEqualsColumnNameMatcher = new ColumnNameMatcher() {
@Override
public boolean matchesColumnName(String definitionName, String csvName) {
return definitionName.equals(csvName);
}
};
private char columnSeparator = DEFAULT_COLUMN_SEPARATOR;
private char columnQuote = DEFAULT_COLUMN_QUOTE;
private String lineTermination = DEFAULT_LINE_TERMINATION;
private boolean allowPartialLines;
private boolean alwaysTrimInput;
private boolean headerValidation = true;
private boolean firstLineHeader = true;
private boolean flexibleOrder;
private boolean ignoreUnknownColumns;
private RowValidator<T> rowValidator;
private ColumnNameMatcher columnNameMatcher = stringEqualsColumnNameMatcher;
private Class<T> entityClass;
private Constructor<T> constructor;
private Callable<T> constructorCallable;
private final Map<Class<?>, Converter<?, ?>> converterMap = new HashMap<Class<?>, Converter<?, ?>>();
private List<ColumnInfo<Object>> allColumnInfos;
private Map<Integer, ColumnInfo<Object>> columnPositionInfoMap;
{
ConverterUtils.addInternalConverters(converterMap);
}
public CsvProcessor() {
// for spring
}
/**
* Constructs a processor with an entity class whose fields should be marked with {@link CsvColumn} annotations. The
* entity-class must also define a public no-arg contructor so the processor can instantiate them using reflection.
*/
public CsvProcessor(Class<T> entityClass) {
this.entityClass = entityClass;
}
/**
* Register a converter class for all instances of the class argument. The converter can also be specified with the
* {@link CsvColumn#converterClass()} annotation field.
*/
public <FT> void registerConverter(Class<FT> clazz, Converter<FT, ?> converter) {
converterMap.put(clazz, converter);
}
/**
* Register a converter class for all instances of the class argument. The converter can also be specified with the
* {@link CsvColumn#converterClass()} annotation field. Alternative way to do
* {@link #registerConverter(Class, Converter)}.
*/
public <FT> CsvProcessor<T> withConverter(Class<FT> clazz, Converter<FT, ?> converter) {
converterMap.put(clazz, converter);
return this;
}
/**
* This initializing the internal configuration information. It will self initialize if you start calling read/write
* methods but this is here if you are using the class concurrently and need to force the initialization.
*/
public CsvProcessor<T> initialize() {
configureEntityClass();
return this;
}
/**
* Read in all of the entities in the file passed in.
*
* @param file
* Where to read the header and entities from. It will be closed when the method returns.
* @param parseErrors
* If not null, any errors will be added to the collection and null will be returned. If validateHeader
* is true and the header does not match then no additional lines will be returned. If this is null then
* a ParseException will be thrown on parsing problems.
* @return A list of entities read in or null if validateHeader is true and the first-line header was not valid.
* @throws ParseException
* Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and
* an exception should not be thrown.
* @throws IOException
* If there are any IO exceptions thrown when reading.
*/
public List<T> readAll(File file, Collection<ParseError> parseErrors) throws IOException, ParseException {
checkEntityConfig();
return readAll(new FileReader(file), parseErrors);
}
/**
* Read in all of the entities in the reader passed in. It will use an internal buffered reader.
*
* @param reader
* Where to read the header and entities from. It will be closed when the method returns.
* @param parseErrors
* If not null, any errors will be added to the collection and null will be returned. If validateHeader
* is true and the header does not match then no additional lines will be returned. If this is null then
* a ParseException will be thrown on parsing problems.
* @return A list of entities read in or null if parseErrors is not null.
* @throws ParseException
* Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and
* an exception should not be thrown.
* @throws IOException
* If there are any IO exceptions thrown when reading.
*/
public List<T> readAll(Reader reader, Collection<ParseError> parseErrors) throws IOException, ParseException {
checkEntityConfig();
BufferedReader bufferedReader = new BufferedReaderLineCounter(reader);
try {
ParseError parseError = null;
// we do this to reuse the parse error objects if we can
if (parseErrors != null) {
parseError = new ParseError();
}
if (firstLineHeader) {
if (readHeader(bufferedReader, parseError) == null) {
if (parseError != null && parseError.isError()) {
parseErrors.add(parseError);
}
return null;
}
}
return readRows(bufferedReader, parseErrors);
} finally {
bufferedReader.close();
}
}
/**
* Read in a line and process it as a CSV header.
*
* @param bufferedReader
* Where to read the header from. It needs to be closed by the caller. Consider using
* {@link BufferedReaderLineCounter} to populate the line-number for parse errors.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return Array of header column names or null on error.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
* @throws IOException
* If there are any IO exceptions thrown when reading.
*/
public String[] readHeader(BufferedReader bufferedReader, ParseError parseError)
throws ParseException, IOException {
checkEntityConfig();
String header = bufferedReader.readLine();
if (header == null) {
if (parseError == null) {
throw new ParseException("no header line read", 0);
} else {
parseError.setErrorType(ErrorType.NO_HEADER);
parseError.setLineNumber(getLineNumber(bufferedReader));
return null;
}
}
String[] columns = processHeader(header, parseError, getLineNumber(bufferedReader));
if (columns == null) {
return null;
} else if (headerValidation && !validateHeaderColumns(columns, parseError, getLineNumber(bufferedReader))) {
if (parseError == null) {
throw new ParseException("header line is not valid: " + header, 0);
} else {
return null;
}
}
return columns;
}
/**
* Read in all of the entities in the reader passed in but without the header.
*
* @param bufferedReader
* Where to read the entries from. It needs to be closed by the caller. Consider using
* {@link BufferedReaderLineCounter} to populate the line-number for parse errors.
* @param parseErrors
* If not null, any errors will be added to the collection and null will be returned. If validateHeader
* is true and the header does not match then no additional lines will be returned. If this is null then
* a ParseException will be thrown on parsing problems.
* @return A list of entities read in or null if parseErrors is not null.
* @throws ParseException
* Thrown on any parsing problems. If parseErrors is not null then parse errors will be added there and
* an exception should not be thrown.
* @throws IOException
* If there are any IO exceptions thrown when reading.
*/
public List<T> readRows(BufferedReader bufferedReader, Collection<ParseError> parseErrors)
throws IOException, ParseException {
checkEntityConfig();
ParseError parseError = null;
// we do this to reuse the parse error objects if we can
if (parseErrors != null) {
parseError = new ParseError();
}
List<T> results = new ArrayList<T>();
while (true) {
if (parseError != null) {
parseError.reset();
}
T result = readRow(bufferedReader, parseError);
if (result != null) {
results.add(result);
} else if (parseError != null && parseError.isError()) {
// if there was an error then add it to the list
parseErrors.add(parseError);
// once we use it, we need to create another one
parseError = new ParseError();
} else {
// if no result and no error then EOF
return results;
}
}
}
/**
* Read an entity line from the reader.
*
* @param bufferedReader
* Where to read the row from. It needs to be closed by the caller. Consider using
* {@link BufferedReaderLineCounter} to populate the line-number for parse errors.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return Entity read in or null on EOF or error. Check {@link ParseError#isError()} to see if it was an error or
* EOF.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
* @throws IOException
* If there are any IO exceptions thrown when reading.
*/
public T readRow(BufferedReader bufferedReader, ParseError parseError) throws ParseException, IOException {
checkEntityConfig();
String line = bufferedReader.readLine();
if (line == null) {
return null;
} else {
return processRow(line, parseError, getLineNumber(bufferedReader));
}
}
/**
* Validate the header row against the configured header columns.
*
* @param line
* Line to process to get our validate our header.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return true if the header matched the column names configured here otherwise false.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
*/
public boolean validateHeader(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
String[] columns = processHeader(line, parseError);
return validateHeaderColumns(columns, parseError, 1);
}
/**
* Validate header columns returned by {@link #processHeader(String, ParseError)}.
*
* @param columns
* Array of columns to validate.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return true if the header matched the column names configured here otherwise false.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
*/
public boolean validateHeaderColumns(String[] columns, ParseError parseError) {
checkEntityConfig();
return validateHeaderColumns(columns, parseError, 1);
}
/**
* Process a header line and divide it up into a series of quoted columns.
*
* @param line
* Line to process looking for header.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return Returns an array of processed header names entity or null if an error and parseError has been set. The
* array will be the same length as the number of configured columns so some elements may be null.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
*/
public String[] processHeader(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
return processHeader(line, parseError, 1);
}
/**
* Read and process a line and return the associated entity.
*
* @param line
* to process to build our entity.
* @param parseError
* If not null, this will be set with the first parse error and it will return null. If this is null then
* a ParseException will be thrown instead.
* @return Returns a processed entity or null if an error and parseError has been set.
* @throws ParseException
* Thrown on any parsing problems. If parseError is not null then the error will be added there and an
* exception should not be thrown.
*/
public T processRow(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
return processRow(line, parseError, 1);
}
/**
* Write a collection of entities to the writer.
*
* @param file
* Where to write the header and entities.
* @param entities
* Collection of entities to write to the writer.
* @param writeHeader
* Set to true to write header at the start of the output file.
* @throws IOException
* If there are any IO exceptions thrown when writing.
*/
public void writeAll(File file, Collection<T> entities, boolean writeHeader) throws IOException {
writeAll(new FileWriter(file), entities, writeHeader);
}
/**
* Write a header and then the collection of entities to the writer.
*
* @param writer
* Where to write the header and entities. It will be closed before this method returns.
* @param entities
* Collection of entities to write to the writer.
* @param writeHeader
* Set to true to write header at the start of the writer.
* @throws IOException
* If there are any IO exceptions thrown when writing.
*/
public void writeAll(Writer writer, Collection<T> entities, boolean writeHeader) throws IOException {
checkEntityConfig();
BufferedWriter bufferedWriter = new BufferedWriter(writer);
try {
if (writeHeader) {
writeHeader(bufferedWriter, true);
}
for (T entity : entities) {
writeRow(bufferedWriter, entity, true);
}
} finally {
bufferedWriter.close();
}
}
/**
* Write the header line to the writer.
*
* @param bufferedWriter
* Where to write our header information.
* @param appendLineTermination
* Set to true to add the newline to the end of the line.
* @throws IOException
* If there are any IO exceptions thrown when writing.
*/
public void writeHeader(BufferedWriter bufferedWriter, boolean appendLineTermination) throws IOException {
checkEntityConfig();
bufferedWriter.write(buildHeaderLine(appendLineTermination));
}
/**
* Write an entity row to the writer.
*
* @param bufferedWriter
* Where to write our header information.
* @param entity
* The entity we are writing to the buffered writer.
* @param appendLineTermination
* Set to true to add the newline to the end of the line.
* @throws IOException
* If there are any IO exceptions thrown when writing.
*/
public void writeRow(BufferedWriter bufferedWriter, T entity, boolean appendLineTermination) throws IOException {
checkEntityConfig();
String line = buildLine(entity, appendLineTermination);
bufferedWriter.write(line);
}
/**
* Build and return a header string made up of quoted column names.
*
* @param appendLineTermination
* Set to true to add the newline to the end of the line.
*/
public String buildHeaderLine(boolean appendLineTermination) {
checkEntityConfig();
StringBuilder sb = new StringBuilder();
boolean first = true;
for (ColumnInfo<?> columnInfo : allColumnInfos) {
if (first) {
first = false;
} else {
sb.append(columnSeparator);
}
String header = columnInfo.getColumnName();
// need to protect the column if it contains a quote
if (header.indexOf(columnQuote) >= 0) {
writeQuoted(sb, header);
continue;
}
sb.append(columnQuote);
sb.append(header);
sb.append(columnQuote);
}
if (appendLineTermination) {
sb.append(lineTermination);
}
return sb.toString();
}
/**
* Convert the entity into a string of column values.
*
* @param appendLineTermination
* Set to true to add the newline to the end of the line.
*/
public String buildLine(T entity, boolean appendLineTermination) {
checkEntityConfig();
StringBuilder sb = new StringBuilder();
boolean first = true;
for (ColumnInfo<Object> columnInfo : allColumnInfos) {
if (first) {
first = false;
} else {
sb.append(columnSeparator);
}
Object value;
try {
value = columnInfo.getValue(entity);
} catch (Exception e) {
throw new IllegalStateException("Could not get value from entity field: " + columnInfo);
}
@SuppressWarnings("unchecked")
Converter<Object, Object> castConverter = (Converter<Object, Object>) columnInfo.getConverter();
String str = castConverter.javaToString(columnInfo, value);
boolean needsQuotes = columnInfo.isNeedsQuotes();
if (str == null) {
if (needsQuotes) {
sb.append(columnQuote).append(columnQuote);
}
continue;
}
// need to protect the column if it contains a quote
if (str.indexOf(columnQuote) >= 0) {
writeQuoted(sb, str);
continue;
}
if (!needsQuotes) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == columnSeparator || ch == '\r' || ch == '\n' || ch == '\t' || ch == '\b') {
needsQuotes = true;
break;
}
}
}
if (needsQuotes) {
sb.append(columnQuote);
}
sb.append(str);
if (needsQuotes) {
sb.append(columnQuote);
}
}
if (appendLineTermination) {
sb.append(lineTermination);
}
return sb.toString();
}
/**
* Class that we are processing.
*/
public void setEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
}
/**
* Class that we are processing. Alternative way to do {@link #setEntityClass(Class)}.
*/
public CsvProcessor<T> withEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
return this;
}
/**
* Set the a method that will construct the entity we are loading. This is used in case there are is not a no-arg
* constructor for the entity.
*/
public void setConstructorCallable(Callable<T> constructorCallable) {
this.constructorCallable = constructorCallable;
}
/**
* Set the a method that will construct the entity we are loading. This is used in case there are is not a no-arg
* constructor for the entity. Alternative way to do {@link #setConstructorCallable(Callable)}.
*/
public CsvProcessor<T> withConstructorCallable(Callable<T> constructorCallable) {
this.constructorCallable = constructorCallable;
return this;
}
/**
* String that separates columns in out CSV input and output.
*/
public void setColumnSeparator(char columnSeparator) {
this.columnSeparator = columnSeparator;
}
/**
* String that separates columns in out CSV input and output. Alternative way to do
* {@link #setColumnSeparator(char)}.
*/
public CsvProcessor<T> withColumnSeparator(char columnSeparator) {
this.columnSeparator = columnSeparator;
return this;
}
/**
* Quote character that is used to wrap each column.
*/
public void setColumnQuote(char columnQuote) {
this.columnQuote = columnQuote;
}
/**
* Quote character that is used to wrap each column. Alternative way to do {@link #setColumnQuote(char)}.
*/
public CsvProcessor<T> withColumnQuote(char columnQuote) {
this.columnQuote = columnQuote;
return this;
}
/**
* Sets the character which is written at the end of the row. Default is to use
* System.getProperty("line.separator");.
*/
public void setLineTermination(String lineTermination) {
this.lineTermination = lineTermination;
}
/**
* Sets the character which is written at the end of the row. Default is to use
* System.getProperty("line.separator");. Alternative way to do {@link #setLineTermination(String)}.
*/
public CsvProcessor<T> withLineTermination(String lineTermination) {
this.lineTermination = lineTermination;
return this;
}
/**
* Set to true to allow lines that do not have values for all of the columns. Otherwise an IllegalArgumentException
* is thrown.
*/
public void setAllowPartialLines(boolean allowPartialLines) {
this.allowPartialLines = allowPartialLines;
}
/**
* Set to true to allow lines that do not have values for all of the columns. Otherwise an IllegalArgumentException
* is thrown. Alternative way to do {@link #setAllowPartialLines(boolean)}.
*/
public CsvProcessor<T> withAllowPartialLines(boolean allowPartialLines) {
this.allowPartialLines = allowPartialLines;
return this;
}
/**
* Set to true to always call {@link String#trim()} on data input columns to remove any spaces from the start or
* end.
*/
public void setAlwaysTrimInput(boolean alwaysTrimInput) {
this.alwaysTrimInput = alwaysTrimInput;
}
/**
* Set to true to always call {@link String#trim()} on data input columns to remove any spaces from the start or
* end. Alternative way to do {@link #setAlwaysTrimInput(boolean)}.
*/
public CsvProcessor<T> withAlwaysTrimInput(boolean alwaysTrimInput) {
this.alwaysTrimInput = alwaysTrimInput;
return this;
}
/**
* Set to false to not validate the header when it is read in. Default is true.
*/
public void setHeaderValidation(boolean headerValidation) {
this.headerValidation = headerValidation;
}
/**
* Set to false to not validate the header when it is read in. Default is true.
*/
public CsvProcessor<T> withHeaderValidation(boolean headerValidation) {
this.headerValidation = headerValidation;
return this;
}
/**
* Set to false if the first line is a header line to be processed. Default is true.
*/
public void setFirstLineHeader(boolean firstLineHeader) {
this.firstLineHeader = firstLineHeader;
}
/**
* Set to false if the first line is a header line to be processed. Default is true.
*/
public CsvProcessor<T> withFirstLineHeader(boolean firstLineHeader) {
this.firstLineHeader = firstLineHeader;
return this;
}
/**
* Set the column name matcher class which will be used to see if the column from the CSV file matches the
* definition name. This can be used if you have optional suffix characters such as "*" or something. Default is
* {@link String#equals(Object)}.
*/
public void setColumnNameMatcher(ColumnNameMatcher columnNameMatcher) {
this.columnNameMatcher = columnNameMatcher;
}
/**
* Set the column name matcher class which will be used to see if the column from the CSV file matches the
* definition name. This can be used if you have optional suffix characters such as "*" or something. Default is
* {@link String#equals(Object)}.
*/
public CsvProcessor<T> withColumnNameMatcher(ColumnNameMatcher columnNameMatcher) {
this.columnNameMatcher = columnNameMatcher;
return this;
}
/**
* Set to true if the order of the input columns is flexible and does not have to match the order of the definition
* fields in the entity. The order is determined by the header columns so their must be a header. Default is false.
*
* <b>WARNING:</b> If you are using flexible ordering, this CsvProcessor cannot be used with multiple files at the
* same time since the column orders are dynamic depending on the input file being read.
*/
public void setFlexibleOrder(boolean flexibleOrder) {
this.flexibleOrder = flexibleOrder;
}
/**
* Set to true if the order of the input columns is flexible and does not have to match the order of the definition
* fields in the entity. The order is determined by the header columns so their must be a header. Default is false.
*
* <b>WARNING:</b> If you are using flexible ordering, this CsvProcessor cannot be used with multiple files at the
* same time since the column orders are dynamic depending on the input file being read.
*/
public CsvProcessor<T> withFlexibleOrder(boolean flexibleOrder) {
this.flexibleOrder = flexibleOrder;
return this;
}
/**
* Set to true to ignore columns that are not know to the configuration. Default is to raise an error.
*
* <b>WARNING:</b> If you are using unknown columns, this CsvProcessor cannot be used with multiple files at the
* same time since the column position is dynamic depending on the input file being read.
*/
public void setIgnoreUnknownColumns(boolean ignoreUnknownColumns) {
this.ignoreUnknownColumns = ignoreUnknownColumns;
}
/**
* Set to true to ignore columns that are not know to the configuration. Default is to raise an error.
*
* <b>WARNING:</b> If you are using unknown columns, this CsvProcessor cannot be used with multiple files at the
* same time since the column position is dynamic depending on the input file being read.
*/
public CsvProcessor<T> withIgnoreUnknownColumns(boolean ignoreUnknownColumns) {
this.ignoreUnknownColumns = ignoreUnknownColumns;
return this;
}
/**
* Set the validator which will validate each entity after it has been parsed.
*/
public void setRowValidator(RowValidator<T> rowValidator) {
this.rowValidator = rowValidator;
}
/**
* Set the validator which will validate each entity after it has been parsed.
*/
public CsvProcessor<T> withRowValidator(RowValidator<T> rowValidator) {
this.rowValidator = rowValidator;
return this;
}
private boolean validateHeaderColumns(String[] columns, ParseError parseError, int lineNumber) {
boolean result = true;
Map<String, ColumnInfo<Object>> columnNameToInfoMap = new HashMap<String, ColumnInfo<Object>>();
for (ColumnInfo<Object> columnInfo : allColumnInfos) {
columnNameToInfoMap.put(columnInfo.getColumnName(), columnInfo);
}
Map<Integer, ColumnInfo<Object>> columnPositionInfoMap = new HashMap<Integer, ColumnInfo<Object>>();
int lastColumnInfoPosition = -1;
for (int i = 0; i < columns.length; i++) {
String headerColumn = columns[i];
ColumnInfo<Object> matchedColumnInfo = null;
if (columnNameMatcher == null) {
matchedColumnInfo = columnNameToInfoMap.get(headerColumn);
} else {
// have to do a N^2 search because we are using a matcher not just string equals
for (ColumnInfo<Object> columnInfo : allColumnInfos) {
if (columnNameMatcher.matchesColumnName(columnInfo.getColumnName(), headerColumn)) {
matchedColumnInfo = columnInfo;
break;
}
}
}
if (matchedColumnInfo == null) {
if (!ignoreUnknownColumns) {
if (parseError != null) {
parseError.setErrorType(ErrorType.INVALID_HEADER);
parseError.setMessage("column name '" + headerColumn + "' is unknown");
parseError.setLineNumber(lineNumber);
}
result = false;
}
} else {
if (!flexibleOrder && matchedColumnInfo.getPosition() <= lastColumnInfoPosition) {
if (parseError != null) {
parseError.setErrorType(ErrorType.INVALID_HEADER);
parseError.setMessage("column name '" + headerColumn + "' is not in the proper order");
assignParseErrorFields(parseError, matchedColumnInfo, null);
parseError.setLineNumber(lineNumber);
}
result = false;
} else {
lastColumnInfoPosition = matchedColumnInfo.getPosition();
}
// remove it from the map once we've matched with it
columnNameToInfoMap.remove(matchedColumnInfo.getColumnName());
columnPositionInfoMap.put(i, matchedColumnInfo);
}
}
// did the column position information change
if (!columnPositionInfoMap.equals(this.columnPositionInfoMap)) {
this.columnPositionInfoMap = columnPositionInfoMap;
}
// now look for must-be-supplied columns
for (ColumnInfo<Object> columnInfo : columnNameToInfoMap.values()) {
if (columnInfo.isMustBeSupplied()) {
if (parseError != null) {
parseError.setErrorType(ErrorType.INVALID_HEADER);
parseError.setMessage(
"column '" + columnInfo.getColumnName() + "' must be supplied and was not specified");
assignParseErrorFields(parseError, columnInfo, null);
parseError.setLineNumber(lineNumber);
}
result = false;
}
}
// if we have an error then reset the columnCount
if (!result) {
resetColumnPositionInfoMap();
}
return result;
}
private String[] processHeader(String line, ParseError parseError, int lineNumber) throws ParseException {
StringBuilder sb = new StringBuilder(32);
int linePos = 0;
ParseError localParseError = parseError;
if (localParseError == null) {
localParseError = new ParseError();
}
List<String> headerColumns = new ArrayList<String>();
while (true) {
boolean atEnd = (linePos == line.length());
localParseError.reset();
sb.setLength(0);
if (linePos < line.length() && line.charAt(linePos) == columnQuote) {
linePos = processQuotedColumn(line, lineNumber, linePos, null, null, sb, localParseError);
} else {
linePos = processUnquotedColumn(line, lineNumber, linePos, null, null, sb, localParseError);
}
if (localParseError.isError()) {
if (localParseError == parseError) {
// if we pass in an error then it gets set and we return null
return null;
} else {
// if no error passed in then we throw
throw new ParseException("Problems parsing header line at position " + linePos + " ("
+ localParseError + "): " + line, linePos);
}
}
if (sb.length() > 0) {
headerColumns.add(sb.toString());
}
if (atEnd) {
break;
}
}
return headerColumns.toArray(new String[headerColumns.size()]);
}
private T processRow(String line, ParseError parseError, int lineNumber) throws ParseException {
T entity = processRowInner(line, parseError, lineNumber);
if (entity != null && rowValidator != null) {
ParseError localParseError = parseError;
if (localParseError == null) {
localParseError = new ParseError();
}
try {
rowValidator.validateRow(line, lineNumber, entity, localParseError);
} catch (ParseException pe) {
if (localParseError != parseError) {
throw pe;
}
localParseError.setErrorType(ErrorType.INVALID_ENTITY);
localParseError.setMessage(pe.getMessage());
}
}
if (parseError != null && parseError.isError()) {
if (parseError.getLine() == null) {
parseError.setLine(line);
}
if (parseError.getLineNumber() == 0) {
parseError.setLineNumber(lineNumber);
}
if (parseError.getMessage() == null) {
parseError.setMessage(parseError.getErrorType().getTypeMessage());
}
// force the entity to be null
entity = null;
}
return entity;
}
private T processRowInner(String line, ParseError parseError, int lineNumber) throws ParseException {
T target = constructEntity();
int linePos = 0;
ParseError localParseError = parseError;
if (localParseError == null) {
localParseError = new ParseError();
}
int columnCount = 0;
while (true) {
ColumnInfo<Object> columnInfo = columnPositionInfoMap.get(columnCount);
if (columnInfo == null && !ignoreUnknownColumns) {
break;
}
// we have to do this because a blank column may be ok
boolean atEnd = (linePos == line.length());
localParseError.reset();
if (linePos < line.length() && line.charAt(linePos) == columnQuote) {
linePos = processQuotedColumn(line, lineNumber, linePos, columnInfo, target, null, localParseError);
} else {
linePos = processUnquotedColumn(line, lineNumber, linePos, columnInfo, target, null, localParseError);
}
if (localParseError.isError()) {
if (localParseError == parseError) {
// parseError has the error information
return null;
} else {
throw new ParseException(
"Problems parsing line at position " + linePos + " for type "
+ columnInfo.getType().getSimpleName() + " (" + localParseError + "): " + line,
linePos);
}
}
columnCount++;
if (atEnd) {
break;
}
// NOTE: we can't break here if we are at the end of line because might be blank column
}
if (columnCount < columnPositionInfoMap.size() && !allowPartialLines) {
if (parseError == null) {
throw new ParseException("Line does not have " + columnPositionInfoMap.size() + " columns: " + line,
linePos);
} else {
parseError.setErrorType(ErrorType.TRUNCATED_LINE);
parseError.setMessage("Line does not have " + columnPositionInfoMap.size() + " columns");
parseError.setLinePos(linePos);
return null;
}
}
if (linePos < line.length() && !ignoreUnknownColumns) {
if (parseError == null) {
throw new ParseException(
"Line has extra information past last column at position " + linePos + ": " + line, linePos);
} else {
parseError.setErrorType(ErrorType.TOO_MANY_COLUMNS);
parseError.setMessage("Line has extra information past last column at position " + linePos);
parseError.setLinePos(linePos);
return null;
}
}
return target;
}
private T constructEntity() throws ParseException {
try {
if (constructorCallable == null) {
return constructor.newInstance();
} else {
return constructorCallable.call();
}
} catch (Exception e) {
ParseException parseException = new ParseException("Could not construct instance of " + entityClass, 0);
parseException.initCause(e);
throw parseException;
}
}
private void checkEntityConfig() {
if (allColumnInfos == null) {
configureEntityClass();
}
}
private void configureEntityClass() {
if (entityClass == null) {
throw new IllegalStateException("Entity class not configured for CSV processor");
}
Map<String, ColumnInfo<Object>> fieldNameMap = new LinkedHashMap<String, ColumnInfo<Object>>();
for (Class<?> clazz = entityClass; clazz != Object.class; clazz = clazz.getSuperclass()) {
for (Field field : clazz.getDeclaredFields()) {
if (fieldNameMap.containsKey(field.getName())) {
continue;
}
CsvField csvField = field.getAnnotation(CsvField.class);
CsvColumn csvColumn = field.getAnnotation(CsvColumn.class);
if (csvField == null && csvColumn == null) {
continue;
}
addColumnInfo(fieldNameMap, csvColumn, csvField, field.getName(), field.getType(), field, null, null);
field.setAccessible(true);
}
}
// now process the get/set methods
Map<String, Method> otherMethodMap = new HashMap<String, Method>();
for (Class<?> clazz = entityClass; clazz != Object.class; clazz = clazz.getSuperclass()) {
for (Method method : clazz.getMethods()) {
CsvColumn csvColumn = method.getAnnotation(CsvColumn.class);
if (csvColumn == null) {
continue;
}
Method getMethod = null;
Method setMethod = null;
String fieldName = method.getName();
if (fieldName.length() > 3 && fieldName.startsWith("get")) {
fieldName = Character.toLowerCase(fieldName.charAt(3)) + fieldName.substring(4);
getMethod = method;
} else if (fieldName.length() > 2 && fieldName.startsWith("is")) {
fieldName = Character.toLowerCase(fieldName.charAt(2)) + fieldName.substring(3);
getMethod = method;
} else if (fieldName.length() > 3 && fieldName.startsWith("set")) {
fieldName = Character.toLowerCase(fieldName.charAt(3)) + fieldName.substring(4);
setMethod = method;
}
if (fieldNameMap.containsKey(fieldName)) {
continue;
}
Method otherMethod = otherMethodMap.remove(fieldName);
if (otherMethod == null) {
otherMethodMap.put(fieldName, method);
continue;
}
// figure out which method is the right one
if (getMethod == null) {
getMethod = otherMethod;
} else {
setMethod = otherMethod;
}
// test the types
if (getMethod.getReturnType() == null || getMethod.getReturnType() == void.class) {
throw new IllegalStateException("Get method must return a type, not void: " + getMethod);
}
Class<?>[] setParamTypes = setMethod.getParameterTypes();
if (setParamTypes.length != 1) {
throw new IllegalStateException("Get method must have exactly 1 argument: " + setMethod);
}
if (setParamTypes[0] != getMethod.getReturnType()) {
throw new IllegalStateException("Get method return type " + getMethod.getReturnType()
+ " should match set method parameter type " + setParamTypes[0] + " for field "
+ fieldName);
}
// NOTE: it is the CsvColumn on the 2nd method that is really the one that is used
addColumnInfo(fieldNameMap, csvColumn, null, fieldName, getMethod.getReturnType(), null, getMethod,
setMethod);
}
}
if (!otherMethodMap.isEmpty()) {
Method firstMethod = otherMethodMap.values().iterator().next();
throw new IllegalStateException(
"Must mark both the get/is and set methods with CsvColumn annotation, not just: " + firstMethod);
}
if (fieldNameMap.isEmpty()) {
throw new IllegalArgumentException("Could not find any exposed CSV fields in: " + entityClass);
}
this.allColumnInfos = assignColumnPositions(fieldNameMap);
resetColumnPositionInfoMap();
if (constructorCallable == null) {
try {
this.constructor = entityClass.getConstructor();
} catch (Exception e) {
throw new IllegalStateException(
"No callable configured or could not find public no-arg constructor for: " + entityClass);
}
}
}
private List<ColumnInfo<Object>> assignColumnPositions(Map<String, ColumnInfo<Object>> fieldNameMap) {
// run through the columns and track the columns that come after others
Map<ColumnInfo<Object>, ColumnInfo<Object>> afterMap = new HashMap<ColumnInfo<Object>, ColumnInfo<Object>>();
Set<ColumnInfo<Object>> afterDestSet = new HashSet<ColumnInfo<Object>>();
for (ColumnInfo<Object> columnInfo : fieldNameMap.values()) {
if (columnInfo.getAfterColumn() == null) {
continue;
}
// lookup the column by name
ColumnInfo<Object> previousColumnInfo = fieldNameMap.get(columnInfo.getAfterColumn());
if (previousColumnInfo == null) {
throw new IllegalArgumentException(
"Could not find an after column with the name: " + columnInfo.getAfterColumn());
}
/*
* Add this to the end of the fields already in the after list for this field (first one wins). We track the
* field number so we don't get into some sort of infinite loop.
*/
int fieldCount = 0;
while (true) {
ColumnInfo<Object> previousNext = afterMap.get(previousColumnInfo);
if (previousNext == null) {
break;
}
previousColumnInfo = previousNext;
if (++fieldCount > fieldNameMap.size()) {
throw new IllegalStateException(
"Some sort of after-column loop has been detected, check all after-column settings");
}
}
afterMap.put(previousColumnInfo, columnInfo);
afterDestSet.add(columnInfo);
}
// go back and build our list of column infos
List<ColumnInfo<Object>> columnInfos = new ArrayList<ColumnInfo<Object>>(fieldNameMap.size());
for (ColumnInfo<Object> columnInfo : fieldNameMap.values()) {
// if the column does not come after any other column then spit it out in order
if (afterDestSet.contains(columnInfo)) {
continue;
}
// also spit out any of the columns that come after it according to after-column
for (; columnInfo != null; columnInfo = afterMap.get(columnInfo)) {
columnInfos.add(columnInfo);
if (columnInfos.size() > fieldNameMap.size()) {
throw new IllegalStateException(
"Some sort of after-column loop has been detected, check all after-column settings");
}
}
}
/*
* Now we need to make sure that we don't have a gap in the after-column points. This could happen because of:
* value1, value2 comes after value3, value3 comes after value2.
*/
if (columnInfos.size() < fieldNameMap.size()) {
throw new IllegalStateException("Some sort of after-column gap has been detected because only configured "
+ columnInfos.size() + " fields but expected " + fieldNameMap.size());
}
int fieldCount = 0;
for (ColumnInfo<Object> columnInfo : columnInfos) {
columnInfo.setPosition(fieldCount++);
}
return columnInfos;
}
private void addColumnInfo(Map<String, ColumnInfo<Object>> fieldNameMap, CsvColumn csvColumn, CsvField csvField,
String fieldName, Class<?> type, Field field, Method getMethod, Method setMethod) {
Converter<?, ?> converter = converterMap.get(type);
// test for the enum converter specifically
if (converter == null && type.isEnum()) {
converter = EnumConverter.getSingleton();
}
// NOTE: converter could be null in which case the CsvColumn.converterClass must be set
@SuppressWarnings("unchecked")
Converter<Object, Object> castConverter = (Converter<Object, Object>) converter;
ColumnInfo<Object> columnInfo;
@SuppressWarnings("unchecked")
Class<Object> castType = (Class<Object>) type;
if (csvField == null) {
columnInfo = ColumnInfo.fromAnnotation(csvColumn, fieldName, castType, field, getMethod, setMethod,
castConverter);
} else {
columnInfo = ColumnInfo.fromAnnotation(csvField, fieldName, castType, field, getMethod, setMethod,
castConverter);
}
fieldNameMap.put(columnInfo.getColumnName(), columnInfo);
}
private void resetColumnPositionInfoMap() {
Map<Integer, ColumnInfo<Object>> columnPositionInfoMap = new HashMap<Integer, ColumnInfo<Object>>();
int columnCount = 0;
for (ColumnInfo<Object> columnInfo : allColumnInfos) {
columnPositionInfoMap.put(columnCount, columnInfo);
columnCount++;
}
this.columnPositionInfoMap = columnPositionInfoMap;
}
private int processQuotedColumn(String line, int lineNumber, int linePos, ColumnInfo<Object> columnInfo,
Object target, StringBuilder headerSb, ParseError parseError) {
// linePos is pointing at the first quote, move past it
linePos++;
int columnStart = linePos;
int sectionStart = linePos;
int sectionEnd = linePos;
StringBuilder sb = null;
while (linePos < line.length()) {
// look for the next quote
sectionEnd = line.indexOf(columnQuote, linePos);
if (sectionEnd < 0) {
parseError.setErrorType(ErrorType.TRUNCATED_COLUMN);
parseError.setMessage("Column not terminated with quote '" + columnQuote + "'");
assignParseErrorFields(parseError, columnInfo, null);
parseError.setLinePos(linePos);
return line.length();
}
linePos = sectionEnd + 1;
if (linePos == line.length()) {
break;
} else if (line.charAt(linePos) == columnSeparator) {
linePos++;
break;
}
// must have a quote following a quote if there wasn't a columnSeparator
if (line.charAt(linePos) != columnQuote) {
parseError.setErrorType(ErrorType.INVALID_FORMAT);
parseError.setMessage(
"quote '" + columnQuote + "' is not followed up separator '" + columnSeparator + "'");
assignParseErrorFields(parseError, columnInfo, null);
parseError.setLinePos(linePos);
return linePos;
}
sectionEnd = linePos;
// move past possibly end quote
linePos++;
if (linePos == line.length()) {
break;
}
if (line.charAt(linePos) == columnSeparator) {
// move past the comma
linePos++;
break;
}
// need to build the string dynamically now
if (sb == null) {
sb = new StringBuilder(32);
}
// add to the string-builder the column + 1 quote
sb.append(line, sectionStart, sectionEnd);
// line-pos is pointing past 2nd (maybe 3rd) quote
sectionStart = linePos;
}
if (sb == null) {
if (headerSb == null) {
String columnStr = line.substring(sectionStart, sectionEnd);
if (columnInfo != null) {
extractAndAssignValue(line, lineNumber, columnInfo, columnStr, columnStart, target, parseError);
}
} else {
headerSb.append(line, sectionStart, sectionEnd);
}
} else {
sb.append(line, sectionStart, sectionEnd);
String str = sb.toString();
if (headerSb == null) {
if (columnInfo != null) {
extractAndAssignValue(str, lineNumber, columnInfo, str, columnStart, target, parseError);
}
} else {
headerSb.append(str);
}
}
return linePos;
}
private int processUnquotedColumn(String line, int lineNumber, int linePos, ColumnInfo<Object> columnInfo,
Object target, StringBuilder headerSb, ParseError parseError) {
int columnStart = linePos;
linePos = line.indexOf(columnSeparator, columnStart);
if (linePos < 0) {
linePos = line.length();
}
if (headerSb == null) {
String columnStr = line.substring(columnStart, linePos);
if (columnInfo != null) {
extractAndAssignValue(line, lineNumber, columnInfo, columnStr, columnStart, target, parseError);
}
} else {
headerSb.append(line, columnStart, linePos);
}
if (linePos < line.length()) {
// skip over the separator
linePos++;
}
return linePos;
}
private void writeQuoted(StringBuilder sb, String str) {
sb.append(columnQuote);
int start = 0;
while (true) {
int linePos = str.indexOf(columnQuote, start);
if (linePos < 0) {
sb.append(str, start, str.length());
break;
}
// move past the quote so we can output it
linePos++;
sb.append(str, start, linePos);
// output another quote
sb.append(columnQuote);
start = linePos;
}
sb.append(columnQuote);
}
/**
* Extract a value from the line, convert it into its java equivalent, and assign it to our target object.
*/
private void extractAndAssignValue(String line, int lineNumber, ColumnInfo<Object> columnInfo, String columnStr,
int linePos, Object target, ParseError parseError) {
Object value = extractValue(line, lineNumber, columnInfo, columnStr, linePos, target, parseError);
if (value == null) {
assignParseErrorFields(parseError, columnInfo, columnStr);
// either error or no value
return;
}
try {
columnInfo.setValue(target, value);
} catch (Exception e) {
parseError.setErrorType(ErrorType.INTERNAL_ERROR);
parseError
.setMessage("setting value for field '" + columnInfo.getFieldName() + "' error: " + e.getMessage());
assignParseErrorFields(parseError, columnInfo, columnStr);
parseError.setLinePos(linePos);
}
}
/**
* Extract a value from the line and convert it into its java equivalent.
*/
private Object extractValue(String line, int lineNumber, ColumnInfo<Object> columnInfo, String columnStr,
int linePos, Object target, ParseError parseError) {
Converter<Object, ?> converter = columnInfo.getConverter();
if (alwaysTrimInput || columnInfo.isTrimInput() || converter.isAlwaysTrimInput()) {
columnStr = columnStr.trim();
}
if (columnStr.isEmpty() && columnInfo.getDefaultValue() != null) {
columnStr = columnInfo.getDefaultValue();
}
if (columnStr.isEmpty() && columnInfo.isMustNotBeBlank()) {
parseError.setErrorType(ErrorType.MUST_NOT_BE_BLANK);
parseError.setMessage("field '" + columnInfo.getFieldName() + "' must not be blank");
assignParseErrorFields(parseError, columnInfo, columnStr);
parseError.setLinePos(linePos);
return null;
}
try {
return converter.stringToJava(line, lineNumber, linePos, columnInfo, columnStr, parseError);
} catch (ParseException e) {
parseError.setErrorType(ErrorType.INVALID_FORMAT);
parseError.setMessage("field '" + columnInfo.getFieldName() + "' parse-error: " + e.getMessage());
parseError.setLinePos(linePos);
return null;
} catch (Exception e) {
parseError.setErrorType(ErrorType.INTERNAL_ERROR);
parseError.setMessage("field '" + columnInfo.getFieldName() + "' error: " + e.getMessage());
parseError.setLinePos(linePos);
return null;
}
}
private void assignParseErrorFields(ParseError parseError, ColumnInfo<Object> columnInfo, String columnStr) {
if (parseError != null && parseError.isError() && columnInfo != null) {
parseError.setColumnName(columnInfo.getColumnName());
if (columnStr != null) {
parseError.setColumnValue(columnStr);
}
parseError.setColumnType(columnInfo.getType());
}
}
private int getLineNumber(BufferedReader bufferedReader) {
if (bufferedReader instanceof BufferedReaderLineCounter) {
return ((BufferedReaderLineCounter) bufferedReader).getLineCount();
} else {
return 1;
}
}
}
| [
"[email protected]"
] | |
7469d1721fb71df2f0ef54ec61105fe6815da4f9 | 16b2e5a479dad04c1cd8eb83fdf0fba4f2fc9357 | /src/com/javarush/test/level20/lesson07/task02/Solution.java | bfc82a02d5982379bdc9981d86d0af3e9679511a | [] | no_license | jtumano/JavaRushHomeWork | 84823c5148b44f9e861a4f921f07618d0d26048c | b9ed19341d10eced119039ffb68cec9586118019 | refs/heads/master | 2021-01-14T08:25:42.390389 | 2017-01-15T16:41:26 | 2017-01-15T16:41:26 | 49,190,563 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,059 | java | package com.javarush.test.level20.lesson07.task02;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/* OutputToConsole
Класс OutputToConsole должен сериализоваться с помощью интерфейса Externalizable.
Подумайте, какие поля не нужно сериализовать.
Исправьте ошибку.
Сигнатуры методов менять нельзя.
*/
public class Solution {
public static String greeting = "Hello world";
/**
* OutputToConsole is the inner base class for improving your attentiveness.
* An OutputToConsole object encapsulates the information needed
* for the displaying [greeting] variable to the console by character.
* @author JavaRush
*/
public static class OutputToConsole implements Externalizable {
private int i = 8;
/**
* @param out A stream for an externalization
* @throws java.io.IOException
*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(i);
}
/**
* @param in A stream for a de-externalization
* @throws java.io.IOException
* @throws ClassNotFoundException
*/
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
i = in.readInt();
}
public OutputToConsole()
{
}
/**
* Class constructor specifying fake private field [i].
*/
public OutputToConsole(int ii) {
this.i = ii;
}
/**
* Outputs to the console a static field of Solution class [greeting].
* Has to use [charAt] method of String class
*/
public void outputToConsole(int ii) {
for (int i = 0; i < greeting.length(); i++) {
System.out.write(greeting.charAt(i));
}
}
}
}
| [
"[email protected]"
] | |
9bdd6d6861633082b70f249fba34dbbee381ffff | 95ffc8892e10ef91935f50952483927cb74e5a16 | /Project_ChaChaCha/app/src/main/java/com/example/project_chachacha/template/src/shop/shopInfo/ShopReview/ReviewItemData.java | 48e3b0372f05c60fb96acf6a967b871a779729f3 | [] | no_license | softsquared-sky/chachacha-tony | e02277518c7f84156c4a7e954b5b8034383fb465 | 71707d76588a5cc4a147acce3126bb8cbd744979 | refs/heads/master | 2020-07-10T01:30:32.913840 | 2019-09-07T18:07:40 | 2019-09-07T18:07:40 | 204,131,251 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 745 | java | package com.example.project_chachacha.template.src.shop.shopInfo.ShopReview;
public class ReviewItemData {
private String name;
private int rate;
private String content;
public ReviewItemData(String name, int rate, String content) {
this.name = name;
this.rate = rate;
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| [
"[email protected]"
] | |
4bed4a084f362e57a881c8d362545c6d0f0d557d | 26d79a6b31cbde029dd236f09d308ce3b3afa3ab | /bundles/de.fzi.replica.old/src/de/fzi/replica/util/OWLOntologyToOWLMutableOntologyCopier.java | 4ec903e5061a87ba51519ca60401b24e4a79216e | [
"Apache-2.0"
] | permissive | j3w7/replica-framework | ce514486b98ffb77fa294df20537c5b6ceb21989 | f534155577ed700b895dd6e4760e32d09a44fc8a | refs/heads/master | 2020-03-31T00:42:15.409258 | 2012-04-22T10:30:43 | 2012-04-22T10:30:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,090 | java | /*
Copyright 2011 Jan Novacek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.fzi.replica.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLMutableOntology;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyChange;
/**
* Very simple utility class to copy all axioms into an existing OWLMutableOntology.
*
* @author Jan Novacek [email protected]
* @version version 1.0, 20.10.2010
*
*/
public class OWLOntologyToOWLMutableOntologyCopier extends OWLOntologyCopier<OWLOntology, OWLMutableOntology> {
// Maybe we want filters some day, so dont use static methods
@Override
public void copy(Set<OWLOntology> sources, OWLMutableOntology target) {
for(OWLOntology source : sources) {
/*
* TODO set the way this is done in a global property
* Beware: this has a major impact on replication speed!
* With current (25.10.10) settings, even when replicating
* just locally some test cases fail because of test timings.
*/
// One by one
// for(OWLAxiom axiom : source.getAxioms()) {
// AddAxiom addAxiom = new AddAxiom(target, axiom);
// target.applyChange(addAxiom);
// }
// // Aggregate changes
List<OWLOntologyChange> changes = new LinkedList<OWLOntologyChange>();
for(OWLAxiom axiom : source.getAxioms()) {
changes.add(new AddAxiom(target, axiom));
}
target.applyChanges(changes);
}
}
}
| [
"novacek@69b9e6ae-700c-0410-834d-e0df161635a7"
] | novacek@69b9e6ae-700c-0410-834d-e0df161635a7 |
3ee020cd654da4d8b930aba6fe18568c4f8c0de3 | b0eb0f209570197a76f0795366f5c0bfc4e65819 | /app/src/androidTest/java/origami/origamilogin/ExampleInstrumentedTest.java | bb0d3f6a18e4b5576f41aef59a3b62a333d26b66 | [] | no_license | mshehzad1/FacebookLogin | dad71bc4d5aa635057bcf05e0e0842216feffe73 | 27e9f8bc4e30586ff9c3f023c66afadd9a869ac9 | refs/heads/master | 2021-05-11T09:52:53.825193 | 2018-01-23T11:38:46 | 2018-01-23T11:38:46 | 118,087,995 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java | package origami.origamilogin;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("origami.origamilogin", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
e75e263a3ed1935ac7510ac7461bbada12910628 | c405671aeec556be37c9ff795887e8e7730a631a | /config/config-api/src/main/java/com/thoughtworks/go/security/CryptoException.java | 31e774bcce83ac1d3f24fbda575dde8fd5c449c1 | [
"Apache-2.0"
] | permissive | naveenbhaskar/gocd | e13efb06d25cd65e01b53af5256db9bd2484143f | eacc5b10804cc9d9fb09396a76ea25141aedea4c | refs/heads/master | 2020-04-06T04:26:59.167258 | 2019-06-03T10:26:08 | 2019-06-03T10:26:08 | 66,810,821 | 1 | 0 | Apache-2.0 | 2018-08-28T04:08:02 | 2016-08-29T04:17:05 | Java | UTF-8 | Java | false | false | 842 | java | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.security;
public class CryptoException extends Exception {
public CryptoException(Throwable cause) {
super(cause);
}
public CryptoException(String message) {
super(message);
}
}
| [
"[email protected]"
] | |
37fe7016a4f96174127de41f6c0bbfdcc3272be1 | 28b7ecefb1b74050fa11df78c2e307e108068756 | /app/src/main/java/kr/or/kead/busan/nailcare/Step3Activity.java | 6bcde3f2430fa0669c768268ce8e6d714e97ce6c | [] | no_license | chunxpd/Busan_Nail_Care | 5ec62ee8195a98c9c6ca8bca8fa86096dde37bbc | 5d44f77498372968d69397d60de867d562e5705a | refs/heads/master | 2020-05-23T22:46:38.485519 | 2019-05-16T08:01:12 | 2019-05-16T08:01:12 | 186,980,861 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,480 | java | package kr.or.kead.busan.nailcare;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class Step3Activity extends AppCompatActivity {
String caretype="";
int f_cot[] = new int[10];
int f_colour[] = new int[10];
String shape;
int selectedcolor=0;
int numofcolor = 40; //손가락에 칠할 칼라의 갯수 xml파일과 일치해야 함.
int selcolour[]={
0xff995e3e, 0xff725449, 0xff1c0c0c, 0xff2a1115, 0xff46241a, 0xff9d7c6d, 0xff55384c, 0xff423733, 0xff927f54, 0xff907653,
0xff2f2121, 0xff8f8b80, 0xff1c0c0c, 0xffb5b0b4, 0xffbcbaad, 0xff0f0d0e, 0xff272b37, 0xff353c46, 0xff6b6a66, 0xffe7e7e7,
0xff732636, 0xff6f383b, 0xffb69896, 0xffc8b6a2, 0xffcf1d2b, 0xffcf1b62, 0xffe9338a, 0xffdb74b9, 0xffc4959f, 0xffe0a4c0,
0xff080e48, 0xff970707, 0xff621c1c, 0xff380808, 0xff25181f, 0xff390f10, 0xff770505, 0xffc92629, 0xffbc181f, 0xffd40b1e,
0xff583b71, 0xff471d29, 0xff21152d, 0xff321436, 0xff34163c, 0xff5b2698, 0xff883771, 0xff7f4184, 0xff9644b3, 0xff9f76b0,
0xff4f1f08, 0xff776559, 0xffc8ad78, 0xffba9b31, 0xffcfc15e, 0xff9d800b, 0xffa18507, 0xffc0b002, 0xffbeb325, 0xffc5bd75,
0xff803c27, 0xffad8b7f, 0xffbba18a, 0xffdc270a, 0xffe93e2c, 0xffd04e3e, 0xffd9726b, 0xffe1a492, 0xffd3a359, 0xffdfba9f,
0xff73aa8d, 0xff41888e, 0xff1f80a0, 0xff007467, 0xff326584, 0xff222953, 0xff979ca0, 0xff112b82, 0xff0952b0, 0xff377eb2,
};
String seltext[]={
"995e3e", "725449", "1c0c0c", "2a1115", "46241a", "9d7c6d", "55384c", "423733", "927f54", "907653",
"2f2121", "8f8b80", "1c0c0c", "b5b0b4", "bcbaad", "0f0d0e", "272b37", "353c46", "6b6a66", "e7e7e7",
"732636", "6f383b", "b69896", "c8b6a2", "cf1d2b", "cf1b62", "e9338a", "db74b9", "c4959f", "e0a4c0",
"080e48", "970707", "621c1c", "380808", "25181f", "390f10", "770505", "c92629", "bc181f", "d40b1e",
"583b71", "471d29", "21152d", "321436", "34163c", "5b2698", "883771", "7f4184", "9644b3", "9f76b0",
"4f1f08", "776559", "c8ad78", "ba9b31", "cfc15e", "9d800b", "a18507", "c0b002", "beb325", "c5bd75",
"803c27", "ad8b7f", "bba18a", "dc270a", "e93e2c", "d04e3e", "d9726b", "e1a492", "d3a359", "dfba9f",
"73aa8d", "41888e", "1f80a0", "007467", "326584", "222953", "979ca0", "112b82", "0952b0", "377eb2",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step3);
Intent intent = getIntent();
f_cot = intent.getIntArrayExtra("cot");
shape = intent.getStringExtra("shape");
caretype = intent.getStringExtra("care");
ImageView imageViewFinger[]={
(ImageView) findViewById(R.id.finger_0),
(ImageView) findViewById(R.id.finger_1),
(ImageView) findViewById(R.id.finger_2),
(ImageView) findViewById(R.id.finger_3),
(ImageView) findViewById(R.id.finger_4),
(ImageView) findViewById(R.id.finger_5),
(ImageView) findViewById(R.id.finger_6),
(ImageView) findViewById(R.id.finger_7),
(ImageView) findViewById(R.id.finger_8),
(ImageView) findViewById(R.id.finger_9),
};
switch(shape) {
case "round":
for(int i=0;i<10;i++) {
imageViewFinger[i].setBackgroundResource(R.drawable.finger_round);
}
break;
case "oval":
for(int i=0;i<10;i++) {
imageViewFinger[i].setBackgroundResource(R.drawable.finger_oval);
}
break;
case "square":
for(int i=0;i<10;i++) {
imageViewFinger[i].setBackgroundResource(R.drawable.finger_square);
}
break;
}
for(int i=0;i<10;i++) {
imageViewFinger[i].setImageResource(f_cot[i]);
}
for(int i=0; i<numofcolor; i++) {
ImageView imageView;
TextView textView;
int rid;
rid = getResources().getIdentifier("color_" + i, "id", this.getBaseContext().getPackageName());
imageView = (ImageView) findViewById(rid);
imageView.setColorFilter(selcolour[i], PorterDuff.Mode.MULTIPLY);
rid = getResources().getIdentifier("color_text_" + i, "id", this.getBaseContext().getPackageName());
textView = (TextView) findViewById(rid);
textView.setText(seltext[i]);
}
}
public void onClickColour(View view) {
ImageView imageView = (ImageView) findViewById(view.getId());
int selcolor = Integer.valueOf(view.getResources().getResourceEntryName(view.getId()).substring(6));
//Toast.makeText(this,selcolor,Toast.LENGTH_SHORT).show(); //color_0
selectedcolor = selcolor;
}
public void onClickFinger(View view) {
ImageView imageView = (ImageView) findViewById(view.getId());
int selfinger = Integer.valueOf(view.getResources().getResourceEntryName(view.getId()).substring(7));
f_colour[selfinger] = selcolour[selectedcolor];
imageView.setColorFilter(selcolour[selectedcolor], PorterDuff.Mode.MULTIPLY);
}
public void onClickPrev(View view) {
finish();
}
public void onClickHome(View view) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void onClickNext(View view) {
Intent intent = new Intent(this,Step4Activity.class);
intent.putExtra("care",caretype);
intent.putExtra("shape",shape);
intent.putExtra("cot",f_cot);
intent.putExtra("colour",f_colour);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==2) {
setResult(2);
finish();
}
}
}
| [
"[email protected]"
] | |
d528829f7c40b05d1b9e55444546246ad67c96c5 | 8036c23a9e69f1adc2956ad3d738f96656b12cdf | /Prereq/src/Addstudent/Finalshow.java | 4532ce3e6e5c1bfde8b491fee53ffff3cc6772b5 | [] | no_license | AbhayGoyal/Pre-requisite-and-Co-requisite-checker | 41b3db7a24221682ad8d1b4904e01964ad214da1 | d4c9c7f6054faa63fda38345567f49ec29bdf1fa | refs/heads/master | 2021-05-02T08:20:34.721311 | 2018-02-08T18:52:31 | 2018-02-08T18:52:31 | 120,802,291 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,306 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Addstudent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author Abhay Goyal
*/
public class Finalshow extends javax.swing.JFrame {
/**
* Creates new form Finalshow
*/
public Finalshow() {
initComponents();
}
int val1;
String v1,v2;
public Finalshow(int val)
{
initComponents();
val1=val;
}
public Finalshow(String v1,String v2)
{
initComponents();
this.v1=v1;
this.v2=v2;
}
String subject1, subject2;
/*public void getshow(String v1,String v2,int i)
{
//initComponents();
this.subject1=v1;
this.subject2=v2;
System.out.print(subject1);
System.out.print(subject2);
//this.v1=v1;
//this.v2=v2;
}*/
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
formFocusGained(evt);
}
});
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
jLabel1.setText("Subject 1:-");
jLabel2.setText("Subject 2:-");
jLabel3.setText("Subject 3:-");
jLabel4.setText("Subject 4:-");
jLabel5.setText("Subject 5:-");
jLabel6.setText("Subject 6:-");
jLabel7.setText("Subject 7:-");
jTextField1.setText("Theory of Computation");
jTextField2.setText("Computer Networks");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jTextField3.setEditable(false);
jTextField3.setText("Maths");
jTextField4.setEditable(false);
jTextField4.setText("Database Management Systems ");
jTextField4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
jTextField5.setEditable(false);
jTextField5.setText("Aptitude");
jLabel8.setText("The subjects for you for this year would be:-");
jButton1.setText("Show me subjects");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(249, 249, 249)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField2)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(249, 249, 249)
.addComponent(jLabel5)
.addGap(47, 47, 47)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(249, 249, 249)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(48, 48, 48)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(47, 47, 47)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(255, 255, 255)
.addComponent(jLabel8)
.addGap(35, 35, 35)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGap(249, 249, 249)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3))
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(249, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jButton1))
.addGap(71, 71, 71)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel4))
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel5))
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel6))
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(82, 82, 82))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField4ActionPerformed
private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
// TODO add your handling code here:
Selectsubs s=new Selectsubs();
// String s1[]=s.setoptions();
// System.out.println(s1);
//jTextField6.requestFocusInWindow(s1[0]);
// jTextField7.setText(s1[1]);
}//GEN-LAST:event_formFocusGained
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
// TODO add your handling code here:
/*Selectsubs3 s=new Selectsubs3();
String s1[]=s.setoptions();
System.out.println(s1);
jTextField6.setText(s1[0]);
jTextField7.setText(s1[1]);*/
}//GEN-LAST:event_formWindowGainedFocus
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//Selectsubs s=new Selectsubs();
//int value=s.sendoptions();
System.out.println("\n"+val1);
try
{
Class.forName("java.sql.Driver");
//ArrayList<String> opt=new ArrayList<>();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/backcheck","root","abhay");
Statement stmt=(Statement) con.createStatement();
String s="Select * from login where id="+val1+";";
System.out.println(s);
ResultSet rs=stmt.executeQuery(s);String s1="",s2="";
while(rs.next())
{
s1=rs.getString(3);
s2=rs.getString(4);
}
String regno="";
String s6="Select regno from done order by id desc limit 1;";
System.out.println(s6);
ResultSet rs1=stmt.executeQuery(s6);
while(rs1.next())
{
regno=rs1.getString(1);
}
String s7="Select subject1,subject2 from actual where regno='"+regno+"';";
System.out.println(s7);
ResultSet rs2=stmt.executeQuery(s7);String sub1="",sub2="";
while(rs2.next())
{
sub1=rs2.getString(1);
sub2=rs2.getString(2);
}
jTextField6.setText(s1);
jTextField7.setText(s2);
jTextField1.setText(sub1);
jTextField2.setText(sub2);
System.out.println(sub1);
System.out.println(sub2);
String s21="Update optionalsubjects set counttaken=counttaken+1 where course='"+s1+"';";
String s22="Update optionalsubjects set counttaken=counttaken+1 where course='"+s2+"';";
System.out.println(s22);
System.out.println(s21);
stmt.executeUpdate(s21);
stmt.executeUpdate(s22);
//String s3="Select ;";
// jTextField1.setText(sub1);
//jTextField2.setText(sub2);
//System.out.println(subject1);
//System.out.println(subject2);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
// String s1=s.setoptions1();
// String s2=s.setoptions2();
/* System.out.println(s1);
jTextField6.setText(s1);
jTextField7.setText(s2);*/
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Finalshow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Finalshow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Finalshow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Finalshow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Finalshow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
// End of variables declaration//GEN-END:variables
}
| [
"[email protected]"
] | |
850aa92afa163a240076a68e00c39c51710dbb37 | 5baf60b57a2d1d3e24f46294ebf43a3c3653fd47 | /spring-boot-jpa/src/main/java/com/jpabook/jpashop/domain/item/Movie.java | 65344448469ec4a121a679ad4d86a5a9c5f2ed22 | [] | no_license | dmfullstack/study-jpa-basic | 47be350d4a830bc431c9fdb6c34ef4e09b39a357 | b53e7ecf44696d81497982966108a64cafa9d455 | refs/heads/master | 2022-04-02T06:06:10.847583 | 2020-02-08T06:01:47 | 2020-02-08T06:01:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 309 | java | package com.jpabook.jpashop.domain.item;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("M")
@Getter @Setter
public class Movie extends Item {
private String director;
private String actor;
}
| [
"[email protected]"
] | |
c00c956200b45d749cdf5c7701411d0823330800 | d24de9be4c3993d9dc726e9a3c74d9662c470226 | /reverse/Rocketbank_All_3.12.4_source_from_JADX/sources/com/flurry/sdk/lr.java | 0607b4c28313465a217ea0aacfea5215bd603b95 | [] | no_license | MEJIOMAH17/rocketbank-api | b18808ee4a2fdddd8b3045cd16655b0d82e0b13b | fc4eb0cbb4a8f52277fdb09a3b26b4cceef6ff79 | refs/heads/master | 2022-07-17T20:24:29.721131 | 2019-07-26T18:55:21 | 2019-07-26T18:55:21 | 198,698,231 | 4 | 0 | null | 2022-06-20T22:43:15 | 2019-07-24T19:31:49 | Smali | UTF-8 | Java | false | false | 12,110 | java | package com.flurry.sdk;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import io.fabric.sdk.android.services.common.CommonUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public final class lr {
/* renamed from: a */
private static final String f426a = "lr";
/* renamed from: a */
public static void m304a() {
if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
throw new IllegalStateException("Must be called from the main thread!");
}
}
/* renamed from: b */
public static void m312b() {
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
throw new IllegalStateException("Must be called from a background thread!");
}
}
/* renamed from: a */
public static String m302a(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
Uri parse = Uri.parse(str);
return (parse != null && parse.getScheme() == null) ? "http://".concat(String.valueOf(str)) : str;
}
/* renamed from: c */
public static java.lang.String m313c(java.lang.String r4) {
/* JADX: method processing error */
/*
Error: java.lang.NullPointerException
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:56)
at jadx.core.ProcessClass.process(ProcessClass.java:39)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:282)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
at jadx.api.JadxDecompiler$$Lambda$8/1556461159.run(Unknown Source)
*/
/*
r0 = "UTF-8"; Catch:{ UnsupportedEncodingException -> 0x0007 }
r0 = java.net.URLEncoder.encode(r4, r0); Catch:{ UnsupportedEncodingException -> 0x0007 }
return r0;
L_0x0007:
r0 = 5;
r1 = f426a;
r2 = new java.lang.StringBuilder;
r3 = "Cannot encode '";
r2.<init>(r3);
r2.append(r4);
r4 = "'";
r2.append(r4);
r4 = r2.toString();
com.flurry.sdk.kf.m176a(r0, r1, r4);
r4 = "";
return r4;
*/
throw new UnsupportedOperationException("Method not decompiled: com.flurry.sdk.lr.c(java.lang.String):java.lang.String");
}
/* renamed from: d */
public static java.lang.String m314d(java.lang.String r4) {
/* JADX: method processing error */
/*
Error: java.lang.NullPointerException
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:56)
at jadx.core.ProcessClass.process(ProcessClass.java:39)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:282)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
at jadx.api.JadxDecompiler$$Lambda$8/1556461159.run(Unknown Source)
*/
/*
r0 = "UTF-8"; Catch:{ UnsupportedEncodingException -> 0x0007 }
r0 = java.net.URLDecoder.decode(r4, r0); Catch:{ UnsupportedEncodingException -> 0x0007 }
return r0;
L_0x0007:
r0 = 5;
r1 = f426a;
r2 = new java.lang.StringBuilder;
r3 = "Cannot decode '";
r2.<init>(r3);
r2.append(r4);
r4 = "'";
r2.append(r4);
r4 = r2.toString();
com.flurry.sdk.kf.m176a(r0, r1, r4);
r4 = "";
return r4;
*/
throw new UnsupportedOperationException("Method not decompiled: com.flurry.sdk.lr.d(java.lang.String):java.lang.String");
}
/* renamed from: a */
public static void m305a(java.io.Closeable r0) {
/* JADX: method processing error */
/*
Error: java.lang.NullPointerException
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:56)
at jadx.core.ProcessClass.process(ProcessClass.java:39)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:282)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
at jadx.api.JadxDecompiler$$Lambda$8/1556461159.run(Unknown Source)
*/
/*
if (r0 == 0) goto L_0x0007;
L_0x0002:
r0.close(); Catch:{ Throwable -> 0x0006 }
goto L_0x0007;
L_0x0006:
return;
L_0x0007:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: com.flurry.sdk.lr.a(java.io.Closeable):void");
}
/* renamed from: e */
public static byte[] m315e(String str) {
if (TextUtils.isEmpty(str)) {
return null;
}
try {
return str.getBytes("UTF-8");
} catch (String str2) {
String str3 = f426a;
StringBuilder stringBuilder = new StringBuilder("Unsupported UTF-8: ");
stringBuilder.append(str2.getMessage());
kf.m176a(5, str3, stringBuilder.toString());
return null;
}
}
/* renamed from: f */
public static byte[] m316f(String str) {
try {
MessageDigest instance = MessageDigest.getInstance(CommonUtils.SHA1_INSTANCE);
instance.update(str.getBytes(), 0, str.length());
return instance.digest();
} catch (String str2) {
String str3 = f426a;
StringBuilder stringBuilder = new StringBuilder("Unsupported SHA1: ");
stringBuilder.append(str2.getMessage());
kf.m176a(6, str3, stringBuilder.toString());
return null;
}
}
/* renamed from: a */
public static String m303a(byte[] bArr) {
StringBuilder stringBuilder = new StringBuilder(bArr.length << 1);
char[] cArr = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (byte b : bArr) {
byte b2 = (byte) (b & 15);
stringBuilder.append(cArr[(byte) ((b & 240) >> 4)]);
stringBuilder.append(cArr[b2]);
}
return stringBuilder.toString();
}
/* renamed from: b */
public static String m311b(byte[] bArr) {
if (bArr == null) {
return null;
}
try {
return new String(bArr, "ISO-8859-1");
} catch (byte[] bArr2) {
String str = f426a;
StringBuilder stringBuilder = new StringBuilder("Unsupported ISO-8859-1:");
stringBuilder.append(bArr2.getMessage());
kf.m176a(5, str, stringBuilder.toString());
return null;
}
}
/* renamed from: a */
public static boolean m306a(long j) {
if (j != 0) {
if (System.currentTimeMillis() > j) {
return 0;
}
}
return 1;
}
/* renamed from: a */
public static boolean m308a(Intent intent) {
return jr.m114a().f293a.getPackageManager().queryIntentActivities(intent, 65536).size() > null ? true : null;
}
/* renamed from: g */
public static String m317g(String str) {
return str.replace("\\b", "").replace("\\n", "").replace("\\r", "").replace("\\t", "").replace("\\", "\\\\").replace("'", "\\'").replace("\"", "\\\"");
}
/* renamed from: h */
public static Map<String, String> m318h(String str) {
Map<String, String> hashMap = new HashMap();
if (!TextUtils.isEmpty(str)) {
for (String split : str.split("&")) {
String[] split2 = split.split("=");
if (!split2[0].equals(NotificationCompat.CATEGORY_EVENT)) {
hashMap.put(m314d(split2[0]), m314d(split2[1]));
}
}
}
return hashMap;
}
/* renamed from: i */
public static long m319i(String str) {
if (str == null) {
return 0;
}
long j = 1125899906842597L;
int i = 0;
while (i < str.length()) {
i++;
j = (31 * j) + ((long) str.charAt(i));
}
return j;
}
/* renamed from: a */
public static long m301a(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] bArr = new byte[1024];
long j = 0;
while (true) {
int read = inputStream.read(bArr);
if (read < 0) {
return j;
}
outputStream.write(bArr, 0, read);
j += (long) read;
}
}
/* renamed from: a */
public static byte[] m309a(InputStream inputStream) throws IOException {
if (inputStream == null) {
return null;
}
OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
m301a(inputStream, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
/* renamed from: a */
public static double m300a(double d) {
return ((double) Math.round(d * Math.pow(10.0d, 3.0d))) / Math.pow(10.0d, 3.0d);
}
/* renamed from: a */
public static boolean m307a(Context context, String str) {
if (context != null) {
if (!TextUtils.isEmpty(str)) {
try {
if (context.getPackageManager().checkPermission(str, context.getPackageName()) == null) {
return true;
}
return false;
} catch (Context context2) {
String str2 = f426a;
StringBuilder stringBuilder = new StringBuilder("Error occured when checking if app has permission. Error: ");
stringBuilder.append(context2.getMessage());
kf.m176a(6, str2, stringBuilder.toString());
return false;
}
}
}
return false;
}
/* renamed from: b */
public static String m310b(String str) {
if (str == null) {
return "";
}
if (str.length() <= 255) {
return str;
}
return str.substring(0, 255);
}
}
| [
"mekosichkin.ru"
] | mekosichkin.ru |
fedbea5cf19882473f2d54539820f23d358f10ea | c4d428cd534dacb5b11911e1226328cd55d0cd2c | /lib/src/main/java/com/example/lib/basic_classes/phase_objects.java | fbe62be97ed453495c5e668b70950c0c6551660b | [] | no_license | alex0pheiffer/LiberatingDelta_vCurrent | a9480b2cb982d1d2f9f9ed395716e3cf04f65acb | eadb005d95290e755c953e6ef7f322697e004b0c | refs/heads/master | 2020-09-21T21:42:12.976610 | 2020-01-24T02:55:48 | 2020-01-24T02:55:48 | 224,941,245 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 421 | java | package com.example.lib.basic_classes;
public abstract class phase_objects {
//to be extended by fights and phases
int coorPL;
int phaseNumber;
public phase_objects(int pl, int phase) {
this.coorPL = pl;
this.phaseNumber = phase;
}
public int getPL() { return coorPL; }
public int getPhase() { return phaseNumber; }
public String toString() { return "phase_objects";}
}
| [
"[email protected]"
] | |
d4195f613f2cd7b585691533d307f59b6e04b591 | 45e076b8f77da0d416d90410f25637f4db5a109d | /src/test/java/visualizar_Informacoes_resumidas_requisicao_pagamento/Teste_Visualiza.java | 7ea8b9c0114a09a406401efd10a336dbf826cf61 | [] | no_license | renan-throsa/Selenium-WebDriver | 8331b8be482d001970654c8fc8012717534669b4 | aceb870e9028c6ae1071b15f2096a1186ddd02b2 | refs/heads/master | 2021-09-01T10:12:21.751667 | 2017-12-26T11:50:49 | 2017-12-26T11:50:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,089 | java | package visualizar_Informacoes_resumidas_requisicao_pagamento;
import java.util.Arrays;
import org.openqa.selenium.TimeoutException;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import gep_pagamento_auxiliary.Report;
/**
* This class implements one of the scenarios of test case described in
* 'Maintain Payment Requisition - Visualize Registry' Last test of the class:
* 04/10/2018
*
* @author Renan Rosa, Estagiario, SETIN.
* @version 1.5
* @since 15-04-2018
*/
public class Teste_Visualiza extends Report {
@Test(groups = { "Smoke testing", "Regression testing" })
public void UC002_CT005_PD001_1() throws TimeoutException, InterruptedException {
logger = extent.createTest("|UC002_CT005_PD001_1");
((Pagina) pagina).novo().preencher("00001/2018", "0000006-55.2008.5.08.0009");
if (((Pagina) pagina)
.resultado(Arrays.asList("00001/2018", "0000006-55.2008.5.08.0009", "VARA DO TRABALHO DE CASTANHAL"))) {
AssertJUnit.assertTrue(true);
} else {
Assert.fail("Error 404: Process not found");
}
}
@Test(groups = { "Regression testing" })
public void UC002_CT005_PD001_2() throws TimeoutException, InterruptedException {
logger = extent.createTest("|UC002_CT005_PD001_1");
((Pagina) pagina).novo().preencher("00002/2018", "0000008-25.2008.5.08.0009");
if (((Pagina) pagina).resultado(Arrays.asList("00002/2018", "0000008-25.2008.5.08.0009",
"VARA DO TRABALHO DE ALTAMIRA"))) {
AssertJUnit.assertTrue(true);
} else {
Assert.fail("Error 404: Process not found");
}
}
@Test(groups = { "Regression testing" })
public void UC002_CT005_PD001_3() throws TimeoutException, InterruptedException {
logger = extent.createTest("UC002_CT005_PD001_3");
((Pagina) pagina).novo().preencher("00003/2018", "0000008-25.2008.5.08.0009");
if (((Pagina) pagina).resultado(Arrays.asList("00003/2018", "0000008-25.2008.5.08.0009",
"VARA DO TRABALHO DE ALTAMIRA", "RPV", "Alimentar"))) {
AssertJUnit.assertTrue(true);
} else {
Assert.fail("Error 404: Process not found");
}
}
}
| [
"[email protected]"
] | |
c3732ad8b98ac2359ff33e9868c5f2db7da100e5 | 72801413c77f907b92535fe80b22171ac8619d07 | /Lock/app/src/main/java/com/otherlokscreen/bestlockscreenforandroid32/controller/LockScreenReciever.java | 471f949a566de18e66dabcb22e9a8f60027864e6 | [] | no_license | sureshdraco/odesk_android_ios_lock | 9f0daf36fbee068fc454f62063ebf697d8667d57 | 70cfe4c88a10ca7d319277d8019f883434407cb5 | refs/heads/master | 2020-05-27T12:48:18.384697 | 2014-10-02T15:50:59 | 2014-10-02T15:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,618 | java | package com.otherlokscreen.bestlockscreenforandroid32.controller;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.otherlokscreen.bestlockscreenforandroid32.R;
import com.otherlokscreen.bestlockscreenforandroid32.util.PreferenceUtil;
import com.otherlokscreen.bestlockscreenforandroid32.view.LockScreenActivity;
public class LockScreenReciever extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (!PreferenceUtil.isLockScreenEnabled(context))
return;
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
Intent intent11 = new Intent(context, LockScreenActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent11);
// do whatever you need to do here
//wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
Intent intent11 = new Intent(context, LockScreenActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent intent11 = new Intent(context, LockScreenActivity.class);
intent11.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent11);
}
}
}
| [
"[email protected]"
] | |
c59028bb08bead13c6b952bb127021cd2f0cbf6a | 07f07f7a8fc4c1b178f2d4c89cdd80f2931e6c80 | /Endereco.java | 0f83c319694faec02197d89d5a89350978d6b066 | [] | no_license | gabrielnmaia/ARQ_Hash | 27faf46c93b4c0f0fb9ba87774a8fc8e4786d7f6 | 675f948fae9b57e04bd37e3ca39d63d9e6a22eb4 | refs/heads/master | 2021-01-12T12:52:20.872565 | 2019-01-10T12:46:51 | 2019-01-10T12:46:51 | 69,387,559 | 0 | 2 | null | 2019-01-10T12:46:52 | 2016-09-27T18:40:20 | Java | ISO-8859-1 | Java | false | false | 1,951 | java | package br.cefetrj.arq;
import java.io.DataInput;
import java.io.IOException;
import java.nio.charset.Charset;
public class Endereco {
private String logradouro;
private String bairro;
private String cidade;
private String estado;
private String sigla;
private String cep;
public void leEndereco(DataInput din) throws IOException
{
byte logradouro[] = new byte[72];
byte bairro[] = new byte[72];
byte cidade[] = new byte[72];
byte estado[] = new byte[72];
byte sigla[] = new byte[2];
byte cep[] = new byte[8];
din.readFully(logradouro);
din.readFully(bairro);
din.readFully(cidade);
din.readFully(estado);
din.readFully(sigla);
din.readFully(cep);
din.readByte(); // Ultimo espaco em branco
din.readByte(); // Quebra de linha
// Definie a forma como caracteres especias estão codificados.
Charset enc = Charset.forName("ISO-8859-1");
this.logradouro = new String(logradouro,enc);
this.bairro = new String(bairro,enc);
this.cidade = new String(cidade,enc);
this.estado = new String(estado,enc);
this.sigla = new String(sigla,enc);
this.cep = new String(cep,enc);
}
public String getLogradouro() {
return logradouro;
}
public void setLogradouro(String logradouro) {
this.logradouro = logradouro;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
}
| [
"[email protected]"
] | |
807c38e2c672faec615683585ab2d794ce3d7e05 | b8c7f073662edb99966933ed0cfa5fa722882a91 | /cantatahealth-fhir-server/dummies/dao/impl/MedicationRequestDAOImpl.java | 3d7fdabc1d9dec13e549077e07b89ee83f24c95d | [] | no_license | cmthomps/fhir-poc | 6a7c1d4f3290ff9f0c995807c47e0a557ec88c7c | b419171a390fe8faed08ef14e9951015984fb167 | refs/heads/master | 2020-07-20T03:44:51.687372 | 2017-11-02T12:06:02 | 2017-11-02T12:06:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 898 | java | /**
*
*/
package com.cantatahealth.fhir.db.dao.impl;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.cantatahealth.fhir.db.dao.MedicationRequestDAO;
import com.cantatahealth.fhir.db.model.DummyDbEntity;
/**
* @author santosh
*
*/
@Repository
public class MedicationRequestDAOImpl implements MedicationRequestDAO {
/* (non-Javadoc)
* @see com.cantatahealth.fhir.db.dao.MedicationDAO#findMedicationById(java.lang.Long)
*/
@Override
public DummyDbEntity findMedicationRequestById(Long id) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see com.cantatahealth.fhir.db.dao.MedicationDAO#findPMedicationByParamMap(java.util.Map)
*/
@Override
public List<DummyDbEntity> findMedicationRequestByParamMap(Map<String, String> paramMap) {
// TODO Auto-generated method stub
return null;
}
}
| [
"[email protected]"
] | |
609254e36b5858daec79fc7badd779e5668f4f2f | 06591ef7336724c7c7dc65e2b76f2836412c107b | /spring-cloud-consul-school-service/src/main/java/com/example/myfirstmicroservice/springcloudconsulschoolservice/SpringCloudConsulSchoolServiceApplication.java | c44edf277c561afc5e993c3a81d77207dafdc5ad | [] | no_license | anirbandebnath/spring-cloud | 92fb813bceb59a56dcedf374e8ce39fd78c9e9d1 | 324d98c949e3cedb9b968fd6f60d1dbbd83a2ddc | refs/heads/master | 2020-04-02T17:26:09.668461 | 2018-10-25T11:32:41 | 2018-10-25T11:32:41 | 154,657,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 498 | java | package com.example.myfirstmicroservice.springcloudconsulschoolservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudConsulSchoolServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConsulSchoolServiceApplication.class, args);
}
}
| [
"[email protected]"
] | |
e1c36f59136a08151debaf546948f61b528332c4 | dd37f7e987b84b0928ed6ef88f6b1fca6e8d7ab9 | /test/LocationImplTest.java | 0d339f60c8eb0e48e7dc037fc12d19b07d1352a0 | [
"CC0-1.0"
] | permissive | simranx/Semantic_Tweet_Analysis_Soen6441 | 50173fe162c0d860abafd584a97dbae8a4433073 | 0550a92a2ae4dfbfc933491778ac333eca7dc02f | refs/heads/master | 2020-07-15T18:04:54.841605 | 2019-09-01T02:56:53 | 2019-09-01T02:56:53 | 205,619,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,420 | java | import static org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
import implementations.Location;
import play.libs.Json;
import services.TwitterService;
import twitter4j.TwitterFactory;
/**
* This class is testing the tweet by location functionality.
* @author Akshay Bansal
* @version 1.0
*/
public class LocationImplTest {
/**
* This is defining the class variables for testing.
*/
public static double latitude;
public static double longitude;
public static int count;
/**
* This method is testing tweet with values of latitude, longitude and count.
* @param latitude
* @param longitude
* @param count
*/
@BeforeClass
public static void setUp() {
TwitterService.isTesting = true;
TwitterService.typeOfFake = "SAD";
latitude= 45.5088400;
longitude = -73.5878100;
count = 10;
}
@AfterClass
public static void tearDown() {
TwitterService.isTesting = false;
TwitterService.typeOfFake = "";
}
/**
* THis method is testing the fetching tweets functionality
* with the use of latitude, longitude and count.
* @param latitude
* @param longitude
* @param count
*/
@Test
public void test() {
ArrayNode arrayNode = Json.newArray();
arrayNode = new Location().getTweetsByLocationAsync(latitude, longitude, count);
assertTrue(arrayNode.size()>0);
}
}
| [
"[email protected]"
] | |
10051716dd328387eee05f3241117b53c943c2f9 | d7437ebeb3bb51091732365924613d5067c1079b | /DS08/src/Queue.java | 37c5688c7a6d4f028ce291318cd32cd3fa36d9ee | [] | no_license | SuminJegal/Class_Data-Structure | bc54da5753e024e46dbeaeaf76742d23920bdc2d | 16e244bd0ea35535924b2c796699fd855b88661a | refs/heads/master | 2021-01-20T06:22:35.123696 | 2017-03-23T01:18:20 | 2017-03-23T01:18:20 | 85,892,177 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 140 | java |
public interface Queue {
public void add(Object object);
public Object first();
public Object remove();
public int size();
} | [
"[email protected]"
] | |
c0ef5dde4d305a432ba49f719d45e50833929cf6 | 634ae05c5e190412b2c50a7b5317c3d331322bdf | /Sandbox/src/main/java/demo/gui/events/ActionEventModifiersDemo.java | c0f081d867beebbfffcd5303fdf251949941efea | [] | no_license | ganqzz/java_workspace | 1b919aff1f177c5b6971e7f19f465129a247ed72 | 3a7285e9b1945c8b55a4b02bbb20aee3d31a9086 | refs/heads/master | 2023-07-16T06:03:36.310878 | 2021-09-04T03:44:37 | 2021-09-04T03:44:37 | 389,467,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,763 | java | package demo.gui.events;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ActionEventModifiersDemo extends JFrame implements ActionListener {
JLabel label;
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new ActionEventModifiersDemo("ActionEvent"));
}
ActionEventModifiersDemo(String title) {
setTitle(title);
setBounds(100, 100, 300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
JButton btn = new JButton("Push!");
btn.addActionListener(this);
JPanel p = new JPanel();
p.add(btn);
getContentPane().add(p, BorderLayout.CENTER);
getContentPane().add(label, BorderLayout.PAGE_END);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int modifiers = e.getModifiers();
StringBuffer sb = new StringBuffer();
sb.append("ボタンクリック ");
if ((modifiers & ActionEvent.ALT_MASK) == ActionEvent.ALT_MASK) {
sb.append("ALT ");
}
if ((modifiers & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) {
sb.append("CTRL ");
}
if ((modifiers & ActionEvent.META_MASK) == ActionEvent.META_MASK) {
sb.append("META ");
}
if ((modifiers & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK) {
sb.append("SHIFT");
}
label.setText(new String(sb));
}
}
| [
"[email protected]"
] | |
3940d1b4d0cce677848627ca85ec732ecc00fe14 | 8be82d2a23946d952421ada2a3a3226a4753a052 | /Ommay/src/com/ommay/service/VipService.java | 3dfb08475d9ce914548dabc14b871c75bf4bab0d | [] | no_license | 529457764/Ommay | 1ee532b91ac1f9287b0182e5d6692155bb12be8d | e743caecc59532f4073f987fbed22ea2392e53bf | refs/heads/master | 2016-09-06T13:52:12.278394 | 2015-09-14T03:56:00 | 2015-09-14T03:56:00 | 42,425,520 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 168 | java | package com.ommay.service;
import org.springframework.stereotype.Service;
@Service
public interface VipService {
public boolean saveVipAppointment(Object object);
}
| [
"[email protected]"
] | |
47d721967043e9ccfdd5ef844cadc32df1a9399b | fb9af9341a6be0cb2a3c046c570bccacb48abf94 | /src/cc/isotopestudio/Crack/listener/ProtectionListener.java | 1f6298a37811901a34b877815fa342bb3717411d | [] | no_license | ISOTOPE-Studio/Crack | 7c4da104d1df51f93b4966826ac1827681e7e486 | 50a9996148d0139ab3ce01478ff525177f506330 | refs/heads/master | 2020-04-06T03:53:50.095110 | 2016-06-18T02:11:51 | 2016-06-18T02:11:51 | 58,383,244 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,695 | java | package cc.isotopestudio.Crack.listener;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.SmallFireball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
/**
* Created by Mars on 6/3/2016.
* Copyright ISOTOPE Studio
*/
class ProtectionListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
if (!event.getPlayer().isOp())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (!event.getPlayer().isOp())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
if (event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) {
event.setFire(false);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockIgnite(BlockIgniteEvent event) {
if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityTeleport(EntityTeleportEvent event) {
event.setTo(event.getFrom().clone());
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onWeatherChange(WeatherChangeEvent event) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
event.setCancelled(true);
}
}
| [
"[email protected]"
] | |
c0ad196c80dddf5ab0d262bf4e03dd982327e0ec | ddce685dadbbc0a8b64762c70cd849a9afd5d61d | /Road Scholar/src/in/valtech/RoadScholar/test/PIP_TC_28.java | 8bff36c983b46c39395f5ca0b6d77fcb517dd932 | [] | no_license | RaviKumari01/SampleTest | acd7586f7e39308058cf352026db8c0b3fb46996 | 3603cf7788a3a04c53335ee2b1b68c13dc4403ae | refs/heads/master | 2020-03-11T03:23:00.986807 | 2018-04-17T07:40:32 | 2018-04-17T07:40:32 | 129,745,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,444 | java | /* Author:Sravani
* Objective:Navigate to PI page->Click on change your email link-Enter password into password field->
* Enter same password in Re-Type password field->Click on save button->
* Sign out from the header->Login with new password
*/
package in.valtech.RoadScholar.test;
import org.testng.Reporter;
import org.testng.annotations.Test;
import in.valtech.RoadScholar.pages.ChangePassword;
import in.valtech.RoadScholar.pages.HomePage;
import in.valtech.RoadScholar.pages.Login;
import in.valtech.RoadScholar.pages.PersonalInformationPage;
import in.valtech.config.BaseTest;
import in.valtech.uiFunctions.GUIFunctions;
public class PIP_TC_28 extends BaseTest
{
//Click on personal Information Page
@Test(priority=7,description="step 7:Click on Personal Information link")
public void step07_clickOnPersonalInformationLink() throws Exception
{
System.out.println("step 7 begin");
HomePage hop=new HomePage(driver);
hop.clickOnPIP();
log.info("Successfully clicked on Personal Information link \n");
Reporter.log("<p>Successfully Clicked on personal information link");
System.out.println("step 7 end");
}
//click on Change Password Link
@Test(priority=8,description="step 8:click on Change Password Link ")
public void step08_clickOnChangePasswordLink() throws Exception
{
System.out.println("step 8 begin");
PersonalInformationPage pip= new PersonalInformationPage(driver);
pip.ClickOnChangePwd();
log.info("Successfully Clicked on change password link \n");
Reporter.log("<p>Successfully Clicked on change password Link");
System.out.println("step 8 end");
}
//Enter Value in password field.
@Test(priority=9,description="step 9:Enter Value in password field ")
public void step09_enterValueInpasswordField() throws Exception
{
System.out.println("step 9 begin");
ChangePassword cp = new ChangePassword(driver);
cp.EnterPwd();
log.info("Successfully entered password in password field \n");
Reporter.log("<p>Successfully entered password in password field");
System.out.println("step 9 end");
}
//Enter Value in re-type password field.
@Test(priority=10,description="step 10:Enter Value in re-type password field. ")
public void step10_enterValueInReTypePasswordField() throws Exception
{
System.out.println("step 10 begin");
ChangePassword cp=new ChangePassword(driver);
cp.EnterReTypeCorrectPwd();
log.info("Successfully entered password in Retype password field \n");
Reporter.log("<p>Successfully entered password in Retype password field");
System.out.println("step 10 end");
}
//click on Change Save Button
@Test(priority=11,description="step 11:click on save Button ")
public void step11_clickOnSaveButton() throws Exception
{
System.out.println("step 11 begin");
ChangePassword cp=new ChangePassword(driver);
cp.ClickOnSave();
log.info("Successfully Clicke on save button \n");
Reporter.log("<p>Successfully Clicke on save button");
System.out.println("step 11 end");
}
//click on signout button
@Test(priority=12,description="step 12:click on signout button ")
public void step12_clickOnSignOutButton() throws Exception
{
System.out.println("step 12 begin");
ChangePassword cp=new ChangePassword(driver);
cp.SignOut();
GUIFunctions.normalWait();
log.info("Successfully Clicked on sign out button \n");
Reporter.log("<p>Successfully Clicked on sign out Button");
System.out.println("step 12 end");
}
//click on Click on sign in Link from Header
@Test(priority=13,description = "step 13:Click on sign in Link from Header")
public void step13_clickOnSignInLinkFromheader() throws Exception
{
System.out.println("step 13 begin");
HomePage HOP=new HomePage(driver);
HOP.clickOnSignINHeader();
GUIFunctions.normalWait();
log.info("Successfully Clicked on sign in Link from Header \n");
Reporter.log("<p>Successfully Clicked on sign in Link from Header");
System.out.println("step 13 end");
}
//entering mail id
@Test(priority=14,description = "step 14:entering mail id into email field")
public void step14_enterValueInEmailField() throws Exception
{
System.out.println("step 14 begin");
Login login=new Login(driver);
GUIFunctions.normalWait();
login.EnterEmail(UserName);
GUIFunctions.normalWait();
log.info("Successfully entered mail id into email field \n");
Reporter.log("<p>Successfully entered entering mail id into email field");
System.out.println("step 14 end");
}
//entering New Password
@Test(priority=15,description = "step 15:entering New Password in Password Field")
public void step15_EnteringNewPasswordInPasswordField() throws Exception
{
System.out.println("step 15 begin");
Login login=new Login(driver);
GUIFunctions.normalWait();
login.EnterPassword(Password);
log.info("Successfully entered the New password in Password Field \n");
Reporter.log("<p>Successfully entered the New password in Password Field");
System.out.println("step 15 end");
GUIFunctions.normalWait();
}
//Click on Sign up Button
@Test(priority=16,description = "step 16:Click on Sign up Button")
public void step16_SignUpBUtton() throws Exception
{
System.out.println("step 16 begin");
Login login=new Login(driver);
GUIFunctions.normalWait();
login.clickOnSignBtn();
log.info("Successfully Clicked on signup button \n");
Reporter.log("<p>Successfully Clicked on signup button ");
System.out.println("step 16 end");
}
}
| [
"[email protected]"
] | |
f7ea29006c1ee5207d97befb85536a1074844586 | 542709976e006d38f73bba37aef93a3e7c2e4025 | /common/src/main/java/com/ch/android/common/exp/NoNetWorkNotice.java | de4c0bdb026597b16f969e45e381ef1b15abcab2 | [
"Apache-2.0"
] | permissive | chenhongs/HrzMavenComponent | f9d10b61f4589a53fc2877cbefb84d58cc81ccf8 | a87d1cc0a441209b6d14d1ab22e768f95dbf6b9d | refs/heads/master | 2020-04-05T15:18:12.941661 | 2018-11-23T09:30:11 | 2018-11-23T09:30:11 | 156,961,698 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,164 | java | package com.ch.android.common.exp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import com.ch.android.common.R;
/**
* @author:admin on 2017/4/11 17:26.
*/
public class NoNetWorkNotice {
private WindowManager wdm;
private View mView;
private WindowManager.LayoutParams params;
private boolean isShowing;
private NoNetWorkNotice(final Activity context){
wdm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mView = View.inflate(context, R.layout.no_net_worke_layout , null);
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intent);
}
});
//设置LayoutParams(全局变量)相关参数
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
}
public static NoNetWorkNotice getInstance(Activity context){
return context == null ? null : new NoNetWorkNotice(context);
}
public void show(){
isShowing = true;
wdm.addView(mView, params);
}
public void cancel(){
isShowing = false;
//wdm.removeView(mView); //此句依然会导致MainActivity退出时导致泄漏窗体 所以使用下一句
wdm.removeViewImmediate(mView);
mView = null;
}
public boolean isShowing() {
return isShowing;
}
}
| [
"[email protected]"
] | |
4c147a18fc3a8abc690bda74090cdbeb16d0112d | f880a04aca16b0594d71fc4791001cbb85345896 | /source/android/adaptivecards/src/main/java/io/adaptivecards/renderer/readonly/RichTextBlockRenderer.java | 73ae11211b7cb749b43fb669dfa149fbf0e9befb | [
"MIT"
] | permissive | kpemmasani/AdaptiveCards | b2815191c319425fb40c8077ccc3f2c28dcfb813 | fd5130391afc2285d9572892fdbe74ecf6aad708 | refs/heads/master | 2020-05-25T10:42:21.132479 | 2019-05-20T21:12:21 | 2019-05-20T21:12:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,837 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package io.adaptivecards.renderer.readonly;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import io.adaptivecards.objectmodel.BaseActionElement;
import io.adaptivecards.objectmodel.BaseCardElement;
import io.adaptivecards.objectmodel.HeightType;
import io.adaptivecards.objectmodel.HostConfig;
import io.adaptivecards.objectmodel.Inline;
import io.adaptivecards.objectmodel.InlineElementType;
import io.adaptivecards.objectmodel.InlineVector;
import io.adaptivecards.objectmodel.RichTextBlock;
import io.adaptivecards.objectmodel.TextBlock;
import io.adaptivecards.objectmodel.TextRun;
import io.adaptivecards.renderer.BaseActionElementRenderer;
import io.adaptivecards.renderer.BaseCardElementRenderer;
import io.adaptivecards.renderer.RenderArgs;
import io.adaptivecards.renderer.RenderedAdaptiveCard;
import io.adaptivecards.renderer.TagContent;
import io.adaptivecards.renderer.actionhandler.ICardActionHandler;
public class RichTextBlockRenderer extends BaseCardElementRenderer
{
public static RichTextBlockRenderer getInstance()
{
if (s_instance == null)
{
s_instance = new RichTextBlockRenderer();
}
return s_instance;
}
private class ActionSpan extends ClickableSpan
{
public ActionSpan(BaseActionElement action, RenderedAdaptiveCard renderedCard, ICardActionHandler cardActionHandler)
{
m_actionListener = new BaseActionElementRenderer.SelectActionOnClickListener(renderedCard, action, cardActionHandler);
}
@Override
public void onClick(@NonNull View widget)
{
// Delegate the job to the listener
m_actionListener.onClick(widget);
}
private BaseActionElementRenderer.SelectActionOnClickListener m_actionListener;
}
private SpannableStringBuilder buildSpannableParagraph(
RenderedAdaptiveCard renderedCard,
InlineVector inlines,
ICardActionHandler cardActionHandler,
HostConfig hostConfig,
RenderArgs renderArgs)
{
SpannableStringBuilder paragraph = new SpannableStringBuilder();
int lastStringLength = 0;
for(int i = 0; i < inlines.size(); ++i, lastStringLength = paragraph.length())
{
Inline inline = inlines.get(i);
if(inline.GetInlineType() == InlineElementType.TextRun)
{
TextRun textRun = null;
if (inline instanceof TextRun)
{
textRun = (TextRun) inline;
}
else if ((textRun = TextRun.dynamic_cast(inline)) == null)
{
throw new InternalError("Unable to convert BaseCardElement to TextBlock object model.");
}
DateTimeParser parser = new DateTimeParser(textRun.GetLanguage());
String textWithFormattedDates = parser.GenerateString(textRun.GetTextForDateParsing());
CharSequence text = RendererUtil.handleSpecialText(textWithFormattedDates);
paragraph.append(text);
int spanStart = lastStringLength;
int spanEnd = lastStringLength + text.length();
int color = getColor(TextRendererUtil.getTextColor(textRun.GetTextColor(), hostConfig, textRun.GetIsSubtle(), renderArgs.getContainerStyle()));
paragraph.setSpan(new ForegroundColorSpan(color), spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
if (textRun.GetHighlight())
{
int highlightColor = getColor(TextRendererUtil.getHighlightColor(textRun.GetTextColor(), hostConfig, textRun.GetIsSubtle(), renderArgs.getContainerStyle()));
paragraph.setSpan(new BackgroundColorSpan(highlightColor), spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (textRun.GetStrikethrough())
{
paragraph.setSpan(new StrikethroughSpan(), spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
// This line sets the bold or italic weight
paragraph.setSpan(new StyleSpan(TextRendererUtil.getTextWeight(textRun.GetTextWeight())), spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
long textSize = TextRendererUtil.getTextSize(textRun.GetFontStyle(), textRun.GetTextSize(), hostConfig);
paragraph.setSpan(new AbsoluteSizeSpan((int)textSize, true), spanStart, spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
// On API 28, TypefaceSpan(Typeface) was added so we don't have to use the TypefaceSpan(String) constructor
String fontName = hostConfig.GetFontFamily(textRun.GetFontStyle());
if(fontName.isEmpty())
{
fontName = "monospace";
}
paragraph.setSpan(new TypefaceSpan(fontName), spanStart, spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
if(textRun.GetSelectAction() != null)
{
paragraph.setSpan(new ActionSpan(textRun.GetSelectAction(), renderedCard, cardActionHandler), spanStart, spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
return paragraph;
}
@Override
public View render(
RenderedAdaptiveCard renderedCard,
Context context,
FragmentManager fragmentManager,
ViewGroup viewGroup,
BaseCardElement baseCardElement,
ICardActionHandler cardActionHandler,
HostConfig hostConfig,
RenderArgs renderArgs)
{
RichTextBlock richTextBlock = null;
if (baseCardElement instanceof TextBlock)
{
richTextBlock = (RichTextBlock) baseCardElement;
}
else if ((richTextBlock = RichTextBlock.dynamic_cast(baseCardElement)) == null)
{
throw new InternalError("Unable to convert BaseCardElement to TextBlock object model.");
}
TextView textView = new TextView(context);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setHorizontallyScrolling(false);
// BaseCardElement properties
// Separator
// Height
// IsVisible
// Spacing
View separator = setSpacingAndSeparator(context, viewGroup, richTextBlock.GetSpacing(), richTextBlock.GetSeparator(), hostConfig, true);
textView.setTag(new TagContent(richTextBlock, separator, viewGroup));
setVisibility(baseCardElement.GetIsVisible(), textView);
if (richTextBlock.GetHeight() == HeightType.Stretch)
{
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1));
}
else
{
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
// RichTextBlock properties
// HorizontalAlignment
// Inlines
textView.setGravity(TextRendererUtil.getTextAlignment(richTextBlock.GetHorizontalAlignment()));
// This is the section for rendering the paragraphs
// Every paragraph may contain contains any number of inlines
// The current inline element types are TextRun
InlineVector inlines = richTextBlock.GetInlines();
textView.setText("");
SpannableStringBuilder convertedString = buildSpannableParagraph(renderedCard, inlines, cardActionHandler, hostConfig, renderArgs);
textView.append(convertedString);
// Properties required for actions to fire onClick event
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setClickable(true);
viewGroup.addView(textView);
return textView;
}
private static RichTextBlockRenderer s_instance = null;
}
| [
"[email protected]"
] | |
2d0adfb60ddf773dc8dc3f018b67cc715285dd0f | 4a905fa2bcb5dc0ef1eec9f908c9b6926857f00f | /giane/src/main/java/com/github/kaitoy/sneo/giane/action/NetworkGridAction.java | 8688e6394059f8ec51bd90ea4cb903482077f162 | [
"MIT"
] | permissive | z0rgr0x/sneo | df6d778a797b1fd7b929121745300105ff2f35d6 | e34b0017e842db30a046464ecf267ebe873c590f | refs/heads/master | 2021-06-20T08:07:03.496079 | 2017-07-26T12:48:35 | 2017-07-26T12:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,994 | java | /*_##########################################################################
_##
_## Copyright (C) 2012 Kaito Yamada
_##
_##########################################################################
*/
package com.github.kaitoy.sneo.giane.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.github.kaitoy.sneo.giane.model.Network;
import com.github.kaitoy.sneo.giane.model.dao.NetworkDao;
import com.github.kaitoy.sneo.giane.model.dto.NetworkDto;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("giane-default")
@InterceptorRef("gianeDefaultStack")
public class NetworkGridAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -4131928669882616269L;
private NetworkDao networkDao;
private static final Comparator<NetworkDto> idComparator
= new Comparator<NetworkDto>() {
public int compare(NetworkDto o1, NetworkDto o2) {
return o2.getId().compareTo(o1.getId());
}
};
private static final Comparator<NetworkDto> nameComparator
= new Comparator<NetworkDto>() {
public int compare(NetworkDto o1, NetworkDto o2) {
return o2.getName().compareTo(o1.getName());
}
};
private static final Comparator<NetworkDto> descrComparator
= new Comparator<NetworkDto>() {
public int compare(NetworkDto o1, NetworkDto o2) {
return o2.getDescr().compareTo(o1.getDescr());
}
};
// result List
private List<NetworkDto> gridModel;
// get how many rows we want to have into the grid - rowNum attribute in the grid
private Integer rows = 0;
// Get the requested page. By default grid sets this to 1.
private Integer page = 0;
// sorting order - asc or desc
private String sord;
// get index row - i.e. user click to sort.
private String sidx;
// Search Field
private String searchField;
// The Search String
private String searchString;
// The Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
private String searchOper;
private boolean loadonce = false;
// Total Pages
private Integer total = 0;
// All Record
private Integer records = 0;
// for DI
public void setNetworkDao(NetworkDao networkDao) {
this.networkDao = networkDao;
}
@Override
@Action(
results = {
@Result(name = "success", type = "json")
}
)
public String execute() {
CriteriaBuilder cb = networkDao.getCriteriaBuilder();
CriteriaQuery<Network> cq = cb.createQuery(Network.class);
Root<Network> r = cq.from(Network.class);
cq.select(r);
if (searchField != null) {
if (searchField.equals("id")) {
Integer searchValue = Integer.valueOf(searchString);
if (searchOper.equals("eq")) {
cq.where(cb.equal(r.get(searchField), searchValue));
}
else if (searchOper.equals("ne")) {
cq.where(cb.notEqual(r.get(searchField), searchValue));
}
else if (searchOper.equals("lt")) {
cq.where(cb.lt(r.get(searchField).as(Integer.class), searchValue));
}
else if (searchOper.equals("gt")) {
cq.where(cb.gt(r.get(searchField).as(Integer.class), searchValue));
}
}
else if (searchField.equals("name") || searchField.equals("descr")) {
if (searchOper.equals("eq")) {
cq.where(cb.equal(r.get(searchField), searchString));
}
else if (searchOper.equals("ne")) {
cq.where(cb.notEqual(r.get(searchField), searchString));
}
else if (searchOper.equals("bw")) {
cq.where(cb.like(r.get(searchField).as(String.class), searchString + "%"));
}
else if (searchOper.equals("ew")) {
cq.where(cb.like(r.get(searchField).as(String.class), "%" + searchString));
}
else if (searchOper.equals("cn")) {
cq.where(cb.like(r.get(searchField).as(String.class), "%" + searchString + "%"));
}
}
}
gridModel = new ArrayList<NetworkDto>();
for (Network model: networkDao.findByCriteria(cq)) {
gridModel.add(new NetworkDto(model));
}
records = gridModel.size();
if (sord != null && sord.length() != 0 && sidx != null && sidx.length() != 0) {
if (sidx.equalsIgnoreCase("id")) {
Collections.sort(gridModel, idComparator);
}
else if (sidx.equalsIgnoreCase("name")) {
Collections.sort(gridModel, nameComparator);
}
else if (sidx.equalsIgnoreCase("descr")) {
Collections.sort(gridModel, descrComparator);
}
if (sord.equalsIgnoreCase("desc")) {
Collections.reverse(gridModel);
}
}
if (!loadonce){
int to = (rows * page);
int from = to - rows;
if (to > records) {
to = records;
}
gridModel = gridModel.subList(from, to);
}
// calculate the total pages for the query
total = (int)Math.ceil((double)records / (double)rows);
return SUCCESS;
}
public String getJSON() { return execute(); }
public List<NetworkDto> getGridModel() {
return gridModel;
}
public void setGridModel(List<NetworkDto> gridModel) {
this.gridModel = gridModel;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public String getSord() {
return sord;
}
public void setSord(String sord) {
this.sord = sord;
}
public String getSidx() {
return sidx;
}
public void setSidx(String sidx) {
this.sidx = sidx;
}
public String getSearchField() {
return searchField;
}
public void setSearchField(String searchField) {
this.searchField = searchField;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchOper() {
return searchOper;
}
public void setSearchOper(String searchOper) {
this.searchOper = searchOper;
}
public boolean isLoadonce() {
return loadonce;
}
public void setLoadonce(boolean loadonce) {
this.loadonce = loadonce;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getRecords() {
return records;
}
public void setRecords(Integer records) {
this.records = records;
}
} | [
"[email protected]"
] | |
e9a6d85ab0c0dbfdfb81612947cb9c17969edbf5 | 64bb1bd1dfa3ce95737f855edb29cad216b5addd | /src/main/java/org/generation/blogPessoal/model/Usuario.java | 64955a5883f4417757ae64796a74265c7bf163d3 | [] | no_license | llauros/Blog_pessoal | f22140fa2f12f591adcab1bd56b52f0dc30c8d5e | ebd36445bb9e3f6f107952be19a2113a7c72169b | refs/heads/main | 2023-07-07T03:08:39.195368 | 2021-08-11T17:14:28 | 2021-08-11T17:14:28 | 390,190,143 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,073 | java | package org.generation.blogPessoal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table( name = "tb_ususario")
public class Usuario {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size( min = 2, max = 100)
private String nome;
@NotNull
@Size( min = 5, max = 100)
private String usuario;
@NotNull
@Size( min = 5, max = 100)
private String senha;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
| [
"lucaslauro@live"
] | lucaslauro@live |
3ae476b3fffbe77e2c1d3e3ca982676e14196897 | c8341b7c1231cd1ab9a3ced0647b696a4bef0432 | /efak-common/src/main/java/org/smartloli/kafka/eagle/common/util/AppUtils.java | 6020ce865d22f1425cef972e791043a1e4a0449e | [
"Apache-2.0"
] | permissive | along163/kafka-eagle | 075d3977cc8e0c17b445deb39912b95e08bb94cd | 9654271c4fa26efac17242e1417c8eb00db7037f | refs/heads/master | 2023-08-24T11:22:20.936299 | 2021-09-24T08:56:54 | 2021-09-24T08:56:54 | 329,528,155 | 0 | 1 | Apache-2.0 | 2021-09-24T08:56:54 | 2021-01-14T06:32:30 | null | UTF-8 | Java | false | false | 2,726 | 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.smartloli.kafka.eagle.common.util;
import java.lang.management.*;
/**
* Count the percent of application resources.
*
* @author smartloli.
* <p>
* Created by Sep 15, 2020
*/
public class AppUtils {
private static AppUtils instance = new AppUtils();
private OperatingSystemMXBean osMxBean;
private RuntimeMXBean runtimeMXBean;
private ThreadMXBean threadBean;
private MemoryMXBean memoryMXBean;
private long preTime = System.nanoTime();
private long preUsedTime = 0;
private AppUtils() {
osMxBean = ManagementFactory.getOperatingSystemMXBean();
memoryMXBean = ManagementFactory.getMemoryMXBean();
threadBean = ManagementFactory.getThreadMXBean();
runtimeMXBean = ManagementFactory.getRuntimeMXBean();
}
public static AppUtils getInstance() {
return instance;
}
/**
* Get current application cpu (such as 1%).
* <p>
* 100% -> 1 cpu cores
*/
public double getProcessCpu() {
long totalTime = 0;
for (long id : threadBean.getAllThreadIds()) {
totalTime += threadBean.getThreadCpuTime(id);
}
long curtime = System.nanoTime();
long usedTime = totalTime - preUsedTime;
long totalPassedTime = curtime - preTime;
preTime = curtime;
preUsedTime = totalTime;
return StrUtils.numberic((((double) usedTime) / totalPassedTime / osMxBean.getAvailableProcessors()) * 100);
}
/**
* Get application mem used.
*/
public long getProcessMemUsed() {
return memoryMXBean.getHeapMemoryUsage().getUsed();
}
/**
* Get application mem max.
*/
public long getProcessMemMax() {
return memoryMXBean.getHeapMemoryUsage().getMax();
}
public String getStartTime() {
return CalendarUtils.convertUnixTime2Date(runtimeMXBean.getStartTime());
}
}
| [
"[email protected]"
] | |
6fdcc254e717d4e90e99c135475996e2b5d5a341 | 9d1574d83b8597f2e39969645430415fc400bde0 | /src/main/java/com/superman/superman/model/Agent.java | fba2f64f765d8a4cd57627f4a9f73561495fbfec | [] | no_license | Hasaki6/ShopMall | ec70fd88852ea7bb80fae348cbf86823e3dde669 | 94b2817a1b11ec99e4f615e7b6b8335737e3a849 | refs/heads/master | 2020-09-26T11:44:52.074858 | 2019-10-16T15:43:03 | 2019-10-16T15:43:03 | 226,248,592 | 5 | 0 | null | 2019-12-06T04:54:32 | 2019-12-06T04:54:31 | null | UTF-8 | Java | false | false | 435 | java | package com.superman.superman.model;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
/** 代理表
* Created by liujupeng on 2018/11/23.
*/
@Data
public class Agent {
private Integer id;
private Integer userId;
private Integer agentId;
private String agentName;
private String userName;
private Date createTime;
private Date updateTime;
}
| [
"[email protected]"
] | |
ffaaf94e7d2d3af1769b902d98211bdffd4d2288 | aa414106e896529e049430cb5dc34a0afba7524a | /src/main/java/com/fzj/blog/service/impl/LinkServiceImpl.java | f0a1f5132f8f45777bc9c0de51139a6164cdf26c | [] | no_license | JackBome/MyBlog | 98f87b802c077eee4c603820a31e41fdb799e5ea | ce6eb739743aa45948098447c66e853da5cc9204 | refs/heads/master | 2021-01-13T11:00:54.863249 | 2016-10-21T09:37:54 | 2016-10-21T09:37:54 | 69,541,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,541 | java | package com.fzj.blog.service.impl;
import com.fzj.blog.dao.LinkDao;
import com.fzj.blog.pojo.Link;
import com.fzj.blog.service.LinkService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by j on 2016/9/29.
*/
@Service
public class LinkServiceImpl implements LinkService {
//自动注入linkDao
@Autowired
private LinkDao linkDao;
@Override
public int addLink(Link link) {
if(link !=null){
int i =linkDao.addLink(link);
if(i ==1){
return 1;
}
}
return 0;
}
@Override
public int delLink(Integer id) {
int i =linkDao.delLink(id);
if(i==1){
return 1;
}
return 0;
}
@Override
public int updateLink(Link link) {
if(link !=null){
int i =linkDao.updateLink(link);
if(i ==1){
return 1;
}
}
return 0;
}
@Override
public Link getLinkById(Integer id) {
Link link =linkDao.getLinkById(id);
if(link !=null){
return link;
}
return null;
}
@Override
public List<Link> queryAllLink(@Param("offset") int offset, @Param("limit") int limit) {
List<Link> links =linkDao.queryAllLink(offset,limit);
if(links !=null){
return links;
}
return null;
}
}
| [
"[email protected]"
] | |
3f8d829cce9f9aa9a5b9ddfef75ace25678a15fc | 1fdbf2abfeb6a0d23a336ff436f7276b82b31379 | /src/main/java/models/specials/Heal.java | 7c40e2cf6188df56f36595a5ef325e432dec1965 | [] | no_license | EleonoraDM/RPG | 283df610b6ea28104613d2350817386ca36c02cd | 22a4672cf913c3d7ee45ea8f5c2e9692aff1b66b | refs/heads/master | 2020-12-04T22:19:16.140795 | 2020-02-11T13:48:06 | 2020-02-11T13:48:06 | 231,920,198 | 0 | 0 | null | 2020-10-13T19:07:53 | 2020-01-05T13:18:08 | Java | UTF-8 | Java | false | false | 94 | java | package models.specials;
public class Heal extends SpecialImpl{
public Heal() {
}
}
| [
"[email protected]"
] | |
27ddfd1f690b394b2639ffea3828e73b9249dd70 | f8306245d9c50827f680567813e4b140d68b2eec | /sampleSet/04aggregate/Test.java | 5defe2896c7d1576f87d84eef6386c2a8491f3ec | [] | no_license | hiuric/hiMongo | 09e8f64234a06d8777785121a6e4c2aa5a378555 | ea31175b16e88e64769ac767ad97356166240eec | refs/heads/master | 2023-01-14T05:15:39.686223 | 2020-11-03T07:14:39 | 2020-11-03T07:14:39 | 295,317,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,205 | java | import hi.db.hiMongo;
import otsu.hiNote.*;
import java.util.*;
import java.io.*;
public class Test {
static class Arec {
String _id;
double min;
double max;
double avg;
}
static class WithDate {
Date date;
}
public static void main(String[] args_){
hiMongo.DB db=hiMongo.use("db01");
long _start_date
=db.in("coll_01")
.find("{type:'A'}","{_id:0,date:1}")
.sort("{_id:-1}").limit(1).getClassList(WithDate.class).get(0)
.date.getTime()-30000;
Arec _r
= db.in("coll_01")
.aggregate("["+
"{ $match:{$and:["+
"{type:'A'},"+
"{date:{$gte:{$date:"+_start_date+"}}}"+
"]}},"+
"{ $group:{"+
"_id:'$type',"+
"min:{$min:'$value'},"+
"max:{$max:'$value'},"+
"avg:{$avg:'$value'}}}"+
"]")
.getClassList(Arec.class).get(0);
System.out.println("start="+_start_date);
System.out.println(String.format("min=%.2f max=%.2f avg=%.2f"
,_r.min,_r.max,_r.avg));
}
}
| [
"[email protected]"
] | |
9418c3fd84089e6c4105ddf4836170a33db3dc47 | 8c31c6738813d754df999a91546bbfb0acfd9dbf | /witkey-system/src/main/java/co/zhenxi/config/thread/TheadFactoryName.java | 6627145aa2fa4a8981a4d5bc418871fcc81691d8 | [
"Apache-2.0"
] | permissive | edjian/witkey | 760062576c84e78ca5da108a49fc389169fe70e9 | 4b32d0c4c321bc56483851d0444c03d66aa8be0d | refs/heads/master | 2023-01-10T10:35:59.911949 | 2020-11-09T06:25:26 | 2020-11-09T06:25:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,585 | java | /**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
*/
package co.zhenxi.config.thread;
import org.springframework.stereotype.Component;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 自定义线程名称
* @author hupeng
* @date 2019年10月31日17:49:55
*/
@Component
public class TheadFactoryName implements ThreadFactory {
private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
public TheadFactoryName() {
this("el-pool");
}
private TheadFactoryName(String name){
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
//此时namePrefix就是 name + 第几个用这个工厂创建线程池的
this.namePrefix = name +
POOL_NUMBER.getAndIncrement();
}
@Override
public Thread newThread(Runnable r) {
//此时线程的名字 就是 namePrefix + -thread- + 这个线程池中第几个执行的线程
Thread t = new Thread(group, r,
namePrefix + "-thread-"+threadNumber.getAndIncrement(),
0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
| [
"[email protected]"
] | |
c3f02b4a15fe9a4570d0a1086786df0deb2570fe | 92f6d78302859383493323ef973012201da998e1 | /QM/src/servlet/Login.java | 46b3ef474002a188f38150590a311e05c1b4c74f | [] | no_license | YBonnie/Pet-Protection-Association | 905f22f735b0e30d62fabbf1d19e781ae3ed7f21 | 2cc0e175c3c484ef4238b6e85202b2c79475e1cf | refs/heads/master | 2020-05-20T04:45:42.686627 | 2019-05-07T11:47:53 | 2019-05-07T11:47:53 | 185,390,013 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,718 | java | package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import javabean.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import factory.BasicFactory;
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //编码问题
//对于get提交只能手动的解决
UserService service = BasicFactory.getFactory().getService(UserService.class);
User user = new User();
String name = request.getParameter("username");
String password1 = request.getParameter("password1");
user.setUsername(name);
user.setPassword1(password1);
User user2=service.getUserByNameAndPsw(user.getUsername(), user.getPassword1());
if(user2==null ||user2.getUsername()==name && user2.getPassword1() == password1){
JOptionPane.showMessageDialog(null, "密码或帐号错误!", "错误提示", JOptionPane.ERROR_MESSAGE);
response.setHeader("Refresh", "1;url=/QM/sign_In.jsp");
return;
}else
JOptionPane.showMessageDialog(null, "登陆成功!", "提示",JOptionPane.PLAIN_MESSAGE);
request.getSession().setAttribute("user2", user2);
response.setHeader("Refresh", "1;url=/QM/IndexList");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
| [
"[email protected]"
] | |
60cd17df9b939a0f0b31314d40ed5e2da43965dd | 580f9e14578281e36eaeb523e284f00cfa2f39bd | /src/test/java/com/example/jumpstart/JumpstartApplicationTests.java | aa769ac2c0c67aff601a6b36567c8db3715e2ce0 | [] | no_license | huxingran1993/Order_Management_BackEnd | 96e5b4de38c973f64c8af2e4e522ed4c2714d411 | fa0bc90addd3201dc6e8c34e97c9678e5befe1da | refs/heads/master | 2020-12-05T08:23:47.853032 | 2020-01-06T10:57:41 | 2020-01-06T10:57:41 | 232,057,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 216 | java | package com.example.jumpstart;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JumpstartApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
dc35ed4e1ac50b2e0315acd173beac3ff612b809 | 83df5c7d9429b055b1b4eab0559a3f7e696a33ac | /alumni/src/main/java/com/niit/alumni/model/Friends.java | dbfee5a47017480b780d3cdebfb4d4617e5c43e3 | [] | no_license | vvijaibaskar/DigiNxt | 7dbd2f22c7a744cdfdd3e6203c006e7c3e79eba5 | d0494fbe2d65e3f677bb183468489d824ba94e82 | refs/heads/master | 2020-05-22T06:51:13.133079 | 2016-09-13T17:49:37 | 2016-09-13T17:49:37 | 59,988,706 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 539 | java | package com.niit.alumni.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Entity
@Table(name = "FRIENDS")
@Component
public class Friends {
@Id
private String usrId;
private String friendId;
public String getUsrId() {
return usrId;
}
public void setUsrId(String usrId) {
this.usrId = usrId;
}
public String getFriendId() {
return friendId;
}
public void setFriendId(String friendId) {
this.friendId = friendId;
}
}
| [
"[email protected]"
] | |
ecf97ba9356aa7f80e178af55f7dce40b28810da | b78567357a72f0c9d8478c2598c0dc99f11713ed | /src/com/ithoughts/twentyonedays/GraphObject.java | 46c74957801d7a4ff257549f304377b75fb2928f | [] | no_license | joelewis/21days | 79993a6af117cf06e71357a32d63139c384f4f4b | f47fc698037004507192ea313f5fc610242aa5b5 | refs/heads/master | 2021-01-23T11:49:30.178123 | 2013-12-03T19:06:25 | 2013-12-03T19:06:25 | 11,198,181 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 161 | java | package com.ithoughts.twentyonedays;
public class GraphObject {
public int[] dotColors;
public int days_from_genesis;
public int hits;
public int misses;
}
| [
"[email protected]"
] | |
2d544d4bf83f48ebb4196c65b5f7ddd531a7147b | 033c4b1427eed55428b58e1d78c281bc080fde37 | /Ball Game/src/dodgeballgame/Settings/IntSetting.java | 8861a354e32b0f966c1a5c519a3c600c9684708d | [] | no_license | Sam-Evans-Thomson/Dodgeball | 4e6442fb46f3925ff21ff9e1491f23a116447c62 | 106bda7960969320907eb1ea921868c2a5185d0f | refs/heads/master | 2021-01-10T15:34:19.071706 | 2016-01-15T09:13:55 | 2016-01-15T09:13:55 | 48,522,434 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,751 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dodgeballgame.Settings;
/**
*
* @author Sam
*/
public class IntSetting extends Setting {
int value;
public IntSetting(int val, String name) {
value = val;
this.name = name;
}
public IntSetting(int val, String name,double start, double end, double inc) {
this.start = start;
this.end = end;
this.inc = inc;
value = val;
this.name = name;
}
public IntSetting(IntSetting set) {
this.start = set.start;
this.end = set.end;
this.inc = set.inc;
value = set.value;
this.name = set.name;
}
@Override
public IntSetting copy() {
return new IntSetting(this);
}
@Override
public String getValueString() {
return "" + value;
}
@Override
public void changeValue(int i) {
moveThrough((int)(i*inc));
}
private double moveThrough(int dist) {
int end2 = (int)end;
int start2 = (int)start;
if (dist > end2-start2) return end2;
if (dist < start2-end2) return start2;
value += dist;
if (value > end2) value = start2;
if (value < start2) value = end2;
return value;
}
public int getValue() {
return value;
}
@Override
public double getDouble() {
return (double)value;
}
@Override
public String toString() {
return "INT" + " - " + name + " - " + getValue() + " - " + start + " - " + end + " - " + inc;
}
}
| [
"[email protected]"
] | |
a20f6087a5ca6643e56018793d1f7a3c9897832f | 9898c51c69aaa49bd68b6ae607bfce6f7df22267 | /GB2017A.java | e6f1e0dd5b3ed92e172a1e245080e2ee254b7e06 | [] | no_license | toufiq-austcse/Codeforces | bc2104544fee1eb8fd21024b33999596a10132c5 | 2e96498ad5e7fee490eb4097741f97b05b861822 | refs/heads/master | 2021-09-18T13:08:24.920359 | 2018-07-14T13:17:35 | 2018-07-14T13:17:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,931 | java | package CodeForces;
/*In the name of Allah the Most Merciful.
* Author
* Md. Toufiqul Islam
* Dept. Of CSE
* Ahsanullah University Of Science And Technology
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class GB2017A {
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
String s = sc.next();
int count =0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u'){
count++;
}
else if(s.charAt(i)=='1'||s.charAt(i)=='3'||s.charAt(i)=='5'||s.charAt(i)=='7'||s.charAt(i)=='9'){
count++;
}
}
out.println(count);
out.close();
}
public static class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n){
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n){
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n){
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n){
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n){
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n){
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
public static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(double[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(double[] array) {
print(array);
writer.println();
}
public void println(long[] array) {
print(array);
writer.println();
}
public void println() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void println(char i) {
writer.println(i);
}
public void println(char[] array) {
writer.println(array);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void println(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
public void separateLines(int[] array) {
for (int i : array) {
println(i);
}
}
}
}
| [
"[email protected]"
] | |
4d6a91a4b9ca47c31581b36664c1eab3ca17c27d | 36dfa297632f9a3c7481e7db0cc5a40629182422 | /src/DynamicProgramming/MinPathSum.java | e377f3abef40478a1b08984db7b71c560677332c | [] | no_license | jalatif/LeetCode | 8b9c2512d3c35c8e95425562aae8a49f90a60339 | 5302bf34c313dd7b8224a62ea158671153b3d6be | refs/heads/master | 2016-09-05T14:32:21.658512 | 2015-04-29T00:28:46 | 2015-04-29T00:28:46 | 29,796,065 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,257 | java | package DynamicProgramming;
/**
* Created by manshu on 1/26/15.
*/
public class MinPathSum {
private static int cache[][];
private static int minPathSum(int[][] grid, int i, int j) {
int m = grid.length;
int n = grid[0].length;
if (i == (m - 1) && j == (n - 1)) return grid[i][j];
if (i >= m || j >= n) return Integer.MAX_VALUE;
if (cache[i][j] != 0) return cache[i][j];
cache[i][j] = grid[i][j] + Math.min(minPathSum(grid, i + 1, j), minPathSum(grid, i, j + 1));
return cache[i][j];
}
public static int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
cache = new int[m][n];
int a = minPathSum(grid, 0, 0);
System.out.println();
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++)
System.out.print(cache[i][j] + " ");
System.out.println();
}
return a;
}
public static void main(String[] args) {
int arr[][] = {
{1, 4, 2},
{0, 5, 3},
{6, 2, 9},
};
System.out.println(minPathSum(arr));
}
}
| [
"[email protected]"
] | |
8ea6accd163cb2d52b74f88718d43ebebda255d8 | 42e32ba16596cd733a1b4e5e1fe029c593ebdace | /app/src/main/java/com/example/chen/tset/page/adapter/LectureListAdapter.java | 69bfa0c870d475a0d3b8b04ba1b06f7e50a27c5c | [] | no_license | chxxbb/TSET | 6d3eeb210071d1fdeeae1f60014944664bf6c62d | f95e1f7fc2e50650b4e26da5f8a6bd12b0d80152 | refs/heads/master | 2020-09-10T02:54:32.022115 | 2016-12-28T08:05:04 | 2016-12-28T08:05:04 | 66,424,028 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,794 | java | package com.example.chen.tset.page.adapter;
import android.content.Context;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.chen.tset.R;
import java.util.List;
/**
* Created by Administrator on 2016/11/8 0008.
*/
public class LectureListAdapter extends BaseAdapter{
private List<String> list;
Context context;
public LectureListAdapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public String getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.lecture_list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
TextPaint tp = viewHolder.textView1.getPaint();
tp.setFakeBoldText(true);
viewHolder.textView.setText("李狗蛋"+list.get(position)+"号 / 25'61'");
return convertView;
}
static class ViewHolder {
TextView textView;
TextView textView1;
ViewHolder(View v) {
textView= (TextView) v.findViewById(R.id.textView);
textView1= (TextView) v.findViewById(R.id.textView1);
}
}
}
| [
"[email protected]"
] | |
ea6981dd1fa3dc533eab90af899bd57b8c7dab42 | 82b2f9b86b0904e472b80ed6e875002457f6fe3c | /src/main/java/cn/takovh/javaBasic/c_14_JDBC/Demo5.java | e2727fc9fa37f70ccb90379a9331ca6fc581f36e | [] | no_license | takovh/JavaBasic | 82817ed89fb5c2accda31877473565541c416012 | e0fbdb13b8f13adb34d333821244057431ad5c6f | refs/heads/master | 2022-07-12T08:12:32.238768 | 2020-12-20T15:29:37 | 2020-12-20T15:29:37 | 214,377,979 | 0 | 0 | null | 2022-06-21T02:01:21 | 2019-10-11T07:59:26 | Java | UTF-8 | Java | false | false | 1,613 | java | package cn.takovh.javaBasic.c_14_JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 测试批处理的基本用法
* @author tako_
*
*/
public class Demo5 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//建立连接
conn = DriverManager.getConnection("c_14_JDBC:mysql://localhost:3306/testjdbc","root","111111");
conn.setAutoCommit(false);//事务设置关闭自动提交
stmt = conn.createStatement();
long start = System.currentTimeMillis();
for(int i=0;i<20000;i++) {
stmt.addBatch("insert into t_user(username,pwd,regTime) values('zhang"+i+"',666666,now())");
}
stmt.executeBatch();
conn.commit();//提交事务
long end = System.currentTimeMillis();
System.out.println("插入20000条数据耗时:" + (end-start) + "ms");
} catch (ClassNotFoundException e) {
System.err.println("数据库加载失败");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关闭顺序遵循:resultSet-->statement-->connection,三个块一定要分开写
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| [
"[email protected]"
] | |
21db368a51221f120a6719259f39b5be2f7fc43c | 177fd311aec0e0a7f112b481636d71ebfec6c803 | /ProyectoClienteHospitalSW/src/serviciosweb/Listar.java | 0e743fbc53b93e75bdf18701905f1966fedb0bba | [] | no_license | cristian1599/AplicacionClienteSW | 7d763e5e53de47ce128eb637f39f66b568debafd | 9e3f4288412453c94a7089fa54d4326156995615 | refs/heads/master | 2022-12-06T14:49:36.535069 | 2020-09-01T15:06:00 | 2020-09-01T15:06:00 | 292,028,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 655 | java |
package serviciosweb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for listar complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="listar">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listar")
public class Listar {
}
| [
"[email protected]"
] | |
dbc90723d44dbaf2c4a92eeb78ca16d85b97483a | 91ab26fbef42207c308ed31055b432a266c6590b | /src/main/java/enegade/uml/debugger/stepmethodcall/ConditionDecorator.java | abf69a367bf635b4d3faaeaebbd47408c2e0710f | [
"Apache-2.0"
] | permissive | enegade/uml | 35c625205b1394fcf97e3d8881fb5c5588a837e7 | 5fd7d323837aa64527d01177e124f835cdd3dd6a | refs/heads/master | 2023-05-11T21:18:16.691458 | 2021-05-27T08:07:22 | 2021-05-27T08:07:22 | 330,693,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,578 | java | package enegade.uml.debugger.stepmethodcall;
/*
* Copyright 2020 enegade
*
* This file is part of the enegade.uml package.
*
* This file is distributed "AS IS", WITHOUT ANY WARRANTIES.
*
* For the full copyright and license information, please view the LICENSE
* file distributed with this project.
*/
import com.sun.jdi.ThreadReference;
import enegade.uml.CallGraph;
import enegade.uml.type.MethodCall;
import enegade.uml.type.StepInfo;
import enegade.uml.debugger.ConditionTask;
import enegade.uml.jdi.StepDebuggerEvent;
import enegade.uml.state.StateBuilder;
import java.util.List;
/**
* @author enegade
*/
public class ConditionDecorator extends BaseDecorator
{
private CallGraph callGraph;
private ConditionTask conditionTask;
private boolean conditionExited = false;
public ConditionDecorator(StepMethodCallTask task, CallGraph callGraph, ConditionTask conditionTask)
{
super(task);
this.callGraph = callGraph;
this.conditionTask = conditionTask;
}
@Override
public void handleInitialState(ThreadReference thread, StateBuilder stateBuilder)
{
task.handleInitialState(thread, stateBuilder);
this.conditionExited = false;
}
@Override
public void handleStepState(StepDebuggerEvent debuggerEvent, StateBuilder stateBuilder) {
super.handleStepState(debuggerEvent, stateBuilder);
this.conditionExited = false;
if( !this.conditionTask.isConditionStarted() ) {
return;
}
System.out.println("condition");
CallGraph.EntranceView entranceView = this.callGraph.getEntranceView();
MethodCall currentMethod = entranceView.getMethodCall().get();
if( currentMethod != this.conditionTask.getConditionMethod() ) {
return;
}
List<StepInfo> stepInfos = entranceView.getStepInfoList();
if (!stepInfos.isEmpty()) {
StepInfo stepInfo = stepInfos.get(stepInfos.size() - 1);
// if( stepInfo.getLineNumber() == 82 ) {
if (stepInfo.getCodeIndex() == 49) {
this.callGraph.closeEntrance();
this.conditionExited = true;
this.conditionTask.exitCondition();
stateBuilder.clearRequests();
}
}
}
@Override
public boolean isConditionExited()
{
return this.conditionExited;
}
@Override
public ConditionTask.CONDITION_SOURCE getConditionSource()
{
return this.conditionTask.getConditionSource();
}
}
| [
"username"
] | username |
ced6ed90a268bbb45777e584ba564f10de405624 | 2286dbc2c27059bfa9c6721de050b3328565d866 | /src/main/java/com/pixelmed/query/QueryTreeBrowser.java | b5cf078411af22f0fd90cb9288760dd40b781cac | [
"MIT"
] | permissive | anniyanvr/nifi-dicom | ae58a48f189c474a14f961cbc8ca6dc9c360c23a | f8616408bda79b3f18845fa156d2f623b6e8bcfc | refs/heads/master | 2023-07-17T06:02:41.369860 | 2021-09-03T12:55:32 | 2021-09-03T12:55:32 | 276,812,772 | 0 | 0 | MIT | 2021-09-03T17:34:34 | 2020-07-03T05:10:40 | null | UTF-8 | Java | false | false | 9,622 | java | /* Copyright (c) 2001-2017, David A. Clunie DBA Pixelmed Publishing. All rights reserved. */
package com.pixelmed.query;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.util.*;
import java.io.*;
import com.pixelmed.dicom.*;
import com.pixelmed.utils.JTreeWithAdditionalKeyStrokeActions;
/**
* <p>The {@link com.pixelmed.query.QueryTreeBrowser QueryTreeBrowser} class implements a Swing graphical user interface
* to browse the contents of {@link com.pixelmed.query.QueryTreeModel QueryTreeModel}.</p>
*
* <p>The browser is rendered as a tree view of the returned query identifier and a one row tabular representation of the
* contents of any level that the user selects in the tree. Constructors are provided to either add
* the browser to a frame and creating the tree and table, or to make use of a pair of existing scrolling
* panes.</p>
*
* <p>Though a functional browser can be built using this class, to add application-specific behavior
* to be applied when a user selects from the tree, a sub-class inheriting
* from this class should be constructed that overrides the
* {@link #buildTreeSelectionListenerToDoSomethingWithSelectedLevel() buildTreeSelectionListenerToDoSomethingWithSelectedLevel}
* method The default implementation is as follows:</p>
*
* <pre>
* protected TreeSelectionListener buildTreeSelectionListenerToDoSomethingWithSelectedLevel() {
* return new TreeSelectionListener() {
* public void valueChanged(TreeSelectionEvent tse) {
* TreePath tp = tse.getNewLeadSelectionPath();
* if (tp != null) {
* Object lastPathComponent = tp.getLastPathComponent();
* if (lastPathComponent instanceof QueryTreeRecord) {
* QueryTreeRecord r = (QueryTreeRecord)lastPathComponent;
* System.err.println("TreeSelectionListener.valueChanged: "+r.getUniqueKeys());
* }
* }
* }
* };
* }
* </pre>
*
* @see com.pixelmed.query
* @see com.pixelmed.query.QueryTreeRecord
* @see com.pixelmed.query.QueryTreeModel
* @see javax.swing.tree.TreePath
* @see javax.swing.event.TreeSelectionListener
*
* @author dclunie
*/
public class QueryTreeBrowser {
private static final String identString = "@(#) $Header: /userland/cvs/pixelmed/imgbook/com/pixelmed/query/QueryTreeBrowser.java,v 1.18 2017/01/24 10:50:46 dclunie Exp $";
private JTree tree;
private QueryTreeModel treeModel;
private QueryInformationModel queryInformationModel;
/**
* <p>Build and display a graphical user interface view of a database information model.</p>
*
* @param q the query information model
* @param m the query tree model (i.e. the results returned from an actual query)
* @param treeBrowserScrollPane the scrolling pane in which the tree view of the query results will be rendered
* @param attributeBrowserScrollPane the scrolling pane in which the tabular view of the currently selected level will be rendered
* @throws DicomException thrown if the information cannot be extracted
*/
public QueryTreeBrowser(QueryInformationModel q,QueryTreeModel m,JScrollPane treeBrowserScrollPane,JScrollPane attributeBrowserScrollPane) throws DicomException {
queryInformationModel=q;
treeModel=m;
tree=new JTreeWithAdditionalKeyStrokeActions(treeModel);
treeBrowserScrollPane.setViewportView(tree);
tree.addTreeSelectionListener(buildTreeSelectionListenerToDisplayAttributesOfSelectedRecord(attributeBrowserScrollPane));
tree.addTreeSelectionListener(buildTreeSelectionListenerToDoSomethingWithSelectedLevel());
}
/**
* <p>Build and display a graphical user interface view of a database information model.</p>
*
* @param q the query information model
* @param m the query tree model (i.e. the results returned from an actual query)
* @param content content pane will to add scrolling panes containing tree and tabular selection views
* @throws DicomException thrown if the information cannot be extracted
*/
public QueryTreeBrowser(QueryInformationModel q,QueryTreeModel m,Container content) throws DicomException {
queryInformationModel=q;
treeModel=m;
tree=new JTreeWithAdditionalKeyStrokeActions(treeModel);
JScrollPane treeBrowserScrollPane = new JScrollPane(tree);
JScrollPane attributeBrowserScrollPane = new JScrollPane();
final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,treeBrowserScrollPane,attributeBrowserScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(0.7);
//splitPane.setDividerLocation(1.0); // setDividerLocation(1.0) to collapse bottom (attribute) pane doesn't work until split pane is actually shown ...
// based on jaydsa's suggestion at "http://java.itags.org/java-swing/43801/" but use ComponentListener instead ofHierarchyListener() ...
splitPane.addComponentListener(new ComponentListener() {
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {
//System.err.println("DoseUtility.OurSourceDatabaseTreeBrowser.componentResized(): event = "+e);
splitPane.setDividerLocation(1.0);
}
public void componentShown(ComponentEvent e) {}
});
content.add(splitPane);
tree.addTreeSelectionListener(buildTreeSelectionListenerToDisplayAttributesOfSelectedRecord(attributeBrowserScrollPane));
tree.addTreeSelectionListener(buildTreeSelectionListenerToDoSomethingWithSelectedLevel());
}
/**
* <p>Build and display a graphical user interface view of a database information model.</p>
*
* @param q the query information model
* @param m the query tree model (i.e. the results returned from an actual query)
* @param frame a frame to whose content pane will be added scrolling panes containing tree and tabular selection views
* @throws DicomException thrown if the information cannot be extracted
*/
public QueryTreeBrowser(QueryInformationModel q,QueryTreeModel m,JFrame frame) throws DicomException {
this(q,m,frame.getContentPane());
}
/**
* <p>Return the records currently selected.</p>
*
* @return the records currently selected
*/
public QueryTreeRecord[] getSelectionPaths() {
ArrayList<QueryTreeRecord> records = new ArrayList<QueryTreeRecord>();
TreeSelectionModel selectionModel = tree.getSelectionModel();
if (selectionModel != null) {
TreePath[] paths = selectionModel.getSelectionPaths();
if (paths != null && paths.length > 0) {
for (TreePath path : paths) {
if (path != null) {
Object lastPathComponent = path.getLastPathComponent();
if (lastPathComponent instanceof QueryTreeRecord) {
QueryTreeRecord r = (QueryTreeRecord)lastPathComponent;
//System.err.println("QueryTreeBrowser.getSelectionPaths(): "+r.getUniqueKeys());
records.add(r);
}
}
}
}
}
QueryTreeRecord[] returnValues = new QueryTreeRecord[records.size()];
return records.toArray(returnValues);
}
/**
* <p>Override this method to perform application-specific behavior when an entity is selected in the tree browser.</p>
*
* <p>By default this method dumps the string values of the unique keys to the console for level selection,
* which is pretty useless.</p>
*/
protected TreeSelectionListener buildTreeSelectionListenerToDoSomethingWithSelectedLevel() {
return new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
TreePath tp = tse.getNewLeadSelectionPath();
if (tp != null) {
Object lastPathComponent = tp.getLastPathComponent();
if (lastPathComponent instanceof QueryTreeRecord) {
QueryTreeRecord r = (QueryTreeRecord)lastPathComponent;
//System.err.println("TreeSelectionListener.valueChanged: "+r.getUniqueKeys());
}
}
}
};
}
/**
* <p>By default this method populates the tabular attribute browser when an entity is selected in the tree browser.</p>
*
* <p>Override this method to perform application-specific behavior, perhaps if not all attributes
* in the query identifer for the selected level are to be displayed, or their values are to be rendered
* specially. The default implementation renders everything as strings.</p>
*
* @param attributeBrowserScrollPane the tabular attribute browser
*/
protected TreeSelectionListener buildTreeSelectionListenerToDisplayAttributesOfSelectedRecord(final JScrollPane attributeBrowserScrollPane) {
return new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse) {
TreePath tp = tse.getNewLeadSelectionPath();
//System.err.println("QueryTreeBrowser.TreeSelectionListener.valueChanged(): "+tp);
if (tp != null) {
Object lastPathComponent = tp.getLastPathComponent();
if (lastPathComponent instanceof QueryTreeRecord) {
//System.err.println("QueryTreeBrowser.TreeSelectionListener.valueChanged(): lastPathComponent="+lastPathComponent);
QueryTreeRecord r = (QueryTreeRecord)lastPathComponent;
AttributeList identifier = r.getAllAttributesReturnedInIdentifier();
//System.err.println("QueryTreeBrowser.TreeSelectionListener.valueChanged(): identifier="+identifier);
if (identifier != null) {
HashSet includeList = null;
HashSet excludeList = null;
AttributeListTableBrowser table = new AttributeListTableBrowser(identifier,includeList,excludeList);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Otherwise horizontal scroll doesn't work
table.setColumnWidths();
attributeBrowserScrollPane.setViewportView(table);
}
}
}
}
};
}
}
| [
"[email protected]"
] | |
348ffd89f2a7f0cf2feadd7d62bc178f2d2bd04d | 9ab179670574ccac01f489076186d6e07842e050 | /src/de/endrullis/idea/postfixtemplates/languages/python/PythonPostfixTemplatesUtils.java | 7837b68ec5bde7d6665bc7129d6ee1af8e6fe99c | [
"Apache-2.0"
] | permissive | 543229143/intellij-postfix-templates | df721e3252e239dadd6e7643ef3f22cc94bbbf76 | 0bce5f3106d274cdf6e1a2f9551188b09ddf5049 | refs/heads/master | 2020-04-22T03:39:40.231470 | 2019-02-11T09:23:37 | 2019-02-11T09:23:37 | 170,095,771 | 0 | 0 | Apache-2.0 | 2019-02-11T08:45:04 | 2019-02-11T08:45:03 | null | UTF-8 | Java | false | false | 1,404 | java | package de.endrullis.idea.postfixtemplates.languages.python;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiElement;
import com.jetbrains.python.psi.PyPsiFacade;
import com.jetbrains.python.psi.PyTypedElement;
import com.jetbrains.python.psi.PyUtil;
import com.jetbrains.python.psi.impl.PyTypeProvider;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.pyi.PyiTypeProvider;
import org.jetbrains.annotations.NotNull;
/**
* Utilities for Python postfix templates.
*
* @author Stefan Endrullis <[email protected]>
*/
class PythonPostfixTemplatesUtils {
/*
@NotNull
static Condition<PsiElement> isCustomClass(String clazz) {
PyTypeProvider tp;
PyType t;
t.isBuiltin()
PyPsiFacade.getInstance(null).createClassByQName()
return e -> e instanceof PyTypedElement && TypeEvalContext.codeAnalysis(e.getProject(), e.getContainingFile()).getType((PyTypedElement) e);
}
private static boolean isCustomClass(SqlType sqlType, String type) {
return StringUtils.substringBefore(sqlType.getDisplayName(), "(").equals(type);
}
static Condition<PsiElement> isCategory(SqlType.Category category) {
return element -> element instanceof SqlExpression && ((SqlExpression) element).getSqlType().getCategory().equals(category);
}
*/
}
| [
"[email protected]"
] | |
cc19fc5d9d2440cba139e2f2da1fd7ba62ecb2b6 | a3f933747121bf35a043f623916e73e441a02132 | /src/main/java/com/wanghang/code/design/callback/CallBacKDemo.java | 5b0613721cf7a836856837744029487d4cb2151d | [] | no_license | wanghang88/wanghang-learning | 38b53da6281df826bd0191d1c01612c3f708a2cd | a8a3f11d6d66b74de01742a7b342f5600a153f4e | refs/heads/master | 2022-06-24T13:51:46.713661 | 2021-12-17T16:30:33 | 2021-12-17T16:30:33 | 178,580,438 | 0 | 2 | null | 2022-06-17T03:34:15 | 2019-03-30T16:02:20 | Java | UTF-8 | Java | false | false | 1,623 | java | package com.wanghang.code.design.callback;
import com.wanghang.code.design.callback.student.Student;
import com.wanghang.code.design.callback.student.WangHang;
/**
*java的回调机制:
*在一个应用系统中,在模块之间的调用方式
* 1)同步调用:
* 类A的方法a()调用类B的方法b(),一直等待b()方法执行完毕,a()方法继续往下走,这种调用方式适用于方法b()执行时间不长的情况,
* 因为如果b()方法执行过长或者阻塞的话,a()方法余下的代码无法执行下去,造成整个流程阻塞。
*2)异步调用:
*类A的方法方法a()通过新起线程的方式调用类B的方法b(),代码接着直接往下执行,但是这种方式,a()方法不必等b()方法执行完,若a()需要b()执行结果的,
* 就必须对b()的执行结果进行监听,在java中可以使用Future+Callable的方式做到这一点(Callable+Future组件介绍 https://www.cnblogs.com/xrq730/p/4872722.html)
*
*3)还有一种方式能处理这种场景:回调
* 回调的思想是:
* 类A的a()方法调用类B的b()方法,
* 类B的b()方法执行完毕主动调用类A的callback()方法。
*
*4)演示案例场景:
* 老师问学生问题,
* 学生思考完毕
* 回答老师
*/
public class CallBacKDemo {
public static void main(String[] args) {
Student student = new WangHang();
Teacher teacher = new Teacher(student);
//1:老师调用学生接口的方法resolveQuestion(),向学生提问
//2:学生解决完毕问题之后调用老师的回调方法tellAnswe()
teacher.askQuestion();
}
}
| [
"[email protected]"
] | |
e16e5fcdac54f2c3f43007e5fffd45cf8c07ba1b | 83f83b95da247912e3a139a1802bc396b204d674 | /src/oop/inter/Daughter.java | 85c3f54b2e68f4c8b559951896bfc736ae219357 | [] | no_license | Runtym/java-study | 55351acbbf7a8c05258a599bf895a34f41f0a49d | 6ed31549b362ab95ed749230cb2ffa1bb1bcdccb | refs/heads/master | 2020-04-22T13:51:23.679206 | 2019-03-27T06:37:50 | 2019-03-27T06:37:50 | 170,423,996 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package oop.inter;
import oop.inherit.Mother;
public class Daughter extends Mother{
public Daughter() {
this("엄마~");
}
public Daughter(String str) {
super("엄마~");
}
public static void main(String[] args) {
Daughter d = new Daughter();
System.out.println(d.money);
System.out.println(d.getMoney());
}
}
| [
"[email protected]"
] | |
d1f2247b0ea3f58851c5210c70273a1a0b8f5ef2 | 14d06b6ae86b32d2b45175a983567ff8441c32ec | /src/org/appwork/utils/swing/table/ExtTableEventSender.java | 4fa17f3324090211c82abe258e56371999699fbd | [
"Artistic-2.0"
] | permissive | Horstman/AppWorkUtils | 60e47ba732fdd2bd485ea4daa13facfbc329bd97 | ce5250409edd29eda0b7ac94be94c7109ec898ed | refs/heads/master | 2021-01-20T07:13:59.417701 | 2011-05-27T08:20:09 | 2011-05-27T08:20:09 | 1,811,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 891 | java | /**
* Copyright (c) 2009 - 2010 AppWork UG(haftungsbeschränkt) <[email protected]>
*
* This file is part of org.appwork.utils.swing.table
*
* This software is licensed under the Artistic License 2.0,
* see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php
* for details
*/
package org.appwork.utils.swing.table;
import org.appwork.utils.event.Eventsender;
/**
* @author thomas
*
*/
public class ExtTableEventSender extends Eventsender<ExtTableListener, ExtTableEvent<?>> {
/*
* (non-Javadoc)
*
* @see
* org.appwork.utils.event.Eventsender#fireEvent(java.util.EventListener,
* org.appwork.utils.event.DefaultEvent)
*/
@Override
protected void fireEvent(final ExtTableListener listener, final ExtTableEvent<?> event) {
listener.onExtTableEvent(event);
}
}
| [
"thomas@21714237-3853-44ef-a1f0-ef8f03a7d1fe"
] | thomas@21714237-3853-44ef-a1f0-ef8f03a7d1fe |
60e4a54772d266ff5989bd5cf4adeb9604fa9d93 | 29e40a71ad98f02d54a20d6b1c867588bccc3345 | /src/com/namanraj/testing/ai/AiWikipediaSlow.java | 9810f260373a9d58e5111cbd4ad2cf202cb55bea | [] | no_license | raj-naman/SoftwareTestingProject | cd8597a214fcfd52dc9a8f787d8d5158bbd8a2e0 | dedab388ed40b2c05083b49da62b17bcb74739d2 | refs/heads/master | 2020-09-11T14:20:27.556021 | 2019-11-16T12:39:05 | 2019-11-16T12:39:05 | 222,094,743 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,423 | java | package com.namanraj.testing.ai;
/**
A partial implementation from the wikipedia rules.
http://en.wikipedia.org/wiki/Tic-tac-toe#Strategy
1) Win: If you have two in a row, play the third to get three in a row.
2) Block: If the opponent has two in a row, play the third to block them.
3) Fork: Create an opportunity where you can win in two ways.
4) Block Opponent's Fork:
Option 1: Create two in a row to force the opponent into defending,
as long as it doesn't result in them creating a fork or winning.
For example, if "X" has a corner, "O" has the center, and "X" has the
opposite corner as well, "O" must not play a corner in order to win.
(Playing a corner in this scenario creates a fork for "X" to win.)
TODO: Implement
Option 2: If there is a configuration where the opponent can fork, block that fork.
TODO: Implement
5) Center: Play the center.
6) Middle: If the opponent is in the corner, play a center of that
row or column.
7) Empty Corner: Play in a corner square.
8) Empty Side: Play in a middle square on any of the 4 sides.
*/
public class AiWikipediaSlow extends Ai {
public int makeMove(char playersMarker, char[] boardArray)
{
char opponentMarker = getOpponentMarker(playersMarker);
try {
step01_win(playersMarker,opponentMarker,boardArray);
step02_blockWin(playersMarker,opponentMarker,boardArray);
step03_fork(playersMarker,opponentMarker,boardArray);
step05_playCenter(playersMarker, opponentMarker, boardArray);
step06_twoInARow(playersMarker, opponentMarker, boardArray);
step07_playEmptyCorner(playersMarker, opponentMarker, boardArray);
step08_playEmptySide(playersMarker, opponentMarker, boardArray);
} catch (AiMove e) {
moveHistory += e.getMoveDisplay();
return e.getSquare();
}
System.exit(0);
return -1;
}
private char getOpponentMarker(char playersMarker) {
char opponentMarker = ' ';
if(playersMarker=='X')
{
opponentMarker='O';
}
else
{
opponentMarker='X';
}
return opponentMarker;
}
public void step01_win(char playersMarker, char opponentMarker, char boardArray[]) throws AiMove
{
int winLines[][] = {
{1,2,3},{4,5,6},{7,8,9},
{1,4,7},{2,5,8},{3,6,9},
{1,5,9},{3,5,7}
};
for(int winLine[]:winLines)
{
int playerMarkerCount = 0;
int openSquare = -1;
for(int square:winLine)
{
if(boardArray[square-1]==playersMarker)
{
playerMarkerCount++;
}
if(boardArray[square-1]==' ')
{
openSquare = square;
}
}
if(playerMarkerCount==2 && openSquare > 0)
{
throw new AiMove("Win",boardArray,openSquare);
}
}
}
public void step02_blockWin(char playersMarker, char opponentMarker, char boardArray[]) throws AiMove
{
int winLines[][] = {
{1,2,3},{4,5,6},{7,8,9},
{1,4,7},{2,5,8},{3,6,9},
{1,5,9},{3,5,7}
};
for(int winLine[]:winLines)
{
int opponentMarkerCount = 0;
int openSquare = -1;
for(int square:winLine)
{
if(boardArray[square-1]==opponentMarker)
{
opponentMarkerCount++;
}
if(boardArray[square-1]==' ')
{
openSquare = square;
}
}
if(opponentMarkerCount==2 && openSquare > 0)
{
throw new AiMove("Block",boardArray,openSquare);
}
}
}
public void step03_fork(char playersMarker, char opponentMarker, char boardArray[]) throws AiMove
{
int forkSquares[][] = {
{7,4,1,2,3}, // Corner L's
{1,2,3,6,9},
{3,6,9,8,7},
{9,8,7,4,1},
{1,2,3,5,7}, // 45 Angle with row
{3,2,1,5,9},
{3,5,7,8,9},
{1,5,9,8,7},
{1,4,7,5,3}, // 45 angle with col
{7,4,1,5,9},
{3,6,9,5,1},
{9,6,3,5,7}
};
for(int[] square:forkSquares)
{
if(
boardArray[square[0]-1]==playersMarker &&
boardArray[square[1]-1]==' ' &&
boardArray[square[2]-1]==' ' &&
boardArray[square[3]-1]==' ' &&
boardArray[square[4]-1]==playersMarker)
{
throw new AiMove("Fork",boardArray,square[2]);
}
}
}
public void step05_playCenter(char playersMarker,char opponentMarker, char boardArray[]) throws AiMove
{
if(boardArray[5-1]==' ')
{
throw new AiMove("Center",boardArray,5);
}
}
public void step06_twoInARow(char playersMarker,char opponentMarker, char boardArray[]) throws AiMove
{
int lSquares[][] = {{1,2,4},{3,2,6},{7,4,8},{9,6,8}};
for(int[] square:lSquares)
{
if(boardArray[square[0]-1]==opponentMarker)
{
if(boardArray[square[1]-1]==' ')
{
throw new AiMove("Middle",boardArray,square[1]);
}
if(boardArray[square[2]-1]==' ')
{
throw new AiMove("Middle",boardArray,square[2]);
}
}
}
}
public void step07_playEmptyCorner(char playersMarker,char opponentMarker, char boardArray[]) throws AiMove
{
int bestSquares[] = {1,3,7,9};
for(int square:bestSquares)
{
if(boardArray[square-1]==' ')
{
throw new AiMove("Empty corner",boardArray,square);
}
}
}
public void step08_playEmptySide(char playersMarker,char opponentMarker, char boardArray[]) throws AiMove
{
int bestSquares[] = {2,6,8,4};
for(int square:bestSquares)
{
if(boardArray[square-1]==' ')
{
throw new AiMove("Empty Side",boardArray,square);
}
}
}
}
| [
"[email protected]"
] | |
debf288e118c427d8f06c5334fdfa334413902da | b0b53a9ed47ee4be93ce98b2cf870fea675a66c9 | /CYBER/src/com/example/cyber/Soalhitung1.java | 597f720d0dfba3628ae938bd7b9db0e306ada383 | [] | no_license | Mikroskil/Ketumbar | b61bd41be47cc97d179bd20011f9e3d96850a2e4 | 1c676c6e034935d69dcdb4c9c0bd592d12444ae9 | refs/heads/master | 2020-04-24T13:04:12.249540 | 2014-01-23T09:43:14 | 2014-01-23T09:43:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,795 | java | package com.example.cyber;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
public class Soalhitung1 extends Activity {
MediaPlayer mp;
ImageButton one ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.soalhitung1);
ketikarrowback();
ketikmikia();
ketikmikib();
ketikmikic();
ketikarrowkiri();
ketikarrowkanan();
}
protected void ketikarrowback(){
final Context context = this;
ImageButton arrow = (ImageButton) findViewById(R.id.arrowback);
arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b) {
Intent intent = new Intent(context,Berhitung.class);
startActivity(intent);
}
});
}
protected void ketikmikia(){
final Context context = this;
ImageButton arrow = (ImageButton) findViewById(R.id.mikia);
arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b1) {
Intent intent = new Intent(context,Ketikabenar.class);
startActivity(intent);
}
});
}
protected void ketikmikib(){
final Context context = this;
ImageButton arrow = (ImageButton) findViewById(R.id.mikib);
arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b1) {
Intent intent = new Intent(context,Ketikasalah.class);
startActivity(intent);
}
});
}
protected void ketikmikic(){
final Context context = this;
ImageButton arrow = (ImageButton) findViewById(R.id.mikic);
arrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b1) {
Intent intent = new Intent(context,Ketikasalah.class);
startActivity(intent);
}
});
}
protected void ketikarrowkiri(){
final Context context = this;
ImageButton btn1 = (ImageButton)findViewById(R.id.leftarrow);
btn1.setOnClickListener(new OnClickListener(){
public void onClick (View a){
Intent intent = new Intent(context,Soalhitung6.class);
startActivity(intent);
}
});
}
protected void ketikarrowkanan(){
final Context context = this;
ImageButton btn2 = (ImageButton)findViewById(R.id.rightarrow);
btn2.setOnClickListener(new OnClickListener(){
public void onClick (View a2){
Intent intent = new Intent(context,Soalhitung2.class);
startActivity(intent);
}
});
}
}
| [
"[email protected]"
] | |
c5887ff264f5dc626aa1df60aecba488504697bf | d1f250427c041bf90349b59e9dafb853d687da71 | /src/TREE/G_거의최대공약수_중상.java | fcfcaf0da52713fb0937db808359c93c3a64ffa7 | [] | no_license | staeminba/Algorithm | ef4e711fd015ad712c278338ed16163e12e9eb19 | 96cd58cb918725e1efcb2c30f064c32797b6d77d | refs/heads/master | 2021-07-04T14:03:00.267870 | 2020-10-22T05:01:50 | 2020-10-22T05:01:50 | 191,584,349 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,730 | java | package TREE;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class G_거의최대공약수_중상 {
static int N, M;
static int[] arr;
static long[] tree;
static int leaf;
static long result;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
arr = new int[N + 1];
leaf = 1 << (int) (Math.ceil(Math.log10(N) / Math.log10(2)));
tree = new long[leaf << 1];
st = new StringTokenizer(br.readLine());
for (int i = 1; i <= N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
init();
for (int i = 1; i <= N; i++) {
int temp = arr[i];
//arr[i] = 0;
//init();
result = Math.max(result , gcd(sum(1,i-1), sum(i+1,N)));
//arr[i] = temp;
}
System.out.println(result);
}
private static long sum(int l, int r) {
// TODO Auto-generated method stub
long res = 0;
l += (leaf - 1);
r += (leaf - 1);
// System.out.println("leaf : " + leaf + " l : " + l + " r : " + r);
while (l < r) {
if ((l % 2) != 0) { // 홀수면
res = gcd(tree[l],res);
l++;
}
if ((r % 2) == 0) {
res = gcd(tree[r],res);
r--;
}
l >>= 1;
r >>= 1;
}
//System.out.println(l+"," + r + " res : " + res + " tree[l] : " + tree[l]);
if (l == r)
res = gcd(res,tree[l]);
return res;
}
private static void update(int idx, int val) {
// TODO Auto-generated method stub
idx += (leaf - 1);
long diff = val - tree[idx];
tree[idx] = val;
/*
* while(idx >= 2){ idx >>= 1; tree[idx] += diff; }
*/
while (idx >= 2) {
idx >>= 1;
tree[idx] += diff;
}
}
private static void init() {
// TODO Auto-generated method stub
for (int i = leaf; i < leaf + N; i++)
tree[i] = arr[i - leaf + 1];
for (int i = leaf - 1; i > 0; i--) {
long a = tree[i<<1];
long b = tree[(i<<1)+1];
tree[i] = gcd(tree[i << 1], tree[(i << 1) + 1]);
}
}
private static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a%b);
}
} | [
"[email protected]"
] | |
09038ded79937433cf0e8b824a4096b4d6038e0d | eb84db93ad84e31888fffc6ee3b31806f24cbcf2 | /Quiz/src/quiz10/Player.java | 7264b1b1e0d1f1a4ef60f790d028dc9fbe5681f7 | [] | no_license | Hyunworld/javabasicworkspace | ee45ea6eecc5c2c6914d97f1f9c1398ccf4ca5c4 | 15db31cdc59f665844ce84d875341d2675b101ce | refs/heads/master | 2023-05-29T10:13:26.419555 | 2021-06-08T07:01:19 | 2021-06-08T07:01:19 | 374,912,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 328 | java | package quiz10;
public class Player {
String id;
int hp; //체력
int mp; //마나
int attack; //공격력
int armor; //방어력
void info() {
System.out.println("케릭명:" + id);
System.out.println("체력:" + hp + ",마나:" + mp);
System.out.println("공격력:" + attack + ",방어력:" + armor);
}
}
| [
"[email protected]"
] | |
b3aa13b215a264fbe28add1a3a1a4c0f16db07df | 522f1a47ae8ece10d066d02b9552c898415cfd8c | /Perpusoft/src/backend/DetilPeminjaman.java | e536431d28c4d21343e3b10295488c8ecd6d1671 | [] | no_license | RizalTH/perpustakaanKelompok2 | 927ac4c957d74236c553c50030f4e422f860c494 | 5c1181a778070cc5f5be87c30525168f1e99199d | refs/heads/master | 2020-12-01T04:32:53.515383 | 2020-01-10T13:09:54 | 2020-01-10T13:09:54 | 230,558,638 | 2 | 4 | null | null | null | null | UTF-8 | Java | false | false | 2,797 | java | package backend;
//import method from class CRUD
import backend.interfaces.CRUD;
import javax.swing.table.DefaultTableModel;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DetilPeminjaman {
// Deklarasi MySql
Connection con;
Statement stm;
Statement stmm;
DBKoneksi DB = new DBKoneksi();
// Class Konstruktor
public DetilPeminjaman() {
// Konek ke Database
DB.connect();
con = DB.con;
stm = DB.stm;
stmm = DB.stm;
}
// ------------------------------------------------------------
// INSERT DATA Method
// ------------------------------------------------------------
//
//
public Boolean create(String id_peminjaman, String id_buku) {
//SQL Query Statement
String sql = "INSERT INTO detilpeminjaman(" +
"id_peminjaman," +
"id_buku ) VALUES('" + id_peminjaman + "','" + id_buku + "' )";
try {
//Eksekusi query
stm.execute(sql);
//Jika Berhasil, Return True.
return true;
//Jika Ada Error
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
// ------------------------------------------------------------
// Balikin stock
// ------------------------------------------------------------
//
public Boolean balikinStock(String id_peminjaman) {
Integer stock;
// SQL Query
String sqlSelect = "SELECT * FROM detilpeminjaman WHERE id_peminjaman='" + id_peminjaman + "'";
try {
// Eksekusi query
ResultSet result = stm.executeQuery(sqlSelect);
// Loop untuk mengambil semua data
while (result.next()) {
// Ambil data
String idBuku = result.getString(2);
stock = new backend.Buku().stockGet(idBuku);
Integer afterStock = stock + 1;
// SQL Query
String sql = "UPDATE buku SET stock='" + afterStock + "' WHERE id_buku='" + idBuku + "'";
try {
// Eksekusi SQL Query
System.out.println(idBuku);
System.out.println(afterStock);
stm.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return true;
// Exception
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
} | [
"[email protected]"
] | |
90ede36521f2457a63b5ae6c5bc1122a8221784c | 7370dd03032c7a06f776e61c9f2667c852d17917 | /src/main/java/com/carz/market/persistence/entity/ComprasProducto.java | 4c59213af0423256918bf11e7b529b957d333da2 | [] | no_license | cesar-rayo/carz-market | 7c3cf7589efc8e2fba50354792ca6e43661319e3 | ceb215283d3480d3d22cf1a520bff1e298f1747c | refs/heads/master | 2023-02-25T13:16:22.267677 | 2021-02-02T19:35:04 | 2021-02-02T19:35:04 | 320,905,308 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,103 | java | package com.carz.market.persistence.entity;
import javax.persistence.*;
@Entity
@Table(name = "compras_productos")
public class ComprasProducto {
@EmbeddedId
private ComprasProductoPK id;
private Integer cantidad;
private Double total;
private Boolean estado;
@ManyToOne
@JoinColumn(name = "id_compra", insertable = false, updatable = false)
private Compra compra;
@ManyToOne
@JoinColumn(name = "id_producto", insertable = false, updatable = false)
private Producto producto;
public ComprasProductoPK getId() {
return id;
}
public void setId(ComprasProductoPK id) {
this.id = id;
}
public Integer getCantidad() {
return cantidad;
}
public void setCantidad(Integer cantidad) {
this.cantidad = cantidad;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public Boolean getEstado() {
return estado;
}
public void setEstado(Boolean estado) {
this.estado = estado;
}
}
| [
"[email protected]"
] | |
d81421ba726d6b22cf5ad8f100ecf2f431389919 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-large-project/src/test/java/org/gradle/test/performancenull_453/Testnull_45289.java | 637c493707bab6638889ccc5af926ef0265044ea | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 308 | java | package org.gradle.test.performancenull_453;
import static org.junit.Assert.*;
public class Testnull_45289 {
private final Productionnull_45289 production = new Productionnull_45289("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"[email protected]"
] | |
40c39daee1fb3c488729d72e31c81e9ef84f37e6 | 99f0f5181948a494afea1cb72fbcf8ced8a0c425 | /src/main/java/cn/scau/lcj/dao/RequestRecordDao.java | ddaeb7e8a8af8af59b5e76fe2c46207e6c3a0409 | [] | no_license | bbbman/ovs | 7c1748671df066a6b62f3c70acd2a4c662d7ca06 | 353b3f0ecdb721b229b463e7df879f8bab5c0ac3 | refs/heads/master | 2021-01-16T21:08:39.560695 | 2016-06-22T08:29:58 | 2016-06-22T08:29:58 | 61,696,361 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 256 | java | package cn.scau.lcj.dao;
import java.util.List;
import cn.scau.lcj.entity.createVote.RequestRecord;
public interface RequestRecordDao extends GenericDao<RequestRecord,Integer> {
List<RequestRecord> selectRequestRecordBySqlString(String sqlString);
}
| [
"[email protected]"
] | |
f18d9f952a4d306f5ff6dadef4c605edfcd21e14 | 33d59626926ef31740b02a8ccc2d0dad09c29473 | /Course/20181108/springboard/src/main/java/examples/boot/springboard/controller/MainController.java | 6929704c944ccb74e45890ca046f8000a0ccb85e | [] | no_license | janghe11/FastCampus_Java | 04a71e4633a73e5b308934e3bef1e42046e9e2ef | c4544ab7e524a04898d9d7e0c86d29d9d069bdc7 | refs/heads/master | 2020-03-27T23:06:33.407617 | 2018-11-21T00:46:10 | 2018-11-21T00:46:10 | 147,291,448 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package examples.boot.springboard.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
public MainController(){
System.out.println("MainController()!");
}
// http://localhost:8080
@RequestMapping("/")
public String main(){
return "index"; // view name을 리턴, /WEB-INF/views/index.jsp로 forward
}
}
| [
"[email protected]"
] | |
1a6bff8a5ca364defb9462feee9ea96c388e0089 | 357da9150522d55ad7eb6bfeb3fe12622b827e6d | /src/es/studium/trivial/VistaPregunta1.java | 525fd7a862c1f80756e9858f6e2f30740623d214 | [] | no_license | juanlu-rr/Trivial | 46be364db41b5f73003223f3ce2c91659f101b56 | ad767b956b73580b10ec982d297d8490febd6e09 | refs/heads/master | 2020-04-23T07:24:44.952393 | 2019-02-27T19:24:21 | 2019-02-27T19:24:21 | 171,004,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,244 | java | package es.studium.trivial;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class VistaPregunta1 {
JFrame frame;
JTextArea pregunta1;
JRadioButton respuesta1;
JRadioButton respuesta2;
JRadioButton respuesta3;
JButton btnSiguiente;
JButton btnVolver;
JButton btnComprobar;
JLabel lblComprueba;
private final ButtonGroup buttonGroup = new ButtonGroup();
public VistaPregunta1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setBackground(new Color(0, 0, 205));
frame.setBounds(100, 100, 690, 606);
JLabel label = new JLabel("Juego de Preguntas");
label.setForeground(new Color(255, 255, 0));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Snap ITC", Font.BOLD, 26));
label.setBackground(new Color(102, 205, 170));
pregunta1 = new JTextArea("");
pregunta1.setEditable(false);
pregunta1.setLineWrap(true);
pregunta1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
pregunta1.setForeground(new Color(0, 0, 0));
pregunta1.setFont(new Font("Tahoma", Font.BOLD, 15));
pregunta1.setBackground(new Color(173, 216, 230));
respuesta1 = new JRadioButton("");
buttonGroup.add(respuesta1);
respuesta2 = new JRadioButton("");
buttonGroup.add(respuesta2);
respuesta3 = new JRadioButton("");
buttonGroup.add(respuesta3);
btnSiguiente = new JButton("Siguiente");
btnVolver = new JButton("Volver");
btnComprobar = new JButton("Comprobar Respuesta");
lblComprueba = new JLabel("");
lblComprueba.setBackground(new Color(0, 0, 0));
lblComprueba.setForeground(new Color(255, 255, 255));
lblComprueba.setBorder(new LineBorder(new Color(0, 255, 255), 3));
lblComprueba.setHorizontalAlignment(SwingConstants.LEFT);
lblComprueba.setFont(new Font("Snap ITC", Font.BOLD, 16));
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label, GroupLayout.DEFAULT_SIZE, 660, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(32)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(respuesta2, GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnVolver, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 390, Short.MAX_VALUE)
.addComponent(btnSiguiente, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE))
.addComponent(pregunta1, GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
.addComponent(respuesta3, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
.addComponent(respuesta1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE)
.addComponent(lblComprueba, GroupLayout.DEFAULT_SIZE, 606, Short.MAX_VALUE))
.addGap(34)))
.addGap(0))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap(258, Short.MAX_VALUE)
.addComponent(btnComprobar)
.addGap(255))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(9)
.addComponent(label)
.addGap(29)
.addComponent(pregunta1, GroupLayout.PREFERRED_SIZE, 78, GroupLayout.PREFERRED_SIZE)
.addGap(14)
.addComponent(respuesta1, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(respuesta2, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(respuesta3, GroupLayout.PREFERRED_SIZE, 56, GroupLayout.PREFERRED_SIZE)
.addGap(16)
.addComponent(btnComprobar, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(lblComprueba, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnSiguiente, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addComponent(btnVolver, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE))
.addGap(41))
);
frame.getContentPane().setLayout(groupLayout);
frame.setVisible(true);
}
}
| [
"[email protected]"
] | |
7d943d1f6b55110fb9ba677735c5b3cdd8e700a7 | 648d6ee13e873c76c2a922a9c23330f251d67fc8 | /BLM103/src/Lab02/Q2.java | 2972d5867b1ddf64ca4fac2594546ecc787be4a8 | [] | no_license | sultanzeybek/Java_BLM103 | 9cd91f5e7dcfd033380f4ba31cb4fe6be198c75e | ce99bc19fdbc6c20e7abe1a51724b08fb368d300 | refs/heads/master | 2020-04-23T16:25:57.955024 | 2019-05-05T10:51:24 | 2019-05-05T10:51:24 | 171,297,800 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 987 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Lab02;
import java.util.Scanner;
/**
*
* @author szeybek
*/
// compute the average of three numbers.
public class Q2 {
public static void main(String[] args) {
int a = 32;
int b = 29;
int c = 55;
double avarage = (a + b + c) / 3.0;
System.out.println("The avarage of three numbers is " + avarage);
Scanner my_scanner = new Scanner(System.in);
System.out.println("Enter first number:" );
a = my_scanner.nextInt();
System.out.println("Enter second number:" );
b = my_scanner.nextInt();
System.out.println("Enter third number:" );
c = my_scanner.nextInt();
System.out.println("The avarage of three numbers is " + (a+b+c)/3.0);
}
}
| [
"[email protected]"
] | |
a6186e378a9ca9b0af1504b294bb172eb7246596 | 431a4f9447a36343d52060c0e29db8a8df566c31 | /app/src/main/java/com/example/car_s/UserHelperClass.java | 8b517ee9c1da1cc06b054b6ae30e2241e20f8dd0 | [] | no_license | Graduation-Project-CS/Car_S | cc712b1c78b97e06e58875b4a9f5ac2640075161 | 62a0dd46fd6293e1c20300f4d41b04d06ca68d54 | refs/heads/master | 2023-03-31T20:39:00.916775 | 2021-04-11T20:29:42 | 2021-04-11T20:29:42 | 354,425,265 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,208 | java | package com.example.car_s;
public class UserHelperClass {
String id,full_name,age_get,phone,city,pass;
public UserHelperClass() {
}
public UserHelperClass(String id, String full_name, String age_get, String phone, String city, String pass){
this.id=id;
this.full_name=full_name;
this.age_get=age_get;
this.phone=phone;
this.city=city;
this.pass=pass;
}
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getAge_get() {
return age_get;
}
public void setAge_get(String age_get) {
this.age_get = age_get;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
| [
"[email protected]"
] | |
75aa3113ac1c5b2f9fad3cf8a97e8075a6cf7da8 | 56063c1c045a533edc3ad7f5ae2dd6f1783effa8 | /src/main/java/kr/or/kpc/dao/NoticeDao.java | 8e34776d58e66f0abbaa8125011891bea28e6f8e | [] | no_license | youngwoo2020/jsp_fundamental | 943693460e14169fca0a7879ba3ef07bc189c1ff | 72422c60d327b6c435ef84ed29f3232a0309c72e | refs/heads/master | 2023-05-26T01:31:53.524289 | 2021-06-16T05:13:02 | 2021-06-16T05:13:02 | 374,942,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,374 | java | package kr.or.kpc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import kr.or.kpc.dto.NoticeDto;
import kr.or.kpc.util.ConnLocator;
public class NoticeDao {
private static NoticeDao single;
private NoticeDao() {
}
public static NoticeDao getInstance() {
if (single == null) {
single = new NoticeDao();
}
return single;
}
public boolean insert(NoticeDto dto) {
boolean success = false;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO notice(n_num, n_writer,n_title,n_content, ");
sql.append("n_regdate) VALUES(?,?,?,?,NOW())");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
pstmt.setInt(index++, dto.getNum());
pstmt.setString(index++, dto.getWriter());
pstmt.setString(index++, dto.getTitle());
pstmt.setString(index++, dto.getContent());
pstmt.executeUpdate();
success = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt , null);
}
return success;
}
public boolean update(NoticeDto dto) {
boolean success = false;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("UPDATE notice ");
sql.append("SET n_writer = ?, n_title=?, ");
sql.append("n_content = ? ");
sql.append("WHERE n_num = ? ");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
pstmt.setString(index++, dto.getWriter());
pstmt.setString(index++, dto.getTitle());
pstmt.setString(index++, dto.getContent());
pstmt.setInt(index++, dto.getNum());
pstmt.executeUpdate();
success = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt , null);
}
return success;
}
public boolean delete(int num) {
boolean success = false;
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("DELETE FROM notice ");
sql.append("WHERE n_num = ?");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
pstmt.setInt(index++, num);
pstmt.executeUpdate();
success = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt , null);
}
return success;
}
public ArrayList<NoticeDto> select(int start, int len) {
ArrayList<NoticeDto> list = new ArrayList<NoticeDto>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("SELECT n_num, n_writer,n_title, n_content, date_format(n_regdate,'%Y/%m/%d') ");
sql.append("FROM notice ");
sql.append("ORDER BY n_regdate DESC ");
sql.append("LIMIT ?, ? ");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
pstmt.setInt(index++, start);
pstmt.setInt(index++, len);
rs = pstmt.executeQuery();
while (rs.next()) {
index = 1;
int num = rs.getInt(index++);
String writer = rs.getString(index++);
String title = rs.getString(index++);
String content = rs.getString(index++);
String regdate = rs.getString(index++);
list.add(new NoticeDto(num, writer, title, content, regdate));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt, rs);
}
return list;
}
public int getRows() {
int resultCount = 0;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(n_num) ");
sql.append("FROM notice ");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
rs = pstmt.executeQuery();
if (rs.next()) {
index = 1;
resultCount = rs.getInt(index++);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt, rs);
}
return resultCount;
}
private void close(Connection con,
PreparedStatement pstmt,
ResultSet rs) {
try {
if (con != null)
con.close();
if (pstmt != null)
pstmt.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getMaxNum(){
int resultCount = 0;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("SELECT ifnull(max(n_num)+1, 1) ");
sql.append("FROM notice ");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
rs = pstmt.executeQuery();
if (rs.next()) {
index = 1;
resultCount = rs.getInt(index++);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt, rs);
}
return resultCount;
}
public NoticeDto select(int num) {
NoticeDto dto = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ConnLocator.getConnect();
StringBuilder sql = new StringBuilder();
sql.append("SELECT n_num, n_writer, n_title, n_content, date_format(n_regdate, '%Y/%m/%d %h:%i') ");
sql.append("FROM notice ");
sql.append("WHERE n_num =? ");
pstmt = con.prepareStatement(sql.toString());
int index = 1;
pstmt.setInt(index++, num);
;
rs = pstmt.executeQuery();
if (rs.next()) {
index = 1;
num = rs.getInt(index++);
String writer = rs.getString(index++);
String title = rs.getString(index++);
String content = rs.getString(index++);
String regdate = rs.getString(index++);
dto = new NoticeDto(num, writer, title, content, regdate);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(con, pstmt, rs);
}
return dto;
}
} | [
"[email protected]"
] | |
5909e91c10f2e631028d1eedddb17b3c802dac9f | d69695dc3d3afa264b7a58ae3ab14312b1a699d1 | /src/GlossaryCreator.java | 75a1369a637ba938d844ab45ddf0e09147236f99 | [] | no_license | simonmanning/cse2221-project-10-glossary | f692044372f8ffba5b7d481f405cba6276d5dac1 | 291e069ccbc22626a551dcbe46d77b88ee17b233 | refs/heads/master | 2020-03-10T10:57:39.049783 | 2018-04-13T04:05:06 | 2018-04-13T04:05:06 | 129,344,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,188 | java | import components.map.Map;
import components.map.Map1L;
import components.sequence.Sequence;
import components.sequence.Sequence1L;
import components.set.Set;
import components.set.Set1L;
import components.simplereader.SimpleReader;
import components.simplereader.SimpleReader1L;
import components.simplewriter.SimpleWriter;
import components.simplewriter.SimpleWriter1L;
/**
* Creates a html glossary from a text file input.
*
* @author Simon Manning
*
*/
public final class GlossaryCreator {
/**
* Private constructor so this utility class cannot be instantiated.
*/
private GlossaryCreator() {
}
/**
* Generates the header of the output HTML file opening html, head, title,
* and body.
*
* @param out
* the output stream.
* @param terms
* the sequence of terms in alphabetical order.
* @param mapTerms
* the map of the terms with their associated definitions.
* @param arrayTerms
* the list of terms in array format.
* @param outputFile
* the output file location selected by the client.
* @ensures homePage includes Glossary title and list of words stored in
* terms as links.
*/
private static void createIndex(SimpleWriter out, Sequence<String> terms,
Map<String, String> mapTerms, String[] arrayTerms,
String outputFile) {
//user input output file name and index location.
String index = outputFile + "/index.html";
SimpleWriter homePage = new SimpleWriter1L(index);
//create header.
homePage.println("<html>");
homePage.println("<head>");
homePage.println("<title>" + "Glossary" + "</title>");
homePage.println("</head>");
homePage.println("<body>");
homePage.println(
"<p style=\"font-size:20pt;\"> <b> <u> Simon's Glossary </u> </b></p>");
homePage.println();
homePage.println("<p style=\"font-size:16pt;\"><b>Index</b></p>");
homePage.println("<ul>");
//creates each term's page and creates a link to the recent created page.
//loop while there are more terms to make pages for.
while (terms.length() > 0) {
String term = terms.remove(0);
createPages(term, out, mapTerms, arrayTerms, outputFile);
homePage.println(
"<li><a href=\"" + term + ".html\">" + term + "</a></li>");
}
//create footer.
homePage.println("</ul>");
homePage.println("</body>");
homePage.println("</html>");
homePage.close();
}
/**
* Creates a page for each of the terms from the input file.
*
* @param term
* the term the page is created around
* @param out
* the output stream
* @param mapTerms
* the map of the terms and their definitions
* @param arrayTerms
* all of the terms that are in the input file
* @param outputFile
* the output file location
* @ensures termPage contains the term as a header & the definition of the
* term displayed, followed by a Return to Index Page option.
*/
private static void createPages(String term, SimpleWriter out,
Map<String, String> mapTerms, String[] arrayTerms,
String outputFile) {
String page = outputFile + "/" + term + ".html";
SimpleWriter termPage = new SimpleWriter1L(page);
termPage.println("<html>");
termPage.println("<head>");
termPage.println("<title>" + term + "</title>");
termPage.println("</head>");
termPage.println("<body>");
termPage.println("<p style=\"color:red;\"><b><i>" + term.toUpperCase()
+ "</b></i></p>");
termPage.println();
String definition = mapTerms.value(term);
Set<Character> separatorSet = new Set1L<>();
String separators = " ,";
//creates the separator set
generateElements(separators, separatorSet);
String inputToPage = "";
int x = 0;
while (x < definition.length()) {
String space = nextWordOrSeparator(definition, x, separatorSet);
if (separatorSet.contains(space.charAt(0))) {
inputToPage = inputToPage + space;
} else {
int i = 0;
int counter = 0;
while (i < arrayTerms.length) {
if (space.equals(arrayTerms[i])) {
inputToPage = inputToPage + "<a href=\"" + arrayTerms[i]
+ ".html\">" + space + "</a>";
counter++;
}
i++;
}
if (counter == 0) {
inputToPage = inputToPage + space;
}
}
x += space.length();
}
termPage.println(
"<p style=\"text-align:left;\">" + inputToPage + ".</p>");
termPage.println();
termPage.println("Return to <a href=\"index.html\">index</a>.");
termPage.println("</body>");
termPage.println("</html>");
termPage.close();
}
/**
* Puts terms and their definitions into a map.
*
* @param in
* the input stream
* @param mapTerms
* the map that will contain the terms with their associated
* definitions
* @param terms
* a set of only the terms
* @ensures mapTerms = terms and definitions of the input file in
*/
private static void mapReader(SimpleReader in, Map<String, String> mapTerms,
Set<String> terms) {
//loops until the end of the input file.
while (!in.atEOS()) {
String newLine = in.nextLine();
String definition = "";
String term = "";
boolean lineIsEmpty = true;
if (newLine.equals("")) {
lineIsEmpty = false;
} else {
term = newLine;
}
//loops until there is an empty line or the end of the file.
while (lineIsEmpty && !in.atEOS()) {
newLine = in.nextLine();
if (!newLine.equals("")) {
//put definition and an empty line after it.
definition = definition + " " + newLine;
} else {
lineIsEmpty = false;
}
}
//paired terms and definitions are put in mapTerms.
mapTerms.add(term, definition);
terms.add(term);
}
}
/**
* Takes the set of terms and puts them in alphabetical order.
*
* @param terms
* the given set of terms
* @replaces terms
* @ensures terms = original terms set except the first word alphabetically.
* @return the new set of terms in alphabetical order.
*/
private static String alphabetize(Set<String> terms) {
Set<String> orderTerms = new Set1L<>();
String result = "";
//while there are still terms to loop through
while (terms.size() > 0 && result.equals("")) {
int count = 0;
//take out a word from terms to compare.
String temp = terms.removeAny();
//compare the word to each word in terms, ignoring case.
for (String word : terms) {
if (word.compareToIgnoreCase(temp) < 0) {
count++;
}
}
//if word does not need to be placed differently.
if (count == 0) {
result = temp;
//add the temp the ordered terms set.
} else {
orderTerms.add(temp);
}
}
terms.add(orderTerms);
return result;
}
/**
* Generates the set of characters in the given {@code String} into the
* given {@code Set}.
*
* @param str
* the given {@code String}
* @param strSet
* the {@code Set} to be replaced
* @replaces strSet
* @ensures strSet = entries(str)
*/
private static void generateElements(String str, Set<Character> strSet) {
assert str != null : "Violation of: str is not null";
assert strSet != null : "Violation of: strSet is not null";
int count = 0;
char setPiece = ' ';
strSet.clear();
while (count < str.length()) {
if (!strSet.contains(str.charAt(count))) {
setPiece = str.charAt(count);
strSet.add(setPiece);
}
count++;
}
}
/**
* Returns the first "word" (maximal length string of characters not in
* {@code separators}) or "separator string" (maximal length string of
* characters in {@code separators}) in the given {@code text} starting at
* the given {@code position}.
*
* @param text
* the {@code String} from which to get the word or separator
* string
* @param position
* the starting index
* @param separators
* the {@code Set} of separator characters
* @return the first word or separator string found in {@code text} starting
* at index {@code position}
* @requires 0 <= position < |text|
* @ensures <pre>
* nextWordOrSeparator =
* text[position, position + |nextWordOrSeparator|) and
* if entries(text[position, position + 1)) intersection separators = {}
* then
* entries(nextWordOrSeparator) intersection separators = {} and
* (position + |nextWordOrSeparator| = |text| or
* entries(text[position, position + |nextWordOrSeparator| + 1))
* intersection separators /= {})
* else
* entries(nextWordOrSeparator) is subset of separators and
* (position + |nextWordOrSeparator| = |text| or
* entries(text[position, position + |nextWordOrSeparator| + 1))
* is not subset of separators)
* </pre>
*/
private static String nextWordOrSeparator(String text, int position,
Set<Character> separators) {
assert text != null : "Violation of: text is not null";
assert separators != null : "Violation of: separators is not null";
assert 0 <= position : "Violation of: 0 <= position";
assert position < text.length() : "Violation of: position < |text|";
int count = 0;
char returnedPiece = ' ';
String returned = "";
if (separators.contains(text.charAt(position))) {
while (count < text.substring(position, text.length()).length()) {
returnedPiece = text.charAt(position + count);
if (separators.contains(text.charAt(position + count))) {
returned = returned + returnedPiece;
count++;
} else {
count = text.substring(position, text.length()).length();
}
}
} else {
while (count < text.substring(position, text.length()).length()) {
returnedPiece = text.charAt(position + count);
if (!separators.contains(text.charAt(position + count))) {
returned = returned + returnedPiece;
count++;
} else {
count = text.substring(position, text.length()).length();
}
}
}
return returned;
}
/**
* Main method.
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
//ask for input file and folder to save to.
out.print("Input file to use: ");
String fileName = in.nextLine();
SimpleReader inFile = new SimpleReader1L(fileName);
out.print("Folder to save output to: ");
String outputFile = in.nextLine();
//create map and set to store the terms and definition(s) into.
Map<String, String> mapTerms = new Map1L<>();
Set<String> terms = new Set1L<>();
mapReader(inFile, mapTerms, terms);
//create sequence and array to use when storing alphabetical terms.
Sequence<String> listOfTerms = new Sequence1L<>();
String[] arrayTerms = new String[terms.size()];
//order terms in alphabetical order for index page.
//loop while there are still more terms.
int x = 0;
while (0 < terms.size()) {
String nextTerm = alphabetize(terms);
listOfTerms.add(listOfTerms.length(), nextTerm);
arrayTerms[x] = nextTerm;
x++;
}
createIndex(out, listOfTerms, mapTerms, arrayTerms, outputFile);
in.close();
out.close();
}
}
| [
"[email protected]"
] | |
8e44135f612108c60d3b0241a9ee3fedd4248b82 | 0e06e096a9f95ab094b8078ea2cd310759af008b | /classes77-dex2jar/com/google/android/gms/internal/ads/zzamm.java | 8e9183ad043ebd0b5d839f047ff0e1f144722c81 | [] | no_license | Manifold0/adcom_decompile | 4bc2907a057c73703cf141dc0749ed4c014ebe55 | fce3d59b59480abe91f90ba05b0df4eaadd849f7 | refs/heads/master | 2020-05-21T02:01:59.787840 | 2019-05-10T00:36:27 | 2019-05-10T00:36:27 | 185,856,424 | 1 | 2 | null | 2019-05-10T00:36:28 | 2019-05-09T19:04:28 | Java | UTF-8 | Java | false | false | 707 | java | //
// Decompiled by Procyon v0.5.34
//
package com.google.android.gms.internal.ads;
import com.google.ads.mediation.admob.AdMobAdapter;
import android.os.Bundle;
@zzadh
public final class zzamm
{
public static boolean zzo(final zzjj zzjj) {
Bundle zzaqg;
if (zzjj.zzaqg != null) {
zzaqg = zzjj.zzaqg;
}
else {
zzaqg = new Bundle();
}
Bundle bundle;
if (zzaqg.getBundle(AdMobAdapter.class.getName()) != null) {
bundle = zzaqg.getBundle(AdMobAdapter.class.getName());
}
else {
bundle = new Bundle();
}
return bundle.getBoolean("render_test_label", false);
}
}
| [
"[email protected]"
] | |
e0cd43f6fadd9ee0f37efe333cc0fb7bf9213c90 | 8a19f172fcf3424feff9b4482fcde4921ae4a63e | /app/src/main/java/com/hacketon/prototipo/adapterMotos/AdapterMotos.java | e561b7408b9f8ce02a8a76828c315e32292e8c69 | [] | no_license | maximopiu18/PrototopoHacketon | b298ac5e518038687139371aa7e685ef1035d1a9 | b1191afd52059dc74431c5c56860fa6f6d2c4dcb | refs/heads/master | 2020-07-10T08:38:17.765165 | 2019-08-25T16:53:43 | 2019-08-25T16:53:43 | 204,220,291 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,088 | java | package com.hacketon.prototipo.adapterMotos;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.hacketon.prototipo.Activity_Descripcion;
import com.hacketon.prototipo.Constans.Constantes;
import com.hacketon.prototipo.R;
public class AdapterMotos extends RecyclerView.Adapter<HolderMotos> {
public static int posicionHeroe;
private Context context;
public AdapterMotos(Context context) {
this.context = context;
}
@Override
public HolderMotos onCreateViewHolder(ViewGroup parent, final int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_motos, parent, false);
return new HolderMotos(view);
}
@Override
public void onBindViewHolder(final HolderMotos holder, final int position) {
holder.tvName.setText(Constantes.ListaMarca.get(position));
holder.tvModel.setText(Constantes.ListaModelo.get(position));
holder.tvDate.setText(Constantes.ListaFecha.get(position));
if(position==0) {
holder.ivModelo.setImageResource(R.drawable.img_moto);
}
if(position==1) {
holder.ivModelo.setImageResource(R.drawable.img_moto2);
}
if(position==2) {
holder.ivModelo.setImageResource(R.drawable.img_moto3);
}
holder.itemLinear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("position", "position: " + position);
Constantes.positionMoto = position;
Intent intent = new Intent(context, Activity_Descripcion.class);
context.startActivity(intent);
((Activity) context).finish();
}
});
}
@Override
public int getItemCount() {
return Constantes.ListaMarca.size();
}
}
| [
"[email protected]"
] | |
44ad3be95c21c237cfec20dc73426fec49bdbca0 | 57adbd976c470e485916ace1cb6a9c17cb6b3064 | /src/main/java/com/darren/activemq/ActivemqContants.java | 77855419d9ff3cfd56b88ba4d24324aed59dc823 | [] | no_license | zhangpanfeng/darren-activemq | 41d50aa14b1f1a44590191da4f8a63d49e1ee7df | 9ad307eed2fe1e03f77b7cabc4947208dab06bde | refs/heads/master | 2021-01-21T18:06:34.988758 | 2017-05-23T06:02:46 | 2017-05-23T06:02:46 | 92,015,505 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 121 | java | package com.darren.activemq;
public class ActivemqContants {
public static final String FINISH_FLAG = "FINISHED";
}
| [
"[email protected]"
] | |
ba4686bbee708d6d152c6a0b812a82d8821cbd61 | 91d0eea5394a142df67309d3c09cc80b20a2e420 | /src/com/collomosse/blinkviewer/VideoPump.java | 5a1f37ce786497c681c46d60cfd48ff9147ac509 | [] | no_license | twogun/blinkviewer | cc70eb39602167bebb53a57f153c599c6d1357e3 | 9c54d4166029b9d87c87a16a6ec89b6c8b74240a | refs/heads/master | 2016-08-09T00:27:09.745785 | 2014-07-20T20:15:30 | 2014-07-20T20:15:30 | 49,092,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,301 | java | package com.collomosse.blinkviewer;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;
public class VideoPump extends Thread {
MainActivity _cxt;
URL _cameraURI;
DataInputStream _cameraDataStream;
Hashtable<String,String> _headers;
PlayAudio _audioengine;
byte _img[];
byte _pcm[];
VideoPumpListener _callback;
public VideoPump(MainActivity cxt, URL url, VideoPumpListener callback) {
_callback=callback;
_cxt=cxt;
_cameraURI=url;
_audioengine=new PlayAudio();
this.start();
}
public void run() {
try {
runStream();
}
catch (final IOException e) {
Log.d("BlinkViewer::Connect" , "Unable to connect: "+e);
_cxt.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(_cxt, "HTTP Connection failed\n\n"+e.toString(), Toast.LENGTH_LONG).show();
}
});
}
}
public void runStream() throws IOException {
// Connect
URLConnection conn = _cameraURI.openConnection();
conn.setRequestProperty("User-Agent", "BlinkViewerApp");
conn.setRequestProperty("Host", _cameraURI.getHost());
_cameraDataStream = new DataInputStream(new BufferedInputStream(conn.getInputStream()));
// Parse HTML headers
_headers = StreamSplit.readHeaders(conn);
for (Enumeration enm = _headers.keys();enm.hasMoreElements();)
{
String hkey = (String)enm.nextElement();
Log.d("BlinkViewer::StreamHeaderDump" ,hkey + " = " + _headers.get(hkey));
}
StreamSplit ssplit = new StreamSplit(_cameraDataStream);
String ctype = (String) _headers.get("content-type");
boolean success=true;
if (ctype == null) {
Log.e("BlinkViewer::Connect","No main content type");
success=false;
} else if (ctype.indexOf("text") != -1) {
String response;
//noinspection deprecation
while ((response = _cameraDataStream.readLine()) != null) {
Log.e("BlinkViewer::Connect","Unexpected HTML response: "+response);
}
success=false;
}
if (success) {
Log.i("BlinkViewer::Connect","Success content type = "+ctype);
// Get boundary marker text
int bidx = ctype.indexOf("boundary=");
String boundary = StreamSplit.BOUNDARY_MARKER_PREFIX;
if (bidx != -1) {
boundary = ctype.substring(bidx + 9);
ctype = ctype.substring(0, bidx);
if (boundary.startsWith("\"") && boundary.endsWith("\""))
{
boundary = boundary.substring(1, boundary.length()-1);
}
if (!boundary.startsWith(StreamSplit.BOUNDARY_MARKER_PREFIX)) {
boundary = StreamSplit.BOUNDARY_MARKER_PREFIX + boundary;
}
}
Log.i("BlinkViewer::Connect","Boundary = ["+boundary+"]");
// Read up to first boundary marker
if (ctype.startsWith("multipart/x-mixed-replace")) {
ssplit.skipToBoundary(boundary);
}
while (true) {
while (!ssplit.isAtStreamEnd()) {
// read headers
_headers = ssplit.readHeaders();
for (Enumeration enm = _headers.keys();enm.hasMoreElements();)
{
String hkey = (String)enm.nextElement();
Log.d("BlinkViewer::StreamHeaderDump-Inner" ,hkey + " = " + _headers.get(hkey));
}
if (ssplit.isAtStreamEnd()) {
break;
}
ctype = (String)_headers.get("content-type");
if (ctype == null) {
Log.e("BlinkView::Connect","No part content type");
}
Log.i("BlinkViewer::Connect","Inner-content type = "+ctype);
// ssplit.skipToBoundary(boundary);
if (ctype.startsWith("multipart/x-mixed-replace")) {
// Skip
// bidx = ctype.indexOf("boundary=");
// boundary = ctype.substring(bidx + 9);
//ssplit.skipToBoundary(boundary);
continue;
}
else {
int clen = Integer.parseInt((String)_headers.get("content-length"));
byte[] data = ssplit.readToBoundary(boundary,clen); // JPC optimize
Log.i("BlinkViewer::Connect","Read image of "+data.length+" bytes (expected "+clen);
int audioType;
int headerType;
int iLength;
int audio_start_offset;
int m_ResetFlag = data[0] & 1;
audioType = data[0] & 6;
headerType = data[0] & 8;
iLength = byteArrayToInt_MSB(data, 1);
int m_imgCurrentIndex = byteArrayToInt_MSB(data, 5);
int m_resolutionJpeg = data[9];
int m_ResetAudioBufferCount = data[10];
int temperature = byteArrayToInt_MSB(data, 11);
audio_start_offset = 0;
if(headerType == 0) {
audio_start_offset = 15;
}
else if(headerType == 8) {
audio_start_offset = 56;
}
else {
continue; //abort
}
byte adpcm[];
adpcm = new byte[iLength];
System.arraycopy(data, audio_start_offset, adpcm, 0, iLength);
// decompress audio
if(audioType == 2)
_pcm = adpcm;
else if (audioType == 0)
_pcm = ADPCMDecoder.decode(adpcm);
else
_pcm = null;
// extract jpeg data
int ImageDataLen = data.length - (audio_start_offset + iLength);
_img = new byte[ImageDataLen];
System.arraycopy(data, audio_start_offset + iLength, _img, 0, _img.length);
notifyNewFrame(m_imgCurrentIndex,temperature);
}
} // end proc blocks
try {
Thread.sleep(20);
} catch (InterruptedException ignored) {}
} // end inf while
} // end if success
}
public static byte[] intToByteArray_MSB(int value)
{
byte b[] = new byte[4];
for(int i = 0; i < 4; i++)
{
int offset = (b.length - 1 - i) * 8;
b[i] = (byte)(value >>> offset & 0xff);
}
return b;
}
public static int byteArrayToInt_MSB(byte b[], int offset)
{
int value = 0;
for(int i = 0; i < 4; i++)
{
int shift = (3 - i) * 8;
value += (b[i + offset] & 0xff) << shift;
}
return value;
}
public void notifyNewFrame(int frameIndex, int roomTemp) {
Log.i("BlinkViewer::Connect","Obtained camera frame "+frameIndex);
Log.i("BlinkViewer::Connect","JPEG: "+_img.length +" PCM: "+_pcm.length);
Bitmap b=BitmapFactory.decodeByteArray (_img, 0, _img.length);
_audioengine.writeAudio(_pcm);
_callback.onFrameReceived(b, frameIndex, roomTemp);
}
}
| [
"[email protected]"
] | |
fae673e573d7c474fef098e755b724f2efaf7605 | 198404f9bf695ba062605cec85a850238d827fb8 | /com.ptoceti.osgi.rest/src/main/java/com/ptoceti/osgi/rest/impl/TimeSeriesServiceListener.java | 21571c7e7df5fb989214fa883226e3fd2d15842d | [
"Apache-2.0"
] | permissive | lathil/Ptoceti | ec2d761506fe3328f18652c32bc3d9b2519f60e9 | e403d7dc3095d634bbe1c43155ff8a7ab364a8cb | refs/heads/master | 2023-06-22T20:16:49.550209 | 2023-03-05T18:34:11 | 2023-03-05T18:34:11 | 17,915,613 | 4 | 1 | Apache-2.0 | 2023-06-14T22:21:44 | 2014-03-19T18:28:55 | Java | UTF-8 | Java | false | false | 1,577 | java | package com.ptoceti.osgi.rest.impl;
import com.ptoceti.osgi.timeseries.TimeSeriesService;
import org.osgi.framework.*;
import java.util.HashMap;
import java.util.Map;
public class TimeSeriesServiceListener implements ServiceListener {
protected BundleContext bc;
protected ServiceReference sRef;
public TimeSeriesServiceListener(BundleContext bundleContext) throws BundleException {
bc = bundleContext;
String filter = "(objectclass=" + TimeSeriesService.class.getName() + ")";
try {
bc.addServiceListener(this, filter);
ServiceReference srLog = bc.getServiceReference(TimeSeriesService.class.getName());
if (srLog != null) {
this.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, srLog));
}
} catch (InvalidSyntaxException e) {
throw new BundleException("Error in filter string while registering TimeSeriesServiceListener." + e.toString());
}
}
/**
* Unique method of the ServiceListener interface.
*/
public void serviceChanged(ServiceEvent event) {
ServiceReference sr = event.getServiceReference();
switch (event.getType()) {
case ServiceEvent.REGISTERED: {
sRef = sr;
Activator.getLogger().info("Detecting TimeSeries");
}
break;
case ServiceEvent.UNREGISTERING: {
sRef = null;
}
break;
}
}
public ServiceReference get() {
return sRef;
}
}
| [
"[email protected]"
] | |
4df804652e23fcd834cca5a2c6c1ff66b4dfe56f | 45b1cf3cecf5ad79fb73ada8241ad12f7d94c4b9 | /src/main/java/com/share/memories/application/users/UsersService.java | 7e4d4c1f6e64bac700af970898ec90841eb28f18 | [] | no_license | psosnowka/ShareMemories | ec294f4fca21dc46730aa53fd4a70512e38f6efa | 8f3c5513b2ca33370b9b6947c1aa17c365e45cba | refs/heads/master | 2023-05-24T05:42:11.699877 | 2019-06-11T19:17:39 | 2019-06-11T19:17:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,167 | java | package com.share.memories.application.users;
import com.share.memories.application.base.BaseEntity;
import com.share.memories.application.posts.PostsFacade;
import com.share.memories.application.posts.dto.PostResponse;
import com.share.memories.application.users.dto.AddUserRequest;
import com.share.memories.application.users.dto.AddUserResponse;
import com.share.memories.application.users.dto.DeleteFollowerRequest;
import com.share.memories.application.users.dto.UserDetailsResponse;
import com.share.memories.application.util.SecurityUtil;
import com.share.memories.application.util.dto.TokenResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
class UsersService {
private final UserApplicationService userApplicationService;
private final SecurityUtil securityUtil;
private final PostsFacade postsFacade;
AddUserResponse addUserAndGetSessionToken(AddUserRequest addUserRequest) {
AppUser appUser = userApplicationService.addUser(addUserRequest);
TokenResponse sessionToken = securityUtil.createSessionToken(appUser.getEmail());
return AddUserResponse.of(appUser.getContext(), sessionToken);
}
Mono<AppUser> addFolower(UserContext userContext, String userUuid) {
return Mono.fromCallable(() -> userApplicationService.addFollower(userContext, userUuid));
}
AppUser getUser(UserContext userContext) {
return userApplicationService.getUserByEmail(userContext.getEmail());
}
UserDetailsResponse getUserByUuid(UserContext userContext, String uuid) {
final AppUser loggedUser = userApplicationService.getUserByUuid(userContext.getUuid());
final UserContext userDetails = userApplicationService.getUserByUuid(uuid).getContext();
if (loggedUser.isFollower(uuid)) {
return UserDetailsResponse.withIsFollowingTrue(userDetails);
} else {
return UserDetailsResponse.withIsFollowingFalse(userDetails);
}
}
List<PostResponse> getAllPostsCreatedByUser(String uuid) {
AppUser userByUuid = userApplicationService.getUserByUuid(uuid);
return postsFacade.getAllPostsForUsers(Collections.singletonList(userByUuid.getUuid()));
}
List<PostResponse> getAllPostsForUser(UserContext userContext) {
List<String> userUuids = userApplicationService.getUserByUuid(userContext.getUuid())
.getFollowers()
.stream()
.map(BaseEntity::getUuid)
.collect(Collectors.toList());
userUuids.add(userContext.getUuid());
return postsFacade.getAllPostsForUsers(userUuids);
}
public AppUser deleteFollower(UserContext userContext, DeleteFollowerRequest request) {
return userApplicationService.deleterFollower(userContext, request.getUserUuid());
}
}
| [
"[email protected]"
] | |
78173202f2315d05f164b6007a8f5c21abc728b2 | 0e3f01ce3f1046b7995dc338495f3c4097bc7176 | /src/test/java/com/accenture/ecommerce/store/domain/OrderItemTest.java | 68104c4d26dc2e94e8c97350be42bb5c39bde8b5 | [
"Apache-2.0"
] | permissive | pdeoliveira/jhi-aj-store | b91457d89b03bc696ecf0faf4434c4a2059b4a04 | e4c07bd87b400e26cc0ce510a9acca6aa86e48c7 | refs/heads/master | 2022-12-31T03:03:44.641451 | 2020-10-20T11:39:56 | 2020-10-20T11:39:56 | 296,624,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 747 | java | package org.jhipster.ecommerce.store.domain;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import org.jhipster.ecommerce.store.web.rest.TestUtil;
public class OrderItemTest {
@Test
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(OrderItem.class);
OrderItem orderItem1 = new OrderItem();
orderItem1.setId(1L);
OrderItem orderItem2 = new OrderItem();
orderItem2.setId(orderItem1.getId());
assertThat(orderItem1).isEqualTo(orderItem2);
orderItem2.setId(2L);
assertThat(orderItem1).isNotEqualTo(orderItem2);
orderItem1.setId(null);
assertThat(orderItem1).isNotEqualTo(orderItem2);
}
}
| [
"[email protected]"
] | |
82e74af6f440e9f0fe9982abaef87b6467cd6a13 | af6251ee729995455081c4f4e48668c56007e1ac | /domain/src/main/java/mmp/gps/domain/statistics/MileageOilCountRequest.java | ece6e6f018f57a7b79a140c202a6e65f1f04c8c0 | [] | no_license | LXKing/monitor | b7522d5b95d2cca7e37a8bfc66dc7ba389e926ef | 7d1eca454ce9a93fc47c68f311eca4dcd6f82603 | refs/heads/master | 2020-12-01T08:08:53.265259 | 2018-12-24T12:43:32 | 2018-12-24T12:43:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package mmp.gps.domain.statistics;
import java.util.Date;
import java.util.List;
public class MileageOilCountRequest {
private List<String> numbers;
private Date start;
private Date end;
public List<String> getNumbers() {
return numbers;
}
public void setNumbers(List<String> numbers) {
this.numbers = numbers;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
}
| [
"[email protected]"
] | |
9a98a56efee4d5d51fc94c60ef890afe00279d20 | 21eb3fab84d4cbd6a2608edd0386e08d53721e9d | /src/test/java/com/google/devtools/build/android/desugar/nest/ClassFileFormatTest.java | 07701c6a5c5270c1220b2bca4ad66dcf133b666b | [
"Apache-2.0"
] | permissive | marcohu/bazel | 77267b22fc2f6e656ead2dbc1aa544bbbab1c9c4 | 9d9e2169c3bbc7b78be061c21da2cda50aefe1f3 | refs/heads/master | 2020-07-10T01:01:24.176408 | 2020-02-03T09:11:20 | 2020-02-03T09:12:16 | 203,660,611 | 0 | 0 | Apache-2.0 | 2019-08-23T21:55:12 | 2019-08-21T20:37:05 | Java | UTF-8 | Java | false | false | 4,660 | java | /*
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.build.android.desugar.nest;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Splitter;
import com.google.devtools.build.android.desugar.testing.junit.AsmNode;
import com.google.devtools.build.android.desugar.testing.junit.DesugarRule;
import com.google.devtools.build.android.desugar.testing.junit.DesugarRunner;
import com.google.devtools.build.android.desugar.testing.junit.JdkSuppress;
import com.google.devtools.build.android.desugar.testing.junit.JdkVersion;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.objectweb.asm.tree.ClassNode;
/**
* Tests for accessing a series of private fields, constructors and methods from another class
* within a nest.
*/
@RunWith(DesugarRunner.class)
@JdkSuppress(minJdkVersion = JdkVersion.V11)
public final class ClassFileFormatTest {
private static final MethodHandles.Lookup lookup = MethodHandles.lookup();
@Rule
@SuppressWarnings("SplitterToStream") // Pending bazel guava update.
public final DesugarRule desugarRule =
DesugarRule.builder(this, lookup)
.addSourceInputs(getInputSourceFilesFromJvmOption("input_srcs"))
.addJavacOptions("-source 11", "-target 11")
.setWorkingJavaPackage(
"com.google.devtools.build.android.desugar.nest.testsrc.simpleunit.classfileformat")
.addCommandOptions("desugar_nest_based_private_access", "true")
.build();
private static Path[] getInputSourceFilesFromJvmOption(String jvmOptionKey) {
return Splitter.on(" ").trimResults().splitToList(System.getProperty(jvmOptionKey)).stream()
.map(Paths::get)
.toArray(Path[]::new);
}
@Test
public void classFileMajorVersions(
@AsmNode(className = "NestOuterInterfaceA", round = 0) ClassNode beforeDesugarClassNode,
@AsmNode(className = "NestOuterInterfaceA", round = 1) ClassNode afterDesugarClassNode) {
assertThat(beforeDesugarClassNode.version).isEqualTo(JdkVersion.V11);
assertThat(afterDesugarClassNode.version).isEqualTo(JdkVersion.V1_7);
}
@Test
public void nestMembersAttribute_strippedOutAfterDesugaring(
@AsmNode(className = "NestOuterInterfaceA", round = 0) ClassNode before,
@AsmNode(className = "NestOuterInterfaceA", round = 1) ClassNode after) {
assertThat(before.nestMembers).isNotEmpty();
assertThat(after.nestMembers).isNull();
}
@Test
public void nestHostAttribute_strippedOutAfterDesugaringForNestedClass(
@AsmNode(className = "NestOuterInterfaceA$NestedClassB", round = 0) ClassNode before,
@AsmNode(className = "NestOuterInterfaceA$NestedClassB", round = 1) ClassNode after) {
assertThat(before.nestHostClass).isNotEmpty();
assertThat(after.nestHostClass).isNull();
}
@Test
public void nestHostAttribute_strippedOutAfterDesugaringForNestedInterface(
@AsmNode(className = "NestOuterInterfaceA$NestedInterfaceC", round = 0) ClassNode before,
@AsmNode(className = "NestOuterInterfaceA$NestedInterfaceC", round = 1) ClassNode after) {
assertThat(before.nestHostClass).isNotEmpty();
assertThat(after.nestHostClass).isNull();
}
@Test
public void nestHostAttribute_strippedOutAfterDesugaringForNestedAnnotation(
@AsmNode(className = "NestOuterInterfaceA$NestedAnnotationD", round = 0) ClassNode before,
@AsmNode(className = "NestOuterInterfaceA$NestedAnnotationD", round = 1) ClassNode after) {
assertThat(before.nestHostClass).isNotEmpty();
assertThat(after.nestHostClass).isNull();
}
@Test
public void nestHostAttribute_strippedOutAfterDesugaringForNestedEnum(
@AsmNode(className = "NestOuterInterfaceA$NestedEnumE", round = 0) ClassNode before,
@AsmNode(className = "NestOuterInterfaceA$NestedEnumE", round = 1) ClassNode after) {
assertThat(before.nestHostClass).isNotEmpty();
assertThat(after.nestHostClass).isNull();
}
}
| [
"[email protected]"
] | |
8decab3c4d2ccfbf16f5296e24d4ed30d2dc3a4d | 4a045ce43accfddaf4c31db61a689f8e70353722 | /VERSION_INTERFACEE_C/API/src/vueGraphique/PanHistorique.java | 6916e3b3121e83ff623be08b4a65ccc261ddac31 | [] | no_license | zDroiDz/Fil-Rouge-Part2 | 8fd3e904a6c28e1ef6020406ae396dcad50e47a1 | 2b68fee31ee1d3807786b0f373229b0861f9b426 | refs/heads/master | 2021-01-24T12:31:22.771640 | 2018-04-28T07:54:31 | 2018-04-28T07:54:31 | 123,135,135 | 0 | 1 | null | 2018-04-14T06:09:08 | 2018-02-27T13:45:45 | Java | UTF-8 | Java | false | false | 6,183 | java | package vueGraphique;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import control.ControlHistorique;
import control.ControlRequeteRecherche;
import model.Admin;
import model.Profil;
// TODO: Auto-generated Javadoc
/**
* The Class PanHistorique.
*/
public class PanHistorique extends JPanel{
/** The control historique. */
private ControlHistorique controlHistorique;
/** The profil. */
private Profil profil;
/** The pan contents. */
private JPanel panContents = new JPanel();
/** The cartes. */
CardLayout cartes ;
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 427882115525050859L;
/** The box mise en page. */
Box boxMiseEnPage = Box.createHorizontalBox();
/** The box recherches. */
Box boxRecherches = Box.createHorizontalBox();
/** The box validation. */
Box boxValidation = Box.createHorizontalBox();
/** The liste inter. */
DefaultListModel<String >listeInter = new DefaultListModel<String>();
/**
* Instantiates a new pan historique.
*
* @param controlHistorique the control historique
* @param profil the profil
*/
public PanHistorique(ControlHistorique controlHistorique, Profil profil) {
this.controlHistorique = controlHistorique;
this.profil = profil;
}
/**
* Initialisation.
*/
public void initialisation() {
controlHistorique.FillBDHistorique(profil);
JLabel ecranTitre = new JLabel("Affichage de l'historique correspondant a : " + profil.getIdentifiant());
ecranTitre.setFont(new Font("Calibri", Font.BOLD, 24));
boxMiseEnPage.add(ecranTitre);
ArrayList<String> listeRecherches = (ArrayList<String>) controlHistorique.consulterListeRecherche();
JList<String >liste = new JList<String>(listeInter);
for(String recherche : listeRecherches) {
listeInter.addElement(recherche);
}
liste.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
liste.setLayoutOrientation(JList.VERTICAL);
liste.setFont(new Font("Calibri", Font.PLAIN, 20));
JScrollPane listScroller = new JScrollPane(liste);
listScroller.setPreferredSize(new Dimension(600,400));
JButton validation = new JButton();
validation.setText("Confirmer");
validation.setFont(new Font("Calibri", Font.BOLD, 25));
boxValidation.add(validation);
boxMiseEnPage.add(boxRecherches);
this.add(boxMiseEnPage);
this.add(listScroller);
this.add(boxValidation);
validation.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(liste.getSelectedIndex());
System.out.println((String) (controlHistorique.consulterHistoriqueRecherche(liste.getSelectedIndex())).get(0));
afficherResultat((String) (controlHistorique.consulterHistoriqueRecherche(liste.getSelectedIndex())).get(0));
}
});
}
/**
* Update liste historique.
*/
public void updateListeHistorique() {
controlHistorique.clearBDHistorique();
controlHistorique.FillBDHistorique(profil);
ArrayList<String> listeRecherches = (ArrayList<String>) controlHistorique.consulterListeRecherche();
listeInter.clear();
for(String recherche : listeRecherches) {
listeInter.addElement(recherche);
}
}
/**
* Afficher resultat.
*
* @param resultat the resultat
*/
private void afficherResultat(String resultat) {
/*//cartes.show(panContents, "RESULTAT RECHERCHE");
JFrame resultat = new JFrame();
System.out.println("test");
Box boxMiseEnPage = Box.createHorizontalBox();
Box boxResultat = Box.createHorizontalBox();
Box boxRetour = Box.createHorizontalBox();
Box boxTexte = Box.createHorizontalBox();
JLabel ecranTitre = new JLabel("Affichage de l'historique correspondant � : " + profil.getIdentifiant());
ecranTitre.setFont(new Font("Calibri", Font.BOLD, 10));
//boxMiseEnPage.add(ecranTitre);
Box boxAffichageTypeRecherche = Box.createHorizontalBox();
Box boxAffichageDateRecherche = Box.createHorizontalBox();
JLabel typeRecherche = new JLabel("default type");
boxMiseEnPage.add(typeRecherche);
JLabel dateRecherche = new JLabel("default date");
boxMiseEnPage.add(dateRecherche);
JTextArea textArea = new JTextArea();
for(String a : liste){
textArea.append(a + "\n\n");
}
textArea.setBounds(10, 10, 200, 200);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
boxTexte.add(textArea);
boxTexte.setBounds(0, 0, 200, 200);
resultat.add(boxMiseEnPage);
//resultat.add(boxTexte);
resultat.getContentPane().addHierarchyBoundsListener(new HierarchyBoundsListener(){
@Override
public void ancestorMoved(HierarchyEvent arg0) {
// TODO Auto-generated method stub
//System.out.println(arg0);
}
@Override
public void ancestorResized(HierarchyEvent arg0) {
// TODO Auto-generated method stub
//System.out.println(arg0);
int x = resultat.getWidth() - 100;
int y = resultat.getHeight() - 100;
//System.out.println("x : " + x + ",y : " + y);
//textArea.setBounds(10,10,x,y);
}
});
//resultat.setSize(400, 400);
Point location = this.getLocation();
if((location.getX() + 700) < 1500)
location.translate(700, 0);
else
location.translate(0, 600);
resultat.setLocation(location);
resultat.setTitle("Resultat recherche");
resultat.setVisible(true);
*/
ControlRequeteRecherche requete = new ControlRequeteRecherche(resultat);
PopupHistorique affichage = new PopupHistorique(requete);
affichage.setVisible(true);
}
}
| [
"[email protected]"
] | |
1428be0f2e5a732fe97e342b4818c14aecd12a25 | 5ecc16187ff70f049bbe6bbae38ef42045c41047 | /app/src/main/java/com/iyoho/social/fragment/tab/FindFragment.java | 9d82bb1c038c5e1d2e96916a9599ec5d5e2c4e26 | [] | no_license | stevenzhu/YohoSocial6 | b02edf81f51fbe03bba59197040276bef8cc8c61 | a8ed870923bd8f3b37eab04e7a1ccd2990de182d | refs/heads/master | 2021-08-14T17:28:53.026823 | 2017-11-16T10:19:45 | 2017-11-16T10:19:45 | 109,644,876 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 995 | java | package com.iyoho.social.fragment.tab;
import android.view.View;
import android.widget.Button;
import com.iyoho.social.R;
import com.iyoho.social.base.IBaseFragment;
import io.rong.imkit.RongIM;
import com.iyoho.social.R;
import static com.iyoho.social.R.id.tvBtn;
public class FindFragment extends IBaseFragment {
private static final String TAG = "MineFragment";
@Override
public int initLayout() {
return R.layout.fragment_mine;
}
@Override
public void initView(View view) {
Button btn=view.findViewById(tvBtn);
btn.setText("find");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RongIM.getInstance().startPrivateChat(getActivity(),"26594","ttlltt");
}
});
}
@Override
public void initEvent() {
}
@Override
public void initData() {
}
@Override
public void onClick(View v) {
}
} | [
"[email protected]"
] | |
4897a1c6fba7b318b5795aadd9e2aa28cd624a72 | cb719fa8db8c75914e258ed098121d24fbadc605 | /common/src/main/java/com/example/common/net/core/NetService.java | 1fb1de85a335abb414e41e38038ddc03a74cfa6c | [] | no_license | chenwentong0/TopsportsDemo | 686d73d747f9445876f86aa31d59f3106a127205 | b5f7accc4843b9969d86ae2dcdafb359c4af2ce0 | refs/heads/master | 2020-03-27T10:25:50.493032 | 2018-08-29T10:06:06 | 2018-08-29T10:06:06 | 146,419,505 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,230 | java | package com.example.common.net.core;
import android.text.TextUtils;
import com.example.common.utils.ToastUtil;
import org.reactivestreams.Subscriber;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.reactivex.Flowable;
import io.reactivex.FlowableOperator;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author by chen.wentong on 2018/8/17.
* 网络请求封装
*/
public class NetService {
private static NetService sInstance;
private String mDefaultUrl;
private Class mService;
private NetService() {
}
public static NetService getInstance() {
if (sInstance == null) {
synchronized (NetService.class) {
if (sInstance == null) {
sInstance = new NetService();
}
}
}
return sInstance;
}
public <S> void init(String baseUrl, Class<S> service) {
mDefaultUrl = baseUrl;
mService = service;
}
public <S> S getService() {
return (S) getService(mDefaultUrl, mService);
}
public <S> S getService(String baseUrl, Class<S> service) {
return getService(new NetConfig.Builder().setBaseUrl(baseUrl).build(), service);
}
/**
* 获取service
* @param netConfig
* @param service
* @param <S>
* @return
*/
public <S> S getService(NetConfig netConfig, Class<S> service) {
ObjectHelper.requireNonNull(netConfig, "netConfig cant be null");
ObjectHelper.requireNonNull(service, "service cant be null");
//添加线程切换代理
S s = createRetrofit(netConfig).create(service);
return (S)Proxy.newProxyInstance(service.getClassLoader(), new Class[]{service}, new NetInvocationHandler<>(s));
}
public Retrofit createRetrofit(String baseUrl) {
return createRetrofit(new NetConfig.Builder().setBaseUrl(baseUrl).build());
}
/**
* 创建baseurl的retrofit
* @param
* @return
*/
public Retrofit createRetrofit(NetConfig netConfig) {
ObjectHelper.requireNonNull(netConfig, "netConfig cant be null");
validateUrl(netConfig.getBaseUrl());
return new Retrofit.Builder()
.baseUrl(netConfig.getBaseUrl())
.client(createClient(netConfig))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public OkHttpClient createClient(NetConfig netConfig) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置超时时间
builder.connectTimeout(netConfig.getConnectTimeout(), TimeUnit.MILLISECONDS);
builder.readTimeout(netConfig.getReadTimeout(), TimeUnit.MILLISECONDS)
.writeTimeout(netConfig.getWriteTimeout(), TimeUnit.MILLISECONDS);
//添加拦截器(日志,请求头,token等)
Interceptor logInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//打印请求信息
//打印响应信息
return chain.proceed(request);
}
};
builder.addInterceptor(logInterceptor);
List<Interceptor> interceptors = netConfig.getInterceptors();
if (interceptors != null) {
for (Interceptor interceptor : interceptors) {
builder.addInterceptor(interceptor);
}
}
return builder.build();
}
private void validateUrl(String url) {
if (TextUtils.isEmpty(url) || !url.startsWith("http")) {
throw new IllegalArgumentException("url must start with http or url is empty");
}
}
/**
* 网络请求线程切换代理类
*/
public static class NetInvocationHandler<T> implements InvocationHandler {
private T mActualService;
public NetInvocationHandler(T service) {
mActualService = service;
}
@Override
public Flowable invoke(Object proxy, Method method, Object[] args) throws Throwable {
//代理对象调用指定方法后,方法的返回值
Object result = method.invoke(mActualService, args);
if (result != null && result instanceof Flowable) {
Flowable flowable = (Flowable) result;
return flowable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
} else {
return (Flowable) result;
}
}
}
}
| [
"[email protected]"
] | |
c469cbbfbb81bb890ad701c0f8d53bb8ec3d8b25 | ae899b80564897a282d6773b14de87e295b40d31 | /java_ustglobal/Exceptions/src/com/ustglobal/exception/TestB.java | 7e217bc8cf16538c07e1fc6d9b2b2d837b6a7ec7 | [] | no_license | kavitha376/ustglobal_16sep19_kavitha | 34fc25c460c07364c7ebcbdc46f05e0908e08f67 | fc6442fe4f82241cdc50d4e563563ebd48a7a534 | refs/heads/master | 2023-01-08T23:25:53.772081 | 2019-12-22T03:17:42 | 2019-12-22T03:17:42 | 215,537,933 | 0 | 0 | null | 2023-01-07T13:03:05 | 2019-10-16T12:03:11 | HTML | UTF-8 | Java | false | false | 460 | java | package com.ustglobal.exception;
public class TestB {
public static void main(String[] args) {
System.out.println("main started");
int a = 10;
int b = 0;
try
{
b = 10/1;
System.out.println(b);
System.out.println("hello");
System.out.println("happy deepvali");
}
catch(ArithmeticException ae)
{
System.out.println("number is divided by zero");
}
System.out.println(b);
System.out.println("main ended");
}
}
| [
"[email protected]"
] | |
2b04abe175c8212cb1a9d8d88afbd3b27f4b849d | a315cd05c6454bc75f46270d96af10ee60fed93f | /src/org/evolizer/changedistiller/distilling/FieldRefactoringHelper.java | 67bc31b5ff5234e3669d1f27463cf05b27127530 | [] | no_license | BensonQuach/ChangeDistiller | df71f01c7f73a35cec3cfc935fa49409011e2055 | e90cdd7157642442f3309cb8a8e0b396f56e064c | refs/heads/master | 2020-04-15T06:38:06.784426 | 2011-05-14T19:00:09 | 2011-05-14T19:00:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,149 | java | /*
* Copyright 2009 University of Zurich, Switzerland
*
* 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.evolizer.changedistiller.distilling;
import org.evolizer.changedistiller.model.classifiers.EntityType;
import org.evolizer.changedistiller.model.entities.ClassHistory;
import org.evolizer.changedistiller.model.entities.StructureEntityVersion;
import simpack.accessor.string.StringAccessor;
import simpack.measure.sequence.Levenshtein;
/**
* Helps finding refactorings of fields.
*
* @author fluri
* @see AbstractRefactoringHelper
*/
public class FieldRefactoringHelper extends AbstractRefactoringHelper {
/**
* Creates a new refactoring helper.
*
* @param classHistory
* on which the helper creates new {@link StructureEntityVersion}s
*/
public FieldRefactoringHelper(ClassHistory classHistory) {
super(classHistory);
}
/**
* {@inheritDoc}
*/
@Override
public StructureEntityVersion createStructureEntityVersion(String name, int modifiers) {
return getClassHistory().createAttribute(name, modifiers);
}
/**
* {@inheritDoc}
*/
@Override
public StructureEntityVersion createStructureEntityVersion(String oldEntityName, String newEntityName, int modifiers) {
StructureEntityVersion attribute = createStructureEntityVersion(oldEntityName, modifiers);
if (!oldEntityName.equals(newEntityName)) {
attribute.setUniqueName(newEntityName);
getClassHistory().overrideAttributeHistory(oldEntityName, newEntityName);
}
return attribute;
}
/**
* {@inheritDoc}
*/
@Override
public String extractShortName(String uniqueName) {
int pos = uniqueName.indexOf(':');
if (pos > 0) {
return uniqueName.substring(0, pos);
}
return uniqueName.substring(0);
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.FIELD_DECLARATION;
}
/**
* {@inheritDoc}
*/
@Override
public double similarity(
String oldEntityName,
String newEntityName,
String oldEntityRepresentation,
String newEntityRepresentation) {
if (!oldEntityName.equals(newEntityName)) {
Levenshtein<String> lm =
new Levenshtein<String>(new StringAccessor(oldEntityRepresentation), new StringAccessor(
newEntityRepresentation));
return lm.getSimilarity();
} else {
return 1.0;
}
}
}
| [
"[email protected]"
] | |
da9a7ebb3c3276ed4d10e13f948f12bf5288ab6b | bcaeeced6641a25aa3d678f97a09f49e3ddaad6c | /src/Waits.java | 55154eb4857b5891083f351c590462b4774b998e | [] | no_license | sanjulb/Automation | e41e9114424b597dcf4802217473a36f9d68decb | 7f47d0f8110acf18f20c23fcbba2dfcaa7ee578d | refs/heads/main | 2023-06-09T05:00:14.055856 | 2021-06-27T14:13:35 | 2021-06-27T14:13:35 | 380,754,998 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 673 | java | import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Waits {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", ".\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
// it will implicitly wait for few seconds
driver.findElement(By.cssSelector("sanju"));
driver.close();
}
}
| [
"[email protected]"
] | |
60a08dd32e1958e9ce41ce165f658ba62b246929 | 3cd69da4d40f2d97130b5bf15045ba09c219f1fa | /sources/com/fasterxml/jackson/databind/deser/impl/SetterlessProperty.java | 7f63460a69968b0f833a183a8fea5052dd510408 | [] | no_license | TheWizard91/Album_base_source_from_JADX | 946ea3a407b4815ac855ce4313b97bd42e8cab41 | e1d228fc2ee550ac19eeac700254af8b0f96080a | refs/heads/master | 2023-01-09T08:37:22.062350 | 2020-11-11T09:52:40 | 2020-11-11T09:52:40 | 311,927,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,872 | java | package com.fasterxml.jackson.databind.deser.impl;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.SettableBeanProperty;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.util.Annotations;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public final class SetterlessProperty extends SettableBeanProperty {
private static final long serialVersionUID = 1;
protected final AnnotatedMethod _annotated;
protected final Method _getter;
public SetterlessProperty(BeanPropertyDefinition beanPropertyDefinition, JavaType javaType, TypeDeserializer typeDeserializer, Annotations annotations, AnnotatedMethod annotatedMethod) {
super(beanPropertyDefinition, javaType, typeDeserializer, annotations);
this._annotated = annotatedMethod;
this._getter = annotatedMethod.getAnnotated();
}
protected SetterlessProperty(SetterlessProperty setterlessProperty, JsonDeserializer<?> jsonDeserializer) {
super((SettableBeanProperty) setterlessProperty, jsonDeserializer);
this._annotated = setterlessProperty._annotated;
this._getter = setterlessProperty._getter;
}
protected SetterlessProperty(SetterlessProperty setterlessProperty, String str) {
super((SettableBeanProperty) setterlessProperty, str);
this._annotated = setterlessProperty._annotated;
this._getter = setterlessProperty._getter;
}
public SetterlessProperty withName(String str) {
return new SetterlessProperty(this, str);
}
public SetterlessProperty withValueDeserializer(JsonDeserializer<?> jsonDeserializer) {
return new SetterlessProperty(this, jsonDeserializer);
}
public <A extends Annotation> A getAnnotation(Class<A> cls) {
return this._annotated.getAnnotation(cls);
}
public AnnotatedMember getMember() {
return this._annotated;
}
public final void deserializeAndSet(JsonParser jsonParser, DeserializationContext deserializationContext, Object obj) throws IOException, JsonProcessingException {
if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) {
try {
Object invoke = this._getter.invoke(obj, new Object[0]);
if (invoke != null) {
this._valueDeserializer.deserialize(jsonParser, deserializationContext, invoke);
return;
}
throw new JsonMappingException("Problem deserializing 'setterless' property '" + getName() + "': get method returned null");
} catch (Exception e) {
_throwAsIOE(e);
}
}
}
public Object deserializeSetAndReturn(JsonParser jsonParser, DeserializationContext deserializationContext, Object obj) throws IOException, JsonProcessingException {
deserializeAndSet(jsonParser, deserializationContext, obj);
return obj;
}
public final void set(Object obj, Object obj2) throws IOException {
throw new UnsupportedOperationException("Should never call 'set' on setterless property");
}
public Object setAndReturn(Object obj, Object obj2) throws IOException {
set(obj, obj2);
return null;
}
}
| [
"[email protected]"
] | |
f805e46786fffeb87e9698e33c63b6c624458582 | b21a83c519fbde9a9915f19e820850f583fc6891 | /cryptobets/src/main/java/fernandez/abel/cryptobets/usecase/createBet/SimpleCreateBetUseCase.java | 9656790095c082deca678ac74ad9cda37fdb61c0 | [] | no_license | abelfernandezc/cryptobets-test | 83c0c3c1d471de680807369955c3d9d851ed84be | 8756c728f02297574c429d3439bb40e596819f33 | refs/heads/main | 2023-07-04T16:47:02.718485 | 2021-08-19T04:56:58 | 2021-08-19T04:56:58 | 397,469,397 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,695 | java | package fernandez.abel.cryptobets.usecase.createBet;
import fernandez.abel.cryptobets.exception.BadRequestException;
import fernandez.abel.cryptobets.exception.NotBetValidException;
import fernandez.abel.cryptobets.messaging.BetReceptionNotification;
import fernandez.abel.cryptobets.model.Bet;
import fernandez.abel.cryptobets.model.RoundOfBet;
import fernandez.abel.cryptobets.model.RoundOfBetStatus;
import fernandez.abel.cryptobets.repository.BetRepository;
import fernandez.abel.cryptobets.repository.RoundOfBetRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@AllArgsConstructor
@Slf4j
public class SimpleCreateBetUseCase implements CreateBetUseCase{
private final BetRepository betRepository;
private final RoundOfBetRepository roundRepository;
private final MessageSendingOperations<String> messageSendingOperations;
private final BetReceptionNotification betReceptionNotification;
public Bet execute(Bet bet) {
log.info("CreateBetUserCase.execute {}", bet);
validateBet(bet);
bet = betRepository.saveAndFlush(bet);
List<Bet> bets = betRepository.findByRoundOfBetId(bet.getRoundOfBetId());
String broadcast = String.format("Quantity of bets: %s", bets.size());
this.messageSendingOperations.convertAndSend("/topic/bet-quantity", broadcast);
betReceptionNotification.sendBetReceptionNotification(bet);
return bet;
}
private void validateBet(Bet bet) {
if (bet == null) {
throw new BadRequestException("The bet is required");
}
if (bet.getUser() == null || bet.getUser().equals("")) {
throw new BadRequestException("The user is required");
}
if (bet.getBetPrice() == null || bet.getBetPrice().isNaN()) {
throw new BadRequestException("The bet price is required");
}
List<RoundOfBet> roundList = roundRepository.findByStatus(RoundOfBetStatus.OPEN.get());
if (roundList.isEmpty()) {
throw new NotBetValidException("In this time not exist a round of bets open");
}
if (roundList.size() > 1) {
throw new NotBetValidException("In this time exist more than permitted round of bets opens");
}
if (!roundList.get(0).isAvailableForBet()) {
throw new NotBetValidException("At this time bets are no longer accepted for this round, please wait for the new round available");
}
bet.setRoundOfBetId(roundList.get(0).getId());
}
}
| [
"[email protected]"
] | |
40289ead099a694ac0f3871ed30e4f7b5b8f2c38 | c638208c6246cd78d59cfac7414a47bded7cb969 | /es.kybele.kybdele.models.relational.diagram/src/gmf_relational_model/gmf_relational_model/diagram/navigator/RelationalModelNavigatorItem.java | 1220b3907586a36ff4896ce89a3a0c2a3a8a41bc | [] | no_license | AngelMorenoMDE/kybdele_relational | b008fcf5c22098bc2e0df9e971fa8974058e80c9 | a354145c0d42268ce3f9df66581d22819c74eb53 | refs/heads/master | 2021-01-13T00:52:41.340620 | 2016-03-02T13:57:29 | 2016-03-02T13:57:29 | 52,961,528 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,331 | java | package gmf_relational_model.gmf_relational_model.diagram.navigator;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gmf.runtime.notation.View;
/**
* @generated
*/
public class RelationalModelNavigatorItem
extends
gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelAbstractNavigatorItem {
/**
* @generated
*/
static {
final Class[] supportedTypes = new Class[] { View.class, EObject.class };
Platform.getAdapterManager().registerAdapters(
new IAdapterFactory() {
public Object getAdapter(Object adaptableObject,
Class adapterType) {
if (adaptableObject instanceof gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelNavigatorItem
&& (adapterType == View.class || adapterType == EObject.class)) {
return ((gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelNavigatorItem) adaptableObject)
.getView();
}
return null;
}
public Class[] getAdapterList() {
return supportedTypes;
}
},
gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelNavigatorItem.class);
}
/**
* @generated
*/
private View myView;
/**
* @generated
*/
private boolean myLeaf = false;
/**
* @generated
*/
public RelationalModelNavigatorItem(View view, Object parent, boolean isLeaf) {
super(parent);
myView = view;
myLeaf = isLeaf;
}
/**
* @generated
*/
public View getView() {
return myView;
}
/**
* @generated
*/
public boolean isLeaf() {
return myLeaf;
}
/**
* @generated
*/
public boolean equals(Object obj) {
if (obj instanceof gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelNavigatorItem) {
return EcoreUtil
.getURI(getView())
.equals(EcoreUtil
.getURI(((gmf_relational_model.gmf_relational_model.diagram.navigator.RelationalModelNavigatorItem) obj)
.getView()));
}
return super.equals(obj);
}
/**
* @generated
*/
public int hashCode() {
return EcoreUtil.getURI(getView()).hashCode();
}
}
| [
"[email protected]"
] | |
1097406bdb9b1d797118ef7483d52dfc93e8b939 | 01b23223426a1eb84d4f875e1a6f76857d5e8cd9 | /icefaces3/tags/icefaces-3.3.0.RC1/icefaces/ace/component/src/org/icefaces/ace/component/themeselect/ThemeSelectMeta.java | 7b3edbf429c6603114e15f2f399daba42e7f8451 | [
"Apache-2.0"
] | permissive | numbnet/icesoft | 8416ac7e5501d45791a8cd7806c2ae17305cdbb9 | 2f7106b27a2b3109d73faf85d873ad922774aeae | refs/heads/master | 2021-01-11T04:56:52.145182 | 2016-11-04T16:43:45 | 2016-11-04T16:43:45 | 72,894,498 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,351 | java | /*
* Copyright 2004-2013 ICEsoft Technologies Canada Corp.
*
* 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.icefaces.ace.component.themeselect;
import org.icefaces.ace.meta.annotation.ClientBehaviorHolder;
import org.icefaces.ace.meta.annotation.ClientEvent;
import org.icefaces.ace.meta.annotation.Component;
import org.icefaces.ace.meta.annotation.Property;
import org.icefaces.ace.meta.baseMeta.UIInputMeta;
import org.icefaces.ace.resources.ACEResourceNames;
import org.icefaces.resources.ICEResourceDependencies;
import org.icefaces.resources.ICEResourceDependency;
import org.icefaces.resources.ICEResourceLibrary;
@Component(
tagName = "themeSelect",
componentClass = "org.icefaces.ace.component.themeselect.ThemeSelect",
rendererClass = "org.icefaces.ace.component.themeselect.ThemeSelectRenderer",
generatedClass = "org.icefaces.ace.component.themeselect.ThemeSelectBase",
extendsClass = "javax.faces.component.UIInput",
componentType = "org.icefaces.ace.component.ThemeSelect",
rendererType = "org.icefaces.ace.component.ThemeSelectRenderer",
componentFamily = "org.icefaces.ace.ThemeSelect",
tlddoc = "The themeSelect component can be used to dynamically change the current ACE ThemeRoller theme in the application. " +
"<p>For more information, see the <a href=\"http://wiki.icefaces.org/display/ICE/ThemeSelect\">ThemeSelect Wiki Documentation</a>."
)
@ICEResourceLibrary(ACEResourceNames.ACE_LIBRARY)
@ICEResourceDependencies({
@ICEResourceDependency(name = ACEResourceNames.COMBINED_CSS),
@ICEResourceDependency(name = ACEResourceNames.JQUERY_JS),
@ICEResourceDependency(name = ACEResourceNames.COMPONENTS_JS)
})
@ClientBehaviorHolder(events = {
@ClientEvent(name = "valueChange", javadoc = "Fired whenever the value of the component changes (default event).",
tlddoc = "Fired whenever the value of the component changes (default event).", defaultRender = "@this", defaultExecute = "@this")
}, defaultEvent = "valueChange")
public class ThemeSelectMeta extends UIInputMeta {
@Property(tlddoc = "Access key that, when pressed, transfers focus to this element.")
private String accesskey;
@Property(tlddoc = "Direction indication for text that does not inherit directionality. Valid values are \"LTR\" (left-to-right) and \"RTL\" (right-to-left).")
private String dir;
@Property(tlddoc = "Flag indicating that this element must never receive focus or be included in a subsequent submit. A value of false causes no attribute to be rendered, while a value of true causes the attribute to be rendered as disabled=\"disabled\".")
private boolean disabled;
@Property(tlddoc = "Code describing the language used in the generated markup for this component.")
private String lang;
@Property(tlddoc = "A localized user presentable name for this component.")
private String label;
@Property(tlddoc = "CSS style(s) to be applied when this component is rendered.")
private String style;
@Property(tlddoc = "Space-separated list of CSS style class(es) to be applied when this element is rendered. This value must be passed through as the \"class\" attribute on generated markup.")
private String styleClass;
@Property(tlddoc = "Position of this element in the tabbing order for the current document. This value must be an integer between 0 and 32767.")
private String tabindex;
@Property(tlddoc = "Advisory title information about markup elements generated for this component.")
private String title;
@Property(tlddoc = "Alternate textual description of the element rendered by this component.")
private String alt;
}
| [
"ken.fyten@8668f098-c06c-11db-ba21-f49e70c34f74"
] | ken.fyten@8668f098-c06c-11db-ba21-f49e70c34f74 |
200a72d5c40d4f70eeef2770f14edc6ee9e4c94c | 147cec9d3d3a7842d7d747a79af5ff0e606a526a | /net/minecraft/dispenser/BehaviorProjectileDispense.java | 1bafb8fd638c59472fc7edfa2cbe69fede075143 | [] | no_license | LXisCool1337/Async-Src | 3f365c69a12ef61d1192d5a276473106c4c4b067 | 77ac70ec28e8d2933ea5a554c026c59023ec630d | refs/heads/main | 2023-09-02T20:59:38.814117 | 2021-11-16T19:19:08 | 2021-11-16T19:19:08 | 428,784,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,405 | java | package net.minecraft.dispenser;
import net.minecraft.block.BlockDispenser;
import net.minecraft.entity.Entity;
import net.minecraft.entity.IProjectile;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
public abstract class BehaviorProjectileDispense extends BehaviorDefaultDispenseItem
{
public ItemStack dispenseStack(IBlockSource source, ItemStack stack)
{
World world = source.getWorld();
IPosition iposition = BlockDispenser.getDispensePosition(source);
EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata());
IProjectile iprojectile = this.getProjectileEntity(world, iposition);
iprojectile.setThrowableHeading((double)enumfacing.getFrontOffsetX(), (double)((float)enumfacing.getFrontOffsetY() + 0.1F), (double)enumfacing.getFrontOffsetZ(), this.func_82500_b(), this.func_82498_a());
world.spawnEntityInWorld((Entity)iprojectile);
stack.splitStack(1);
return stack;
}
protected void playDispenseSound(IBlockSource source)
{
source.getWorld().playAuxSFX(1002, source.getBlockPos(), 0);
}
protected abstract IProjectile getProjectileEntity(World worldIn, IPosition position);
protected float func_82498_a()
{
return 6.0F;
}
protected float func_82500_b()
{
return 1.1F;
}
}
| [
"[email protected]"
] | |
3bc8811c370f8b083d51d6b51d0f8bb11314dfe6 | 0674f4bce98103ad8693a953fed2ba9143a9ca76 | /redis/src/main/java/com/momo/distributedlock/redis/Test.java | 55d4bbe269e8ddebc543c2125aaa1203620d4740 | [] | no_license | mytt-10566/distributedlock | e443553fb87c7c692688be5a628a0e69ac4027b5 | 75294307535b00f160ef66136c369952336e79da | refs/heads/master | 2020-04-11T18:51:11.138455 | 2018-12-17T09:49:06 | 2018-12-17T09:49:06 | 162,013,740 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 366 | java | package com.momo.distributedlock.redis;
public class Test {
public static void main(String[] args) {
Service service = new Service();
Runnable runnable = () -> {
service.doService();
};
for (int i = 0; i < 1000; i++) {
Thread thread = new Thread(runnable);
thread.start();
}
}
}
| [
"[email protected]"
] | |
4715efbb41cea388f5c72677d8f10b90486df6b3 | 66c6ebad0c506704f012e28fa666d3bc35caa29f | /app/src/main/java/com/example/mvvm_jetpack_practice/database/dao/PersonStateDao.java | aff71cc6b359ad8611bd9c17b5b79d4c6b8e653a | [] | no_license | 283006603/room | 2961eec99bb4f7eae78812140c4a00a608b6b917 | fa7cbec240287fafd87318c25c6866bb7bf915df | refs/heads/master | 2022-12-13T01:38:39.534214 | 2020-09-16T02:14:36 | 2020-09-16T02:14:36 | 295,897,077 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 801 | java | package com.example.mvvm_jetpack_practice.database.dao;
import com.example.mvvm_jetpack_practice.bean.PersonStateBean;
import java.util.List;
import androidx.room.Dao;
import androidx.room.Query;
@Dao
public interface PersonStateDao extends BaseDao<PersonStateBean>{
//根据id精确查找某一个persion
@Query("select *from personstatebean where person_id=(:personId)")
PersonStateBean queryPersonById(int personId);
//把吃了饭的人全部找出来
@Query("select * from personstatebean where is_eat=(:isEat)")
PersonStateBean queryListPersonByEat(boolean isEat);
//把所有人找出来(他们的共有属性,是自己定的type=1)
@Query("select * from personstatebean where type=(:type)")
List<PersonStateBean> queryListPersonByType(int type);
}
| [
"[email protected]"
] | |
72912bf5df30c0a10c184278495e1d56b13695c7 | af70e8b7291fe3c0169cd7c9d07c6b429e4db29e | /opencensus-shim/src/main/java/openconsensus/opencensusshim/stats/StatsCollectionState.java | c34946ca2cc9f6e92986b9ac4377345fb8db9b58 | [
"Apache-2.0"
] | permissive | yurishkuro/opentelemetry-java | a967261fd8d50f6a18cee399049b16a60ded2698 | 8e08585053f7f92480efab7e7cd342832304e343 | refs/heads/master | 2020-05-18T14:22:48.259299 | 2019-05-01T19:13:17 | 2019-05-01T19:13:17 | 184,468,638 | 0 | 0 | Apache-2.0 | 2019-05-01T19:18:46 | 2019-05-01T19:18:45 | null | UTF-8 | Java | false | false | 1,199 | java | /*
* Copyright 2019, OpenConsensus 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 openconsensus.opencensusshim.stats;
/**
* State of the {@link StatsComponent}.
*
* @since 0.1.0
*/
public enum StatsCollectionState {
/**
* State that fully enables stats collection.
*
* <p>The {@link StatsComponent} collects stats for registered views.
*
* @since 0.1.0
*/
ENABLED,
/**
* State that disables stats collection.
*
* <p>The {@link StatsComponent} does not need to collect stats for registered views and may
* return empty {@link ViewData}s from {@link ViewManager#getView(View.Name)}.
*
* @since 0.1.0
*/
DISABLED
}
| [
"[email protected]"
] | |
e7b86117412ae727f86aa67188c29054e4d4e54f | 48fd0b689f9cdb660ad06a191107e14d47542fd8 | /ada32/src/SnakeHeadLogicStep.java | e83707ee4816b774611cad7d9fa24ab5ad1bd3b8 | [
"MIT"
] | permissive | chiendarrendor/AlbertsAdalogicalAenigmas | 3dfc6616d47c361ad6911e2ee4e3a3ec24bb6b75 | c6f91d4718999089686f3034a75a11b312fa1458 | refs/heads/master | 2022-08-28T11:34:02.261386 | 2022-07-08T22:45:24 | 2022-07-08T22:45:24 | 115,220,665 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,860 | java | import grid.logic.LogicStatus;
import grid.logic.LogicStep;
import grid.puzzlebits.Direction;
import java.awt.Point;
public class SnakeHeadLogicStep implements LogicStep<Board> {
int x;
int y;
public SnakeHeadLogicStep(int x, int y) { this.x = x; this.y = y; }
@Override public LogicStatus apply(Board thing) {
NumCell ns = thing.getCell(x,y);
if (ns.isBroken()) return LogicStatus.CONTRADICTION;
if (!ns.isDone()) return LogicStatus.STYMIED;
if (ns.getComplete() != 2) return LogicStatus.STYMIED;
// if we get here, we're standing on a '2' cell.
Direction oned = null;
Point onep = null;
for (Direction d : Direction.orthogonals()) {
Point tp = d.delta(x,y,1);
if (!thing.inBounds(tp.x,tp.y)) continue;
NumCell tns = thing.getCell(tp.x,tp.y);
if (tns.isBroken()) return LogicStatus.CONTRADICTION;
if (!tns.isDone()) continue;
if (tns.getComplete() != 1) continue;
if (onep != null) return LogicStatus.CONTRADICTION;
oned = d;
onep = tp;
}
if (onep == null) return LogicStatus.STYMIED;
// if we get here, we are a 2 and we are next to a 1, which means that all cells out in that
// direction must be empty.
LogicStatus result = LogicStatus.STYMIED;
for (int idx = 1 ; ; ++idx){
Point np = oned.delta(onep,idx);
if (!thing.inBounds(np.x,np.y)) break;
NumCell dns = thing.getCell(np.x,np.y);
if (dns.isBroken()) return LogicStatus.CONTRADICTION;
if (!dns.doesContain(0)) return LogicStatus.CONTRADICTION;
if (dns.isDone()) continue;
dns.set(0);
result = LogicStatus.LOGICED;
}
return result;
}
}
| [
"[email protected]"
] | |
51a9f3d4fb95f9ead03380d2b493ed3eb8b685c4 | c65b26ea6036514176990fad78e11358b347b8a0 | /src/com/behavioral/chainofresponsibility/ATMDispenseChain.java | bd677651826d83673b7b9c545b18e7484fc1e71a | [] | no_license | AnouarMhand/Java-Design-Patterns | 617d406967be25d72e3e0d3179ad042612b7dd53 | 0467009937b6c79e6c04265f4636923657e97bdd | refs/heads/master | 2022-10-18T10:29:04.346257 | 2020-06-09T22:11:34 | 2020-06-09T22:11:34 | 262,902,254 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 818 | java | package com.behavioral.chainofresponsibility;
import java.util.Scanner;
public class ATMDispenseChain {
private DispenseChain c1;
ATMDispenseChain() {
this.c1 = new USD100Dispenser();
DispenseChain c2 = new USD50Dispenser();
DispenseChain c3 = new USD20Dispenser();
// set the chain of responsibility
c1.setNextChain(c2);
c2.setNextChain(c3);
}
public static void main(String[] args) {
ATMDispenseChain atmDispenser = new ATMDispenseChain();
while (true) {
int amount = 0;
System.out.println("Enter amount to dispense");
Scanner input = new Scanner(System.in);
amount = input.nextInt();
if (amount % 20 != 0) {
System.out.println("Amount should be in multiple of 20s.");
return;
}
// process the request
atmDispenser.c1.dispense(new Currency(amount));
}
}
}
| [
"[email protected]"
] | |
51f44bc4c43cb57dfe952b034d7b00fd11fedeeb | 20611703dd7f9abf4193032daff482cfca5ef5eb | /busreservationsys/src/main/java/com/brs/controller/UserController.java | 77b1f92e6d6a1551ea7aebccbd99a3287af717fc | [] | no_license | DevapriyaV/Busreservation | 5ea6b7b2c328eff4e122218d681b6b1f3414cc4e | 4e95d8d6b3cda295f187aadfc147788ef516110c | refs/heads/master | 2023-08-07T17:30:13.014619 | 2021-09-23T05:07:08 | 2021-09-23T05:07:08 | 409,428,652 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,832 | java | package com.brs.controller;
import java.util.List;
import java.util.logging.Logger;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.brs.entity.User;
import com.brs.exceptions.UserNotFoundException;
import com.brs.service.IUserService;
/**
* Description:This is UserController Layer
**/
@RestController
public class UserController {
Logger log = Logger.getLogger("UserController");
@Autowired
private IUserService userservice;
/**
* Description :To add user details into the database Return Value :user object
* of the user been fetched
**/
@PostMapping("addUser")
public ResponseEntity<User> addUser(@Valid @RequestBody User user) {
log.info("adduser method");
return new ResponseEntity<User>(userservice.addUser(user), HttpStatus.OK);
}
/**
* Description :To update user details into the database Return Value :user
* object of the user been fetched
**/
@PutMapping("updateUser")
public ResponseEntity<User> updateuser(@Valid @RequestBody User user) {
log.info("update user method");
return new ResponseEntity<User>(userservice.updateUser(user), HttpStatus.OK);
}
/**
* Description :To delete user details from the database Return Value :user
* object of the user been fetched
**/
@DeleteMapping("deleteUser/{Userid}")
public ResponseEntity<User> deleteUser(@PathVariable("Userid") int busId) {
log.info("deleteuser method");
return new ResponseEntity<User>(userservice.deleteUser(busId), HttpStatus.OK);
}
/**
* Description :To view user details in the database Return Value :user object
* of the user been fetched
**/
@GetMapping("view/{Userid}")
public ResponseEntity<User> getUserById(@PathVariable("Userid") int userLoginId) throws UserNotFoundException {
log.info("viewuser by id method");
return new ResponseEntity<User>(userservice.viewUser((long) userLoginId), HttpStatus.OK);
}
/**
* Description :To view all user details in the database Return Value :user
* object of the user been fetched
**/
@GetMapping("alluser")
public ResponseEntity<List<User>> getAllUser() {
log.info("viewalluser method");
return new ResponseEntity<List<User>>(userservice.viewAllUser(), HttpStatus.OK);
}
} | [
"Vetha@LAPTOP-NPPL75RC"
] | Vetha@LAPTOP-NPPL75RC |
9ce0a04b5710bcd4ae8611366e98f251519ce8a2 | 7e1c12b9368cb567c7d5d7e3ca3cb1dd0a2d1753 | /src/test/java/guru/springframework/converters/RecipeCommandToRecipeTest.java | 571b5a281091bb49f00683b7a95611806539c418 | [] | no_license | mistborn03/spring5-recipe-app | bcd34b2385cf4019b8d8b77fe3e4e812fd232391 | d610c6f03b34b3300e078e0213ef83c62cd7b66e | refs/heads/main | 2023-06-09T12:47:07.932757 | 2021-07-05T06:32:50 | 2021-07-05T06:32:50 | 371,307,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,559 | java | package guru.springframework.converters;
import guru.springframework.commands.CategoryCommand;
import guru.springframework.commands.IngredientCommand;
import guru.springframework.commands.NotesCommand;
import guru.springframework.commands.RecipeCommand;
import guru.springframework.domain.Difficulty;
import guru.springframework.domain.Recipe;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class RecipeCommandToRecipeTest {
public static final Integer COOK_TIME = Integer.valueOf("5");
public static final Integer PREP_TIME = Integer.valueOf("7");;
public static final String DESCRIPTION = "My Recipe";
public static final String DIRECTIONS = "Directions";
public static final Integer SERVINGS = Integer.valueOf("3");
public static final String SOURCE = "Source";
public static final String URL = "Some URL";
public static final long ID = 1L;
public static final long INGRED_ID_1 = ID;
public static final long RECIPE_ID = 1L;
public static final Difficulty DIFFICULTY = Difficulty.EASY;
public static final long NOTES_ID = 9L;
public static final long CAT_ID_1 = 1L;
public static final long CAT_ID_2 = 2L;
public static final long INGRED_ID_2 = 2L;
RecipeCommandToRecipe converter;
@BeforeEach
void setUp() {
converter = new RecipeCommandToRecipe(new CategoryCommandToCategory(), new NotesCommandToNotes(),
new IngredientCommandToIngredient(new UnitOfMeasureCommandToUnitOfMeasure()));
}
@Test
void testNullObject() throws Exception{
assertNull(converter.convert(null));
}
@Test
void testEmptyObject() throws Exception {
assertNotNull(converter.convert(new RecipeCommand()));
}
@Test
void convert() {
RecipeCommand recipeCommand = new RecipeCommand();
recipeCommand.setCookTime(COOK_TIME);
recipeCommand.setPrepTime(PREP_TIME);
recipeCommand.setDescription(DESCRIPTION);
recipeCommand.setDirections(DIRECTIONS);
recipeCommand.setDifficulty(DIFFICULTY);
recipeCommand.setServings(SERVINGS);
recipeCommand.setSource(SOURCE);
recipeCommand.setUrl(URL);
recipeCommand.setId(RECIPE_ID);
NotesCommand notes = new NotesCommand();
notes.setId(NOTES_ID);
recipeCommand.setNotes(notes);
CategoryCommand category = new CategoryCommand();
category.setId(CAT_ID_1);
CategoryCommand category2 = new CategoryCommand();
category.setId(CAT_ID_2);
recipeCommand.getCategories().add(category);
recipeCommand.getCategories().add(category2);
IngredientCommand ingredient = new IngredientCommand();
ingredient.setId(INGRED_ID_1);
IngredientCommand ingredient2 = new IngredientCommand();
ingredient.setId(INGRED_ID_2);
recipeCommand.getIngredients().add(ingredient);
recipeCommand.getIngredients().add(ingredient2);
Recipe recipe = converter.convert(recipeCommand);
assertNotNull(recipe);
assertEquals(RECIPE_ID,recipe.getId());
assertEquals(COOK_TIME,recipe.getCookTime());
assertEquals(PREP_TIME,recipe.getPrepTime());
assertEquals(SOURCE,recipe.getSource());
assertEquals(URL,recipe.getUrl());
assertEquals(DIFFICULTY,recipe.getDifficulty());
assertEquals(DIRECTIONS,recipe.getDirections());
assertEquals(SERVINGS,recipe.getServings());
assertEquals(DESCRIPTION,recipe.getDescription());
assertEquals(NOTES_ID,recipe.getNotes().getId());
assertEquals(2,recipe.getCategories().size());
assertEquals(2,recipe.getIngredients().size());
}
}
| [
"[email protected]"
] | |
45c30676a38e7fa3d4730f337dc3ab114388681c | 6a7a63bc5dc68196e14cd9c2255961888f5f1b32 | /src/invaders/Point.java | 26d7483add42e79917c8ac7b9056a95062881f20 | [] | no_license | danzhang41/FakeSpaceInvaders | 0fe41a1c944784001c6c05442878d64b928c5801 | ce12b0c81245dd6788bfb492b131e65ba20acd8d | refs/heads/master | 2020-03-30T02:51:39.153165 | 2018-09-27T22:18:59 | 2018-09-27T22:18:59 | 150,654,881 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,267 | java | package invaders;
public class Point<N>{
private N x, y;
public Point(N x, N y){
this.x = x;
this.y = y;
}
public N getX(){
return this.x;
}
public N getY(){
return this.y;
}
public void setX(N x) {
this.x = x;
}
public void setY(N y) {
this.y = y;
}
public static Point <? extends Number> add(Point <? extends Number> a, Point <? extends Number> b){
if(a.x instanceof Integer){
int x = a.x.intValue() + b.x.intValue();
int y = a.y.intValue() + b.y.intValue();
return new Point<Integer>(x,y);
}
else if(a.x instanceof Double){
double x = a.x.doubleValue() + b.x.doubleValue();
double y = a.y.doubleValue() + b.y.doubleValue();
return new Point<Double>(x,y);
}
else if(a.x instanceof Float){
float x = a.x.floatValue() + b.x.floatValue();
float y = a.y.floatValue() + b.y.floatValue();
return new Point<Float>(x,y);
}
else if(a.x instanceof Long){
long x = a.x.longValue() + b.x.longValue();
long y = a.y.longValue() + b.y.longValue();
return new Point<Long>(x,y);
}
else{
return null;
}
}
public static Point <? extends Number> subtract(Point <? extends Number> a, Point <? extends Number> b){
if(a.x instanceof Integer){
int x = a.x.intValue() - b.x.intValue();
int y = a.y.intValue() - b.y.intValue();
return new Point<Integer>(x,y);
}
else if(a.x instanceof Double){
double x = a.x.doubleValue() - b.x.doubleValue();
double y = a.y.doubleValue() - b.y.doubleValue();
return new Point<Double>(x,y);
}
else if(a.x instanceof Float){
float x = a.x.floatValue() - b.x.floatValue();
float y = a.y.floatValue() - b.y.floatValue();
return new Point<Float>(x,y);
}
else{
long x = a.x.longValue() - b.x.longValue();
long y = a.y.longValue() - b.y.longValue();
return new Point<Long>(x,y);
}
}
@Override public int hashCode(){
if(x instanceof Integer){
final int prime = 31;
int result = 1;
result = prime * result + (int) x;
result = prime * result + (int) y;
return result;
}
else if(x instanceof Double){
final int prime = 31;
int result = 1;
int hX = (int) Double.doubleToLongBits((double) x);
int hY = (int) Double.doubleToLongBits((double) y);
result = prime * result + hX;
result = prime * result + hY;
return (int) result;
}
else if(x instanceof Float){
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits((float) x);
result = prime * result + Float.floatToIntBits((float) y);
return (int) result;
}
else{
long xCoord = (long) x;
long yCoord = (long) y;
final long prime= 31;
long result = 1;
result = prime * 1 + (int)(xCoord ^ (xCoord >>> 32));
result = prime * 1 + (int)(yCoord ^ (yCoord >>> 32));
return (int) result;
}
}
@Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
Point<?> other = (Point<?>) obj;
if(x != other.x)
return false;
if(y != other.y)
return false;
return true;
}
@Override
public String toString(){
return x + "," + y;
}
}
| [
"[email protected]"
] | |
14c157ee852ff361e5dcac537557acead1c3a969 | d32b981c89bce56c24d9512d75b43cabafa220a0 | /src/main/java/io/github/hotdesk/application/security/AuthoritiesConstants.java | db5f49acabd3d4b05c2d2525fc75868d83ca181e | [] | no_license | BulkSecurityGeneratorProject/hotdesk-sample-application | afb88c34422338b9fb77dae5348eeb208475cdc2 | ae1ac9f61a92cdd6324db785c3e2d0685be17add | refs/heads/master | 2022-12-21T14:48:30.313411 | 2019-05-10T08:46:27 | 2019-05-10T08:46:27 | 296,595,532 | 0 | 0 | null | 2020-09-18T10:59:55 | 2020-09-18T10:59:54 | null | UTF-8 | Java | false | false | 359 | java | package io.github.hotdesk.application.security;
/**
* Constants for Spring Security authorities.
*/
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {
}
}
| [
"[email protected]"
] | |
0ed61f67c2236b2d56be440fbfe6f133f59717aa | e463fc52090e01f28ffbd25de2476f7ae150bfa5 | /adapter/src/main/java/org/example/controller/InMemoryUserRepository.java | 78e756a8d4821873f4606937be4554b6d1e9b138 | [] | no_license | mbimbij/clean-architecture-demo-1 | a0d4670c2724576cb91782cf5677fa7bde97a0f3 | 2e3269c6c5a047af9150486569caede8abc78f61 | refs/heads/main | 2023-05-03T09:41:45.717473 | 2021-05-18T09:32:53 | 2021-05-18T09:46:03 | 368,427,428 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 816 | java | package org.example.controller;
import org.example.domain.entity.User;
import org.example.domain.port.UserRepository;
import java.util.*;
public class InMemoryUserRepository implements UserRepository {
private final Map<String, User> inMemoryDb = new HashMap<>();
@Override
public Optional<User> findById(String id) {
return Optional.ofNullable(inMemoryDb.get(id));
}
@Override
public Optional<User> findByEmail(String email) {
return inMemoryDb.values().stream()
.filter(user -> Objects.equals(user.getEmail(), email))
.findFirst();
}
@Override
public List<User> findAllUsers() {
return new ArrayList<>(inMemoryDb.values());
}
@Override
public User create(User userToSave) {
inMemoryDb.put(userToSave.getId(), userToSave);
return userToSave;
}
}
| [
"[email protected]"
] | |
6c84b4aaa9dcf5430fe1e7a378173f3e00b44687 | cd7555289e955b5ca21f86a54183b14b1ad4c482 | /app/src/main/java/com/example/myapp/Json/ActivityJson.java | aaec6040c5c86e9a6b0f9e2e486deba8d5290fda | [] | no_license | quynhvan/MyAppTruyen | 9d7994e06182088952f707a15a77ab8409e11a3e | ba5c759dab6180c114d83b45527297a89160289f | refs/heads/master | 2023-02-28T15:42:31.008763 | 2021-02-03T00:55:49 | 2021-02-03T00:55:49 | 335,466,170 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,864 | java | package com.example.myapp.Json;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.example.myapp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class ActivityJson extends Activity {
private String Van = null;
private ArrayList<ColorObject> listColor = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
String content = LoadFileFromAssests("json_f");
Log.e(Van,"json"+content);
TextView json = findViewById(R.id.tv_color);
json.setText(content);
// bóc tách dữ liệu
// try catch : thực hiện trong try_catch để đảm bảo chương trình không bị gián đoạn trong khối
// try bị lỗi, câu lệnh tiếp theo vẫn thực hiện
try {
//lay ra mảng object
JSONArray jsonArray = new JSONArray(content);
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
// có object ở vị trí i trong mảng rồi
// lay ra
String color = jsonObject.getString("color");
String value = jsonObject.getString("value");
ColorObject colorObject = new ColorObject(color,value);
// thêm object color vào mảng color
listColor.add(colorObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Van","size"+ listColor.size());
}
public String LoadFileFromAssests(String fileName) {
//
String tContents = "";
try {
//getassets truy cập đến mục assests
// để đọc được file cần input stream
// open mở file
// inputStream để đọc file
InputStream stream = getAssets().open(fileName);
// kiểm tra xem file có giá trị hay không?
// lấy ra size của file
int size = stream.available();
// tạo một mảng để lưu dữ liệu đọc được
// buffer chỉ là tên
// buffer là nơi lưu trữ
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
// để chuyển từ một mang byte sang string
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
}
| [
"[email protected]"
] | |
8d4089213c7c31a0e9264d57de4167cb9d1e93a3 | e9b518f5e503edb445c65bb38a2b3174d284e955 | /11_ssm_exam/src/main/java/com/sp/controller/UserController.java | 8158042452cc838115b2f187fca684fc4df92fb8 | [] | no_license | 609849728/hello | d49125e2d429114dd5070eb1672bbe8f8507baec | 5f46fcf5b03cec3bd93c4cd56e30493895e36bc1 | refs/heads/master | 2020-05-23T13:25:30.962587 | 2019-05-15T07:25:23 | 2019-05-15T07:25:23 | 186,771,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,776 | java | package com.sp.controller;
import com.github.pagehelper.PageInfo;
import com.sp.entity.Book;
import com.sp.entity.User;
import com.sp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping("/UserController")
public class UserController {
@Autowired
private UserService userService;
//去登录
@GetMapping("/login")
public String toLogin() {
return "login";
}
@PostMapping("/login")
public String login(String name, String password, HttpServletRequest request) {
User u = userService.login(name, password);
if(u!=null) {
//如果正确,存进session
request.getSession().setAttribute("u",u);
return "redirect:getUserList";
}
request.setAttribute("msg","用户名或密码错误!");
return "login";
}
@RequestMapping("/getUserList")
public String getUserList(Integer pageNum, Model model) {
PageInfo pageInfo = userService.getPageInfo(pageNum);
model.addAttribute("page",pageInfo);
model.addAttribute("pageUrl","UserController/getUserList?");
return "userList";
}
@RequestMapping("/getUserById/{id}")
public String getUserById(@PathVariable Integer id,Model model) {
User user = userService.getById(id);
model.addAttribute("user",user);
return "userUpdate";
}
@RequestMapping("/updateUser")
public String updateUser(User user) {
userService.edit(user);
return "redirect:/UserController/getUserList";
}
@RequestMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable Integer id) {
//删除用户的同时,用户的书籍也当然要跟着全部删除
userService.removeUserAndBook(id);
return "redirect:/UserController/getUserList";
}
@RequestMapping("/addUser")
public String addUser(User user) {
userService.add(user);
return "redirect:/UserController/getUserList";
}
//根据作者id,查询作者的所有书籍
@RequestMapping("/getBookByUserId/{id}")
public String getBookByUserId(@PathVariable Integer id,Model model) {
User user = userService.getBookListByUserId(id);
model.addAttribute("user",user);
return "user_book";
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.