text stringlengths 10 2.72M |
|---|
package jp.noxi.collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
*
* @param <T> The class of objects to enumerate.
*/
public interface Enumerable<T> extends Iterable<T> {
/**
* Determines whether all elements of a sequence satisfy a condition.
*
* @param predicate A function to test each element for a condition.
*
* @return {@code true} if every element of the source sequence passes the test in the specified predicate, or if
* the sequence is empty; otherwise, {@code false}.
*/
boolean all(@Nonnull Predicate<T> predicate);
/**
* Determines whether a sequence contains any elements.
*
* @return {@code true} if the source sequence contains any elements; otherwise, {@code false}.
*/
boolean any();
/**
* Determines whether any element of a sequence satisfies a condition.
*
* @param predicate A function to test each element for a condition.
*
* @return {@code true} if any elements in the source sequence pass the test in the specified predicate; otherwise,
* {@code false}.
*/
boolean any(@Nonnull Predicate<T> predicate);
/**
* Computes the average of a sequence.
*
* @return The average of the sequence of values, or {@code null} if the source sequence is empty or contains only
* values that are {@code null}.
*/
@Nullable
Numeric average();
/**
* Computes the average of a sequence that are obtained by invoking a transform function on each element of the
* input sequence.
*
* @param selector A transform function to apply to each element.
*
* @return The average of the sequence of values, or {@code null} if the source sequence is empty or contains only
* values that are {@code null}.
*/
@Nullable
<TResult extends Number> Numeric average(@Nonnull Converter<T, TResult> selector);
/**
* Casts the elements of a {@link jp.noxi.collection.Enumerable} to the specified type.
*
* @param <TResult> The class to cast the elements of source to.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains each element of the source sequence cast to the
* specified type.
*/
@Nonnull
<TResult> Enumerable<TResult> cast(@Nonnull Class<TResult> castTarget);
/**
* Returns the number of elements in a sequence.
*
* @return The number of elements in the input sequence.
*/
@Nonnegative
int count();
/**
* Returns a number that represents how many elements in the specified sequence satisfy a condition.
*
* @param predicate A function to test each element for a condition.
*
* @return A number that represents how many elements in the sequence satisfy the condition in the predicate
* function.
*/
@Nonnegative
int count(@Nonnull Predicate<T> predicate);
/**
* Returns the first element of a sequence.
*
* @return The first element in the specified sequence.
*
* @throws java.lang.IllegalStateException The source sequence is empty.
*/
@Nullable
T first();
/**
* Returns the first element in a sequence that satisfies a specified condition.
*
* @param predicate A function to test each element for a condition.
*
* @return The first element in the sequence that passes the test in the specified predicate function.
*
* @throws java.lang.IllegalStateException No element satisfies the condition in predicate, or the source sequence
* is empty.
*/
@Nullable
T first(@Nonnull Predicate<T> predicate);
/**
* Returns the first element of a sequence, or a default value if the sequence contains no elements.
*
* @return {@code null} if source is empty; otherwise, the first element in source.
*/
@Nullable
T firstOrDefault();
/**
* Returns the first element of the sequence that satisfies a condition or a default value if no such element is
* found.
*
* @param predicate A function to test each element for a condition.
*
* @return {@code null} if source is empty or if no element passes the test specified by predicate; otherwise, the
* first element in source that passes the test specified by predicate.
*/
@Nullable
T firstOrDefault(@Nonnull Predicate<T> predicate);
/**
* Groups the elements of a sequence according to a specified key selector function.
*
* @param keySelector A function to extract the key for each element.
* @param <TKey> The class of the key returned by keySelector.
*
* @return An {@link jp.noxi.collection.Enumerable} where each {@link jp.noxi.collection.Grouping} object contains a
* sequence of objects and a key.
*/
@Nonnull
<TKey> Enumerable<Grouping<TKey, T>> groupBy(@Nonnull Converter<T, TKey> keySelector);
/**
* Groups the elements of a sequence according to a specified key selector function and compares the keys by using a
* specified comparator.
*
* @param keySelector A function to extract the key for each element.
* @param comparator A {@link java.util.Comparator} to compare keys.
* @param <TKey> The class of the key returned by keySelector.
*
* @return An {@link jp.noxi.collection.Enumerable} where each {@link jp.noxi.collection.Grouping} object contains a
* collection of objects and a key.
*/
@Nonnull
<TKey> Enumerable<Grouping<TKey, T>> groupBy(@Nonnull Converter<T, TKey> keySelector,
@Nonnull Comparator<TKey> comparator);
/**
* Groups the elements of a sequence according to a specified key selector function and projects the elements for
* each group by using a specified function.
*
* @param keySelector A function to extract the key for each element.
* @param elementSelector A function to map each source element to an element in the {@link
* jp.noxi.collection.Grouping}.
* @param <TKey> The class of the key returned by keySelector.
* @param <TElement> The class of the elements in the {@link jp.noxi.collection.Grouping}.
*
* @return An {@link jp.noxi.collection.Enumerable} where each {@link jp.noxi.collection.Grouping} object contains a
* collection of objects of type {@code TElement} and a key.
*/
@Nonnull
<TKey, TElement> Enumerable<Grouping<TKey, TElement>> groupBy(@Nonnull Converter<T, TKey> keySelector,
@Nonnull Converter<T, TElement> elementSelector);
/**
* Groups the elements of a sequence according to a key selector function. The keys are compared by using a
* comparator and each group's elements are projected by using a specified function.
*
* @param keySelector A function to extract the key for each element.
* @param elementSelector A function to map each source element to an element in an {@link
* jp.noxi.collection.Grouping}.
* @param comparator A {@link java.util.Comparator} to compare keys.
* @param <TKey> The class of the key returned by keySelector.
* @param <TElement> The class of the elements in the {@link jp.noxi.collection.Grouping}.
*
* @return An {@link jp.noxi.collection.Enumerable} where each {@link jp.noxi.collection.Grouping} object contains a
* collection of objects and a key.
*/
@Nonnull
<TKey, TElement> Enumerable<Grouping<TKey, TElement>> groupBy(@Nonnull Converter<T, TKey> keySelector,
@Nonnull Converter<T, TElement> elementSelector,
@Nonnull Comparator<TKey> comparator);
/**
* Filters the elements of an {@link jp.noxi.collection.Enumerable} based on a specified type.
*
* @param filter The class to filter the elements of the sequence on.
* @param <TResult> The class to filter the elements of the sequence on.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains elements from the input sequence of class {@code
* TResult}.
*/
@Nonnull
<TResult> Enumerable<TResult> instanceOf(@Nonnull Class<TResult> filter);
/**
* Produces the set intersection of two sequences by using the default equality comparable to compare values.
*
* @param second An {@link java.lang.Iterable} whose distinct elements that also appear in the first sequence will
* be returned.
*
* @return A sequence that contains the elements that form the set intersection of two sequences.
*/
@Nonnull
Enumerable<T> intersect(@Nonnull Iterable<T> second);
/**
* Produces the set intersection of two sequences by using the specified {@link java.util.Comparator} to compare
* values.
*
* @param second An {@link java.lang.Iterable} whose distinct elements that also appear in the first sequence
* will be returned.
* @param comparator A {@link java.util.Comparator} to compare values.
*
* @return A sequence that contains the elements that form the set intersection of two sequences.
*/
@Nonnull
Enumerable<T> intersect(@Nonnull Iterable<T> second, @Nonnull Comparator<T> comparator);
/**
* Returns the last element of a sequence.
*
* @return The value at the last position in the source sequence.
*
* @throws java.lang.IllegalStateException The source sequence is empty.
*/
@Nullable
T last();
/**
* Returns the last element of a sequence that satisfies a specified condition.
*
* @param predicate A function to test each element for a condition.
*
* @return The last element in the sequence that passes the test in the specified predicate function.
*
* @throws java.lang.IllegalStateException No element satisfies the condition in {@code predicate}, or the source
* sequence is empty.
*/
@Nullable
T last(@Nonnull Predicate<T> predicate);
/**
* Returns the last element of a sequence, or {@code null} if the sequence contains no elements.
*
* @return {@code null} if the source sequence is empty; otherwise, the last element in the {@link
* java.lang.Iterable}.
*/
@Nullable
T lastOrDefault();
/**
* Returns the last element of a sequence that satisfies a condition or {@code null} if no such element is found.
*
* @param predicate A function to test each element for a condition.
*
* @return {@code null} if the sequence is empty or if no elements pass the test in the predicate function;
* otherwise, the last element that passes the test in the predicate function.
*/
@Nullable
T lastOrDefault(@Nonnull Predicate<T> predicate);
/**
* Returns the maximum value in a sequence. If the source sequence is empty or contains only values that are {@code
* null}, this function returns {@code null}.
*
* @return The maximum value in the sequence.
*/
@Nullable
Numeric max();
/**
* Invokes a transform function on each element of a sequence and returns the maximum value.
*
* @param selector A transform function to apply to each element.
* @param <TResult> The class of the transformed elements.
*
* @return The maximum value in the sequence.
*/
@Nullable
<TResult extends Number> Numeric max(@Nonnull Converter<T, TResult> selector);
/**
* Returns the minimum value in a sequence. If the source sequence is empty or contains only values that are {@code
* null}, this function returns {@code null}.
*
* @return The minimum value in the sequence.
*/
@Nullable
Numeric min();
/**
* Invokes a transform function on each element of a sequence and returns the minimum value.
*
* @param selector A transform function to apply to each element.
* @param <TResult> The class of the transformed elements.
*
* @return The minimum value in the sequence.
*/
@Nullable
<TResult extends Number> Numeric min(@Nonnull Converter<T, TResult> selector);
/**
* Inverts the order of the elements in a sequence.
*
* @return A sequence whose elements correspond to those of the input sequence in reverse order.
*/
@Nonnull
Enumerable<T> reverse();
/**
* Projects each element of a sequence into a new form.
*
* @param selector A transform function to apply to each element.
* @param <TResult> The class of the value returned by selector.
*
* @return An {@link jp.noxi.collection.Enumerable} whose elements are the result of invoking the transform function
* on each element of source.
*/
@Nonnull
<TResult> Enumerable<TResult> select(@Nonnull Converter<T, TResult> selector);
/**
* Projects each element of a sequence into a new form by incorporating the element's index.
*
* @param selector A transform function to apply to each source element.
* @param <TResult> The class of the value returned by selector.
*
* @return An {@link jp.noxi.collection.Enumerable} whose elements are the result of invoking the transform function
* on each element of source.
*/
@Nonnull
<TResult> Enumerable<TResult> select(@Nonnull IndexConverter<T, TResult> selector);
/**
* Projects each element of a sequence to an {@link java.lang.Iterable} and flattens the resulting sequences into
* one sequence.
*
* @param selector A transform function to apply to each element.
* @param <TResult> The class of the elements of the sequence returned by selector.
*
* @return An {@link jp.noxi.collection.Enumerable} whose elements are the result of invoking the one-to-many
* transform function on each element of the input sequence.
*
* @throws java.lang.NullPointerException transformed sequence is {@code null}.
*/
@Nonnull
<TResult> Enumerable<TResult> selectMany(@Nonnull Converter<T, Iterable<TResult>> selector);
/**
* Projects each element of a sequence to an {@link java.lang.Iterable}, and flattens the resulting sequences into
* one sequence. The index of each source element is used in the projected form of that element.
*
* @param selector A transform function to apply to each source element.
* @param <TResult> The class of the elements of the sequence returned by selector.
*
* @return An {@link jp.noxi.collection.Enumerable} whose elements are the result of invoking the one-to-many
* transform function on each element of an input sequence.
*/
@Nonnull
<TResult> Enumerable<TResult> selectMany(@Nonnull IndexConverter<T, Iterable<TResult>> selector);
/**
* Returns the only element of a sequence, and throws an exception if there is not exactly one element in the
* sequence.
*
* @return The single element of the input sequence.
*
* @throws java.lang.IllegalStateException The input sequence contains more than one element, or the input sequence
* is empty.
*/
@Nullable
T single();
/**
* Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than
* one such element exists.
*
* @param predicate A function to test an element for a condition.
*
* @return The single element of the input sequence that satisfies a condition.
*
* @throws java.lang.IllegalStateException No element satisfies the condition in predicate, more than one element
* satisfies the condition in predicate, or the source sequence is empty.
*/
@Nullable
T single(@Nonnull Predicate<T> predicate);
/**
* Returns the only element of a sequence, or {@code null} if the sequence is empty; this method throws an exception
* if there is more than one element in the sequence.
*
* @return The single element of the input sequence, or {@code null} if the sequence contains no elements.
*
* @throws java.lang.IllegalStateException The input sequence contains more than one element.
*/
@Nullable
T singleOrDefault();
/**
* Returns the only element of a sequence that satisfies a specified condition or {@code null} if no such element
* exists; this method throws an exception if more than one element satisfies the condition.
*
* @param predicate A function to test an element for a condition.
*
* @return The single element of the input sequence that satisfies the condition, or {@code null} if no such element
* is found.
*/
@Nullable
T singleOrDefault(@Nonnull Predicate<T> predicate);
/**
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.
*
* @param count The number of elements to skip before returning the remaining elements.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the elements that occur after the specified index
* in the input sequence.
*/
@Nonnull
Enumerable<T> skip(@Nonnegative int count);
/**
* Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining
* elements.
*
* @param predicate A function to test each element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the elements from the input sequence starting at
* the first element in the linear series that does not pass the test specified by predicate.
*/
@Nonnull
Enumerable<T> skipWhile(@Nonnull Predicate<T> predicate);
/**
* Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* @param predicate A function to test each source element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the elements from the input sequence starting at
* the first element in the linear series that does not pass the test specified by predicate.
*/
@Nonnull
Enumerable<T> skipWhile(@Nonnull IndexPredicate<T> predicate);
/**
* Computes the sum of a sequence. This method returns zero if source contains no elements.
*
* @return The sum of the values in the sequence.
*
* @throws jp.noxi.collection.OverflowException
*/
@Nonnull
Numeric sum();
/**
* Computes the sum of the sequence that are obtained by invoking a transform function on each element of the input
* sequence. This method returns zero if source contains no elements.
*
* @param selector A transform function to apply to each element.
* @param <TResult> The class of the transformed elements.
*
* @return The sum of the projected values.
*
* @throws jp.noxi.collection.OverflowException
*/
@Nonnull
<TResult extends Number> Numeric sum(@Nonnull Converter<T, TResult> selector);
/**
* Returns a specified number of contiguous elements from the start of a sequence.
*
* @param count The number of elements to return.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the specified number of elements from the start of
* the input sequence.
*/
@Nonnull
Enumerable<T> take(@Nonnegative int count);
/**
* Returns elements from a sequence as long as a specified condition is {@code true}.
*
* @param predicate A function to test each source element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the elements from the input sequence that occur
* before the element at which the test no longer passes.
*/
@Nonnull
Enumerable<T> takeWhile(@Nonnull Predicate<T> predicate);
/**
* Returns elements from a sequence as long as a specified condition is {@code true}. The element's index is used in
* the logic of the predicate function.
*
* @param predicate A function to test each source element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains the specified number of elements from the start of
* the input sequence.
*/
@Nonnull
Enumerable<T> takeWhile(@Nonnull IndexPredicate<T> predicate);
/**
* Creates an array from an {@link jp.noxi.collection.Enumerable}
*
* @return An array that contains the elements from the input sequence.
*/
@Nonnull
Object[] toArray();
/**
* Creates an array from an {@link jp.noxi.collection.Enumerable}.
*
* @param clss The class of the elements of source.
*
* @return An array that contains the elements from the input sequence.
*/
@Nonnull
T[] toArray(@Nonnull Class<T> clss);
/**
* Creates a {@link java.util.List} from an {@link jp.noxi.collection.Enumerable}.
*
* @return A {@link java.util.List} that contains elements from the input sequence.
*/
@Nonnull
List<T> toList();
/**
* Creates a {@link jp.noxi.collection.Lookup} from an {@link jp.noxi.collection.Enumerable} according to a
* specified key selector function.
*
* @param keySelector A function to extract a key from each element.
* @param <TKey> The class of the key returned by keySelector.
*
* @return A {@link jp.noxi.collection.Lookup} that contains keys and values.
*/
@Nonnull
<TKey> Lookup<TKey, T> toLookup(@Nonnull Converter<T, TKey> keySelector);
/**
* Creates a {@link jp.noxi.collection.Lookup} from an {@link jp.noxi.collection.Enumerable} according to specified
* key selector and element selector functions.
*
* @param keySelector A function to extract a key from each element.
* @param elementSelector A transform function to produce a result element value from each element.
* @param <TKey> The class of the key returned by keySelector.
* @param <TElement> The class of the value returned by elementSelector.
*
* @return A {@link jp.noxi.collection.Lookup} that contains values of class {@code TElement} selected from the
* input sequence.
*/
@Nonnull
<TKey, TElement> Lookup<TKey, TElement> toLookup(@Nonnull Converter<T, TKey> keySelector,
@Nonnull Converter<T, TElement> elementSelector);
/**
* Creates a {@link java.util.Map} from an {@link jp.noxi.collection.Enumerable} according to a specified key
* selector function.
*
* @param keySelector A function to extract a key from each element.
* @param <TKey> The class of the key returned by keySelector.
*
* @return A {@link java.util.Map} that contains keys and values.
*
* @throws java.lang.IllegalArgumentException keySelector produces duplicate keys for two elements.
*/
@Nonnull
<TKey> Map<TKey, T> toMap(@Nonnull Converter<T, TKey> keySelector);
/**
* Creates a {@link java.util.Map} from an {@link jp.noxi.collection.Enumerable} according to specified key selector
* and element selector functions.
*
* @param keySelector A function to extract a key from each element.
* @param elementSelector A transform function to produce a result element value from each element.
* @param <TKey> The class of the key returned by keySelector.
* @param <TElement> The type of the value returned by elementSelector.
*
* @return A {@link java.util.Map} that contains values of type {@code TElement} selected from the input sequence.
*
* @throws java.lang.IllegalArgumentException keySelector produces duplicate keys for two elements.
*/
@Nonnull
<TKey, TElement> Map<TKey, TElement> toMap(@Nonnull Converter<T, TKey> keySelector,
@Nonnull Converter<T, TElement> elementSelector);
/**
* Filters a sequence of values based on a predicate.
*
* @param predicate A function to test each element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains elements from the input sequence that satisfy the
* condition.
*/
@Nonnull
Enumerable<T> where(@Nonnull Predicate<T> predicate);
/**
* Filters a sequence of values based on a predicate. Each element's index is used in the logic of the predicate
* function.
*
* @param predicate A function to test each element for a condition.
*
* @return An {@link jp.noxi.collection.Enumerable} that contains elements from the input sequence that satisfy the
* condition.
*/
@Nonnull
Enumerable<T> where(@Nonnull IndexPredicate<T> predicate);
/**
* Applies a specified function to the corresponding elements of two sequences, producing a sequence of the
* results.
*
* @param second The second sequence to merge.
* @param resultSelector A function that specifies how to merge the elements from the two sequences.
* @param <TSecond> The class of the elements of the second input sequence.
* @param <TResult> The class of the elements of the result sequence.
*
* @return An {@link java.lang.Iterable} that contains merged elements of two input sequences.
*/
@Nonnull
<TSecond, TResult> Enumerable<TResult> zip(@Nonnull Iterable<TSecond> second,
@Nonnull Merger<T, TSecond, TResult> resultSelector);
}
|
package com.bowlong.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.commons.collections4.list.FixedSizeList;
import org.apache.commons.collections4.list.TreeList;
import com.alibaba.fastjson.JSON;
import com.bowlong.Toolkit;
import com.bowlong.lang.NumEx;
import com.bowlong.lang.RndEx;
import com.bowlong.lang.StrEx;
import com.bowlong.objpool.StringBufPool;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ListEx {
// private static Random rnd;
// static {
// rnd = new Random(System.currentTimeMillis());
// }
public static final List singletonEmptyList = new ArrayList();
public static final List singletonEmptyList() {
return singletonEmptyList;
}
public static final ListBuilder builder() {
return ListBuilder.builder();
}
public static final ListBuilder builder(List list) {
return ListBuilder.builder(list);
}
public static final List newList() {
return Collections.synchronizedList(new ArrayList());
}
public static final <T> List<T> newListT() {
return Collections.synchronizedList(new ArrayList<T>());
}
public static final List newArrayList() {
return new ArrayList();
}
public static final List newLinkedList() {
return new LinkedList();
}
public static final List newVector() {
return new Vector();
}
public static final TreeList newTreeList() {
return new TreeList();
}
public static final FixedSizeList newFixedSizeList(List<?> list) {
return FixedSizeList.fixedSizeList(list);
}
public static final <T> T get(List list, int index) {
return (T) list.get(index);
}
public static final <T> T getFirst(List list) {
if (isEmpty(list))
return null;
return (T) list.get(0);
}
/*** 分隔符,英文逗号(,) **/
static public final List<String> toListByComma(String s, boolean isTrim) {
return toListByDelimiter(s, ",", isTrim);
}
/*** 分隔符 **/
static public final List<String> toListByDelimiter(String s,
String delimiter, boolean isTrim) {
if (StrEx.isEmpty(delimiter))
delimiter = ",";
List<String> result = newListT();
StringTokenizer st = new StringTokenizer(s, delimiter);
while (st.hasMoreTokens()) {
String str = st.nextToken();
if (StrEx.isEmpty(str))
continue;
if (isTrim)
str = str.trim();
result.add(str);
}
return result;
}
public static final List<Integer> toListInt(String s) {
List<Integer> ret = newListT();
List<String> listStr = toListByComma(s, true);
if (isEmpty(listStr))
return ret;
int len = listStr.size();
for (int i = 0; i < len; i++) {
int e = NumEx.stringToInt(listStr.get(i));
ret.add(e);
}
return ret;
}
/*** [12,12,"dfg",\"adsfasd\"] **/
public static final <T> List<T> toListByJson(String s, Class<T> clazz) {
List<T> result = null;
try {
s = s.replaceAll("\\\\", "");
result = JSON.parseArray(s, clazz);
} catch (Exception e) {
result = newListT();
}
return result;
}
public static final List toListByLine(String s) {
List l = new Vector();
StringReader sr = new StringReader(s);
BufferedReader br = new BufferedReader(sr);
try {
while (true) {
String v = br.readLine();
if (v == null)
break;
l.add(v);
}
} catch (IOException e) {
e.printStackTrace();
}
return l;
}
public static final <T> List<T> toList(Set<T> m) {
List<T> ret = newListT();
if (m == null)
return ret;
ret.addAll(m);
return ret;
}
public static final List<Integer> toList(int[] array) {
List ret = newList();
if (array == null)
return ret;
for (int v : array) {
ret.add(v);
}
return ret;
}
public static final List<String> toList(String[] array) {
List ret = newList();
if (array == null)
return ret;
for (String v : array) {
ret.add(v);
}
return ret;
}
public static final int[] toIntArray(List<Integer> list) {
if (list == null || list.isEmpty())
return new int[0];
int count = list.size();
int[] result = new int[count];
for (int i = 0; i < count; i++) {
Integer v = list.get(i);
if (v == null)
result[i] = 0;
result[i] = v.intValue();
}
return result;
}
public static final int[] toIntArray(int... args) {
return args;
}
public static final String[] toStrArray(List<String> list) {
if (list == null || list.isEmpty())
return new String[0];
int count = list.size();
String[] result = new String[count];
for (int i = 0; i < count; i++) {
String v = list.get(i);
if (v == null)
result[i] = "";
result[i] = v;
}
return result;
}
public static final List toArrayList(List list) {
List ret = newArrayList();
if (list == null)
return ret;
for (Object e : list) {
ret.add(e);
}
return ret;
}
public static final List toLinkedList(List list) {
List ret = newLinkedList();
if (list == null)
return ret;
for (Object e : list) {
ret.add(e);
}
return ret;
}
public static final List toVector(List list) {
List ret = newVector();
if (list == null)
return ret;
for (Object e : list) {
ret.add(e);
}
return ret;
}
public static final List toArrayList(Object[] array) {
List list = newArrayList();
if (array == null)
return list;
for (Object e : array)
list.add(e);
return list;
}
public static final List toLinkedList(Object[] array) {
List list = newLinkedList();
if (array == null)
return list;
for (Object e : array)
list.add(e);
return list;
}
public static final <K, V> List<K> keyToList(Map<K, V> map) {
List<K> list = newListT();
if (map == null)
return list;
list.addAll(map.keySet());
return list;
}
public static final <K, V> List<V> valueToList(Map<K, V> map) {
List<V> list = newListT();
if (map == null)
return list;
list.addAll(map.values());
return list;
}
public static final List toVector(Object[] array) {
List list = newVector();
if (array == null)
return list;
for (Object e : array)
list.add(e);
return list;
}
/*** 转为数组对象 **/
static public final <T> T[] toArrs(List<T> list){
if(isEmpty(list))
return null;
return (T[])list.toArray();
}
public static final List listIt(Object... var) {
List result = new Vector();
return add(result, var);
}
public static final List asList(Object... args) {
return Arrays.asList(args);
}
public static final List add(List list, Object... objs) {
for (Object e : objs) {
list.add(e);
}
return list;
}
public static final boolean isEmpty(List l) {
return (l == null || l.isEmpty());
}
public static final boolean isEmpty(Set s) {
return (s == null || s.isEmpty());
}
public static final boolean isEmpty(Object... objs) {
return (objs == null || objs.length <= 0);
}
public static final boolean isEmpty(String... stres) {
return (stres == null || stres.length <= 0);
}
static public final boolean isEmpty(byte[]... bts) {
return (bts == null || bts.length <= 0);
}
public static final boolean notEmpty(List l) {
return (l != null && !l.isEmpty());
}
static public final void clear(List ls) {
if (ls == null)
return;
ls.clear();
}
static public final void clearNull(List ls) {
if (ls == null)
return;
ls.clear();
ls = null;
}
/*** 清空并创建对象 **/
static public final List clear4List(List ls) {
if (ls == null) {
ls = newArrayList();
return ls;
}
ls.clear();
return ls;
}
static public final boolean have(List list, Object obj) {
if (isEmpty(list) || obj == null)
return false;
return list.contains(obj);
}
public static final boolean haveInt(int[] array, int v) {
for (int i : array) {
if (v == i)
return true;
}
return false;
}
public static final boolean haveInt(List vars, int i) {
return have(vars, i);
}
public static final boolean haveInt(Set<Integer> sets, int[] array) {
for (int i : array) {
if (sets.contains(i))
return true;
}
return false;
}
public static final boolean haveInt(int[] array, Set<Integer> sets) {
Iterator<Integer> it = sets.iterator();
while (it.hasNext()) {
int i = it.next();
if (haveInt(array, i))
return true;
}
return false;
}
public static final int max(List<Integer> list) {
return Collections.max(list);
}
public static final int min(List<Integer> list) {
return Collections.min(list);
}
// 是否有交集
public static final boolean isDisjoint(List l1, List l2) {
return Collections.disjoint(l1, l2);
}
/*** 求交集∩ **/
public static final List intersected(List l1, List l2) {
List result = newList();
result.addAll(l1);
result.retainAll(l2);
return result;
}
/*** 求交集∩,泛型T **/
public static final <T> List<T> intersectedT(List<T> l1, List<T> l2) {
List<T> result = newListT();
result.addAll(l1);
result.retainAll(l2);
return result;
}
// 拷贝
public static final List copy(List src) {
if (isEmpty(src))
return null;
List dest = newVector();
Collections.copy(dest, src);
return dest;
}
// 反转
public static final List reverse(List src) {
Collections.reverse(src);
return src;
}
// 旋转
public static final List rotate(List src, int distance) {
Collections.rotate(src, distance);
return src;
}
// 对List进行打乱顺序
public static final List shuffle(List src) {
Collections.shuffle(src);
return src;
}
// 对List进行打乱顺序
public static final List shuffleRnd(List src) {
// Collections.shuffle(src, new Random(System.currentTimeMillis()));
Collections.shuffle(src, new Random(RndEx.randomNum()));
return src;
}
static public final List rndList(List src) {
return RndEx.rndList(src);
}
static public final <T> List<T> rndListT(List<T> src) {
return RndEx.rndListT(src);
}
static public final List subRndList(List src, int subsize) {
return RndEx.subRndList(src, subsize);
}
static public final <T> List<T> subRndListT(List<T> src, int subsize) {
return RndEx.subRndListT(src, subsize);
}
public static final List sort(List src) {
Collections.sort(src);
return src;
}
public static final List<Map> sort(final List m1, final String key) {
Collections.sort(m1, new Comparator<Map>() {
public int compare(Map o1, Map o2) {
try {
Object v1 = o1.get(key);
Object v2 = o2.get(key);
if (v1 == null || v2 == null)
return 0;
return compareTo(v1, v2);
} catch (Exception e) {
return 0;
}
}
});
return m1;
}
public static final int compareTo(Object v1, Object v2) {
return Toolkit.compareTo(v1, v2);
}
public static final List swap(List list, int i, int j) {
Collections.swap(list, i, j);
return list;
}
public static final List sort2(List src, Comparator comparator) {
Collections.sort(src, comparator);
return src;
}
public static final List<Map> sortIntMap(List<Map> m1, final Object key) {
Collections.sort(m1, new Comparator<Map>() {
public int compare(Map o1, Map o2) {
int i1 = (Integer) o1.get(key);
int i2 = (Integer) o2.get(key);
return i1 - i2;
}
});
return m1;
}
public static final List<Map> sortLongMap(List<Map> m1, final Object key) {
Collections.sort(m1, new Comparator<Map>() {
public int compare(Map o1, Map o2) {
long i1 = (Long) o1.get(key);
long i2 = (Long) o2.get(key);
return i1 > i2 ? 1 : -1;
}
});
return m1;
}
public static final List<Byte> distinctByte(List<Byte> vars) {
List<Byte> ret = new Vector<Byte>();
Map<Byte, Byte> mvars = new Hashtable<Byte, Byte>();
for (Byte v : vars) {
mvars.put(v, v);
}
ret.addAll(mvars.values());
return ret;
}
public static final List<Short> distinctShort(List<Short> vars) {
List<Short> ret = new Vector<Short>();
Map<Short, Short> mvars = new Hashtable<Short, Short>();
for (Short v : vars) {
mvars.put(v, v);
}
ret.addAll(mvars.values());
return ret;
}
public static final List<Integer> distinctInteger(List<Integer> vars) {
List<Integer> ret = new Vector<Integer>();
Map<Integer, Integer> mvars = new Hashtable<Integer, Integer>();
for (Integer v : vars) {
mvars.put(v, v);
}
ret.addAll(mvars.values());
return ret;
}
public static final List<Long> distinctLong(List<Long> vars) {
List<Long> ret = new Vector<Long>();
Map<Long, Long> mvars = new Hashtable<Long, Long>();
for (Long v : vars) {
mvars.put(v, v);
}
ret.addAll(mvars.values());
return ret;
}
public static final List<String> distinctString(List<String> vars) {
List<String> ret = new Vector<String>();
Map<String, String> mvars = new Hashtable<String, String>();
for (String v : vars) {
mvars.put(v, v);
}
ret.addAll(mvars.values());
return ret;
}
public static final String formatString(List l) {
int depth = 1;
return formatString(l, depth);
}
public static final String formatString(List l, int depth) {
int p = 0;
int size = l.size();
StringBuffer sb = StringBufPool.borrowObject();
try {
sb.append("[\n");
for (Object v : l) {
for (int i = 0; i < depth; i++)
sb.append(" ");
if (v instanceof List) {
sb.append(ListEx.formatString((List) v, depth + 1));
} else if (v instanceof Map) {
sb.append(MapEx.formatString((Map) v, depth + 1));
} else if (v instanceof String) {
sb.append("\"").append(v).append("\"");
} else {
sb.append(v);
}
p++;
if (p < size) {
sb.append(",");
}
sb.append("\n");
}
for (int i = 1; i < depth; i++)
sb.append(" ");
sb.append("]");
return sb.toString();
} finally {
StringBufPool.returnObject(sb);
}
}
static public final int pageCount(int count, int pageSize) {
if (pageSize < 0)
return 0;
int pageCount = count / pageSize;
pageCount = count == pageCount * pageSize ? pageCount : pageCount + 1;
return pageCount;
}
static public final long pageCount(long count, long pageSize) {
if (pageSize < 0)
return 0l;
long pageCount = count / pageSize;
pageCount = count == pageCount * pageSize ? pageCount : pageCount + 1;
return pageCount;
}
static public final <T> List<T> getPageT(List<T> v, int page, int pageSize) {
List pgList = getPage(v, page, pageSize);
if (isEmpty(pgList))
return new ArrayList<T>();
return (List<T>) pgList;
}
static public final List getPage(List v, int page, int pageSize) {
if (isEmpty(v))
return new ArrayList();
int count = v.size();
int pageCount = pageCount(count, pageSize);
page--;
page = page < 0 ? 0 : page;
page = page >= pageCount ? pageCount - 1 : page;
int begin = (int) (page * pageSize);
int end = (int) (begin + pageSize);
if (begin > count || begin < 0 || end < 0)
return new ArrayList();
end = count < end ? count : end;
if (end <= begin)
return new ArrayList();
return v.subList(begin, end);
}
// //////////////// 过滤 ////////////////
/*** 过滤origin中包含filter里面的元素 **/
static public final <T> List fitlerList(List<T> origin, List<T> filter) {
if (isEmpty(origin)) {
return newListT();
}
if (isEmpty(filter)) {
return origin;
}
List<T> ret = newListT();
int lens = origin.size();
for (int i = 0; i < lens; i++) {
T t = origin.get(i);
if (t == null) {
continue;
}
boolean isFilter = have(filter, t);
if (isFilter) {
continue;
}
ret.add(t);
}
return ret;
}
/*** 过滤origin中包含filter的元素 **/
static public final <T> List fitlerList(List<T> origin, T filter) {
if (isEmpty(origin)) {
return newListT();
}
if (filter == null) {
return origin;
}
List<T> ret = newListT();
int lens = origin.size();
for (int i = 0; i < lens; i++) {
T t = origin.get(i);
if (t == null) {
continue;
}
if (t == filter) {
continue;
}
ret.add(t);
}
return ret;
}
// ==========set
static public final Set newSet() {
return Collections.synchronizedSet(new HashSet());
}
static public final <T> Set<T> newSetT() {
return Collections.synchronizedSet(new HashSet<T>());
}
// //////////////////////////////////////////////////
public static void main(String[] args) {
}
}
|
/**
*Author Fys
*
*Time 2016-7-5-下午4:02:23
**/
package com.goldgov.dygl.module.partyMemberDuty.partyevaluatedata.service;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.module.partyMemberDuty.duty.domain.Duty;
import com.goldgov.dygl.module.partyMemberDuty.duty.service.IDutyService;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.IQualitativeConditionsService;
import com.goldgov.dygl.module.partyMemberDuty.partyevaluatedata.dao.IEvaluateDataDao;
import com.goldgov.dygl.module.partyMemberDuty.partyevaluatedata.domain.EvaluateData;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partymember.service.IPartyMemberService_AA;
import com.goldgov.dygl.module.partymember.service.PartyMemberEvaluateScoreBean;
import com.goldgov.dygl.module.partymemberrated.indexmodule.IndexModuleFactory;
import com.goldgov.dygl.module.partymemberrated.indexmodule.service.IIndexModuleService;
import com.goldgov.dygl.module.partymemberrated.rated.services.IPartyMemberRatedService;
import com.goldgov.dygl.module.partymemberrated.rated.services.PartyMemberRated;
import com.goldgov.dygl.module.partyorganization.service.IPartyOrganizationPortalService;
import com.goldgov.gtiles.module.transactionscheduling.service.TransacationSchLogService;
import com.goldgov.gtiles.module.transactionscheduling.service.TransactionSchLog;
import com.goldgov.gtiles.module.transactionscheduling.service.TransactionSchLog.ExcType;
import com.goldgov.gtiles.utils.SpringBeanUtils;
@Service("scheduleCalculateEvaluateData")
public class ScheduleCalculateEvaluateData implements IScheduleCalculateEvaluateData{
@Autowired
@Qualifier("partyMemberRatedService")
private IPartyMemberRatedService partyMemberRatedService;//党员评价接口
@Autowired
@Qualifier("IndexModuleServiceImpl")
private IIndexModuleService indexModuleService;
@Autowired
@Qualifier("dutyServiceImpl")
private IDutyService dutyService;
@Autowired
@Qualifier("iEvaluateDataDao")
private IEvaluateDataDao evaluateDataDao;
@Autowired
@Qualifier("partyOrganizationPortalServiceImpl")
private IPartyOrganizationPortalService partyOrganizationPortalServiceImpl;//学习积分
@Autowired
@Qualifier("qualitativeconditionsServiceImpl")
private IQualitativeConditionsService qualitativeconditionsService;
@Autowired
@Qualifier("partyMemberService_AA")
private IPartyMemberService_AA partyMemberService;
@Autowired
@Qualifier("TransacationSchLogService")
private TransacationSchLogService transacationSchLogService;
// 每天凌晨一点执行
@Scheduled(cron="0 0 1 * * ? ")
public void calculateEvaluateData() throws Exception{
String jobName="calculateEvaluateData党员评价数据同步";
TransactionSchLog ts = transacationSchLogService.updateInfobyStatu(jobName, ExcType.HOUR, 24);
if(ts!=null){//乐观锁锁定调度成功
String errMsg=null;
try {
/*取当前时间的前一天,查询是否有以这个时间结束的评价,如果有,则计算分值,
* 防止因评价发布过于紧凑,而忽略了上一个评价最后一天的得分 */
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//String date = "2016-06-01";
Date nowDate = new Date(); //当前时间
//Date nowDate = sdf.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(nowDate);
c.add(Calendar.DAY_OF_MONTH, -1);//获取当前时间前一天
String previousDay = sdf.format(c.getTime());
PartyMemberRated rated = partyMemberRatedService.getRateByEndTime(previousDay);
PartyMemberRated latestRate = partyMemberRatedService.getTheLatestPublishedRatedId();//获取最新一次的评价
List<PartyMemberRated> unPublishRateList = partyMemberRatedService.getUnPublishedRateList();//未发布的评价
if(rated!=null){
saveOrUpateInfoByRate(rated);//计算上一次的分值
if(!latestRate.getRatedId().equals(rated.getRatedId())){//最新一次的评价和以昨天为结束日期的评价不是同一个评价 ,则计算最新一次的评价,否则,不再计算最新评价
saveOrUpateInfoByRate(latestRate);//计算最新一次评价的分值
}
}else{//无前一天结束的评价 则只需要计算最新一次的评价分值
if(latestRate!=null){
saveOrUpateInfoByRate(latestRate);//计算最新一次评价的分值
}
}
if(unPublishRateList!=null && unPublishRateList.size()>0){
for(PartyMemberRated rate : unPublishRateList){
saveOrUpateInfoByRate(rate);
}
}
} catch (Exception e) {
e.printStackTrace();
errMsg=jobName+e.getMessage();
}finally{
//保存结束时间 及异常信息
ts.setEndDate(new Date());
ts.setStatu(errMsg==null?TransactionSchLog.JOB_EXEC_END:TransactionSchLog.JOB_EXEC_ERR);//TransactionSchLog.JOB_EXEC_ERR
ts.setExceptionStack(errMsg);
transacationSchLogService.updateInfo(ts);
}
}
}
/**
* 根据党员评价 计算该周期内每个党员的各项分值 存入静态表或修改静态表数据
* @param rated
*/
public void saveOrUpateInfoByRate(PartyMemberRated rated) throws Exception{
Calendar c = Calendar.getInstance();
c.setTime(rated.getRatedTimeEnd());
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
Map<String,EvaluateData> dataMap = new HashMap<String,EvaluateData>();
List<EvaluateData> evaluateDateList = evaluateDataDao.getEvaluateDataListByEvaluateId(rated.getRatedId());//当前评价下党员评价数据列表
if(evaluateDateList!=null && evaluateDateList.size()>0){
for(EvaluateData data:evaluateDateList){
dataMap.put(data.getLoginId(), data);
}
}
List<String> loginIdList = evaluateDataDao.getAllActiveLoginId();
/*List<EvaluateData> prepareUpdateList = new ArrayList<EvaluateData>();
List<EvaluateData> prepareInsertList = new ArrayList<EvaluateData>();*/
Integer poolSize=10;
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(poolSize);
ScheduleCalculateEvaluateData dataService = SpringBeanUtils.getBean("scheduleCalculateEvaluateData");
for(String loginId:loginIdList){
newFixedThreadPool.execute(new EvaluateScoreThread(rated, loginId, year, month,dataMap,dataService,evaluateDataDao));
/*EvaluateData newData = new EvaluateData();
newData.setEvaluateId(rated.getRatedId());
newData.setLoginId(loginId);
newData.setEvaluateYear(year);
newData.setEvaluateMonth(month);
buildEvaluateData(newData,rated,loginId);//构造当前党员的评价数据
if(dataMap.get(loginId)!=null){//当前党员评价下本党员在党员评价静态数据表中有数据 则对比两条数据的得分及违法行为,判断是新增或者是修改
EvaluateData oldData = dataMap.get(loginId);
if(compareValue(oldData.getRequiredPlaylength(),newData.getRequiredPlaylength()) //必修课时长
&&compareValue(oldData.getElectivePlaylength(),newData.getElectivePlaylength()) //选修课时长
&&compareValue(oldData.getExamScore(),newData.getExamScore()) //考试分数
&&compareValue(oldData.getStudyTotalScore(),newData.getStudyTotalScore()) //学习总得分
&&compareValue(oldData.getActivityJoinTimes(),newData.getActivityJoinTimes()) //组织活动参加次数
&&compareValue(oldData.getActivityShouldJoinTimes(),newData.getActivityShouldJoinTimes()) //组织活动应参加次数
&&compareValue(oldData.getActivityScore(),newData.getActivityScore()) //组织活动得分
&&compareValue(oldData.getPerformDutyScore(),newData.getPerformDutyScore()) //履职履责得分
&&compareValue(oldData.getAchievementScore(),newData.getAchievementScore()) //绩效得分
&&compareValue(oldData.getTotalScore(), newData.getTotalScore()) //总得分
&&compareValue(oldData.getConductPartyBehavior(), newData.getConductPartyBehavior()) //违反党员行为规范
&&compareValue(oldData.getWarningBehavior(), newData.getWarningBehavior()) //警示行为
&&compareValue(oldData.getStudyScoreState(), newData.getStudyScoreState()) //学习得分合格状态
&&compareValue(oldData.getActivityScoreState(), newData.getActivityScoreState()) //组织活动得分状态
&&compareValue(oldData.getDutyScoreState(), newData.getDutyScoreState()) //履职履责得分状态
&&compareValue(oldData.getTotalScoreState(), newData.getTotalScoreState()) //总得分状态
){
continue;
}else{//有分值或状态不相等 更新
newData.setDataId(oldData.getDataId());
evaluateDataDao.updateEvaluateData(newData);
}
}else{
evaluateDataDao.addEvaluateData(newData);
}*/
}
}
public void buildEvaluateData(EvaluateData newData, PartyMemberRated rated, String loginId) throws Exception{
String dutyId=dutyService.getPerformDuty(loginId, rated.getRatedId());
newData.setDutyId(dutyId);
buildBehavior(newData,dutyId,loginId);
buildScore(newData,rated,loginId);
}
/**
* 构造党员20项违反党员行为 68项警示行为
* @param newData
* @param dutyId
* @param userId
* @throws Exception
*/
public void buildBehavior(EvaluateData newData,String dutyId,String userId) throws Exception{
Integer dutyNum = getDutyNum(dutyId,userId);
List<Map<String,Object>> list=qualitativeconditionsService.findDXlist(userId,dutyId,null,dutyNum);
// List<Map<String,Object>> list=qualitativeconditionsService.findDXlist("10000151","0820CD7AE16731F65CB2B843F732A5DE" ,null);
int wf=0;
int wfsize=0;
int js=0;
int jssize=0;
String wfIds="";
String jsIds="";
String wfIdsbl="";
String jsIdsbl="";
boolean isWFyellow = false;
for(Map<String,Object> map:list){
if((map.get("ctype")+"").equals("1")){
wf++;
if(!(map.get("bl")+"").equals("0")){
wfsize++;
wfIds+=(wfIds.length()>0?"@@SPLIT@@":"")+map.get("cid");
wfIdsbl+=(wfIdsbl.length()>0?"@@SPLIT@@":"")+map.get("bl");
float wfbl = Float.valueOf(map.get("bl").toString());
if(wfbl>=0.3f){
isWFyellow = true;
}
}
}else {
js++;
if(!(map.get("bl")+"").equals("0")){
jssize++;
jsIds+=(wfIds.length()>0?"@@SPLIT@@":"")+map.get("cid");
jsIdsbl+=(jsIdsbl.length()>0?"@@SPLIT@@":"")+map.get("bl");
}
}
}
newData.setAchievementScore(Float.valueOf(list.get(0).get("achievementsScore")+"")); //设置绩效分值
newData.setConductPartyBehavior(wfIds);//设置违反党员行为规范
newData.setConductTimes(wfsize);
newData.setPartyBehaviorTimes(wf);
newData.setConductScale(wfIdsbl);
newData.setWarningBehavior(jsIds);//设置警示行为
newData.setAgainstWarningTimes(jssize);
newData.setWarningBehaviorTimes(js);
newData.setWarningScale(jsIdsbl);
if(isWFyellow){
newData.setDutyScoreState(EvaluateData.SCORE_STATE_YELLOW);
}else{
newData.setDutyScoreState(EvaluateData.SCORE_STATE_GREEN);
}
}
/**
* 构造各项分值及合格状态
* @param newData
* @param rated
* @param userId
*/
public void buildScore(EvaluateData newData,PartyMemberRated rated,String userId){
String ratedId = rated.getRatedId();
//自由学习
//必修课学习时长
Integer requiredStudyLength = (Integer)indexModuleService.executeModuleMethod(IndexModuleFactory.INDEX_STUDY_REQUIRED, userId, ratedId);
newData.setRequiredPlaylength(requiredStudyLength.longValue());//设置必修课时长
//选修课学习时长
Integer electiveStudyLength = (Integer)indexModuleService.executeModuleMethod(IndexModuleFactory.INDEX_STUDY_ELECTIVE, userId, ratedId);
newData.setElectivePlaylength(electiveStudyLength.longValue());//设置选修课时长
//自由学习得分 25*60%必修课 25*20%选修课 25*20%考试
Integer requiredLength = 200;//必修课要求时长 需查询
Integer electiveLength = 60;//选修课要求时长 需查询
DecimalFormat df = new DecimalFormat("0.00");//
float requiredRate = ((float)requiredStudyLength/60000)/requiredLength;//必修课完成比例
float electiveRate = ((float)electiveStudyLength/60000)/electiveLength;//选修课完成比例
requiredRate = requiredRate>1?1:requiredRate;
electiveRate = electiveRate>1?1:electiveRate;
newData.setExamScore(5f);//设置考试得分 2016-07-06 目前考试是送5分
float learnScoref = (float) (requiredRate*25*0.6+electiveRate*25*0.2+25*0.2);
float totalLearnScore = 25f;//自由学习总分 是否需要查询 2016-06-16
//学习得分状态 大于或者小于总学习得分的60% 则达标
Integer learnState =
learnScoref>=(totalLearnScore*0.6)?PartyMemberEvaluateScoreBean.SCORE_STATE_PASS:PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
newData.setStudyScoreState(learnState);//设置学习得分状态
String learnScore = df.format(learnScoref);//自由学习得分
newData.setStudyTotalScore(Float.valueOf(learnScore));//设置学习总分
//组织生活
float orglifeRate = 0f;//组织生活实际参加比例
Integer shouldTimes = partyOrganizationPortalServiceImpl.getPartyMemberOrganizationLifeJoinCount(userId, ratedId,1);//应参加次数
Integer actualTimes = partyOrganizationPortalServiceImpl.getPartyMemberOrganizationLifeJoinCount(userId, ratedId,2);//实际参加次数
newData.setActivityShouldJoinTimes(shouldTimes);//设置组织活动应参加次数
newData.setActivityJoinTimes(actualTimes);//设置组织活动实际参加次数
if(shouldTimes==null || shouldTimes==0){
orglifeRate = 1f;
}else{
orglifeRate = (float)actualTimes/shouldTimes;
}
float orglifeScoref = orglifeRate*25;
float totalOrglifeScore = 25f;//组织生活总分 是否需要查询 2016-06-16
//组织得分状态 大于或者小于总得分的60% 则达标
Integer orgLifeState =
orglifeScoref>=(totalOrglifeScore*0.6)?PartyMemberEvaluateScoreBean.SCORE_STATE_PASS:PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
newData.setActivityScoreState(orgLifeState);//设置组织活动得分状态
String orglifeScore = df.format(orglifeScoref);//组织生活得分
newData.setActivityScore(Float.valueOf(orglifeScore));//设置组织活动得分
//履职履则
float totalLZLZScore = (Float) indexModuleService.executeModuleMethod(IndexModuleFactory.INDEX_PERFORM_DUTY, userId, ratedId);//履职履则总分
totalLZLZScore = totalLZLZScore>100?100f:totalLZLZScore;
float lzlzScoref = totalLZLZScore*50/100;
float lzlzAllScore = 50f;//履职履则总分 是否需要查询 2016-06-16
//履职履则达标分两种情况 1:得分达到满分60% 2:党员的20项标准里,被评价不符合标准的比例小于10% 两种情况下、任意一种不达标,则视为不达标
Integer lzlzState =
lzlzScoref>=(lzlzAllScore*0.6)?PartyMemberEvaluateScoreBean.SCORE_STATE_PASS:PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
if(lzlzState==PartyMemberEvaluateScoreBean.SCORE_STATE_PASS){//得分达到满分60% 判断20项标准的评价情况
if(newData.getDutyScoreState().equals(PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS)){
lzlzState = PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
}
}
newData.setDutyScoreState(lzlzState);//设置履职履责得分状态
String lzlzScore = df.format(lzlzScoref);//履职履则得分
newData.setPerformDutyScore(Float.valueOf(lzlzScore));//设置履职履责得分
//奖惩得分
float rewardPunishScore = (Float) indexModuleService.executeModuleMethod(IndexModuleFactory.INDEX_AWARD_PUNISH, userId, ratedId);//党员奖惩
Integer rewardPunishScoreState = rewardPunishScore>=0f?PartyMemberEvaluateScoreBean.SCORE_STATE_PASS:PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
newData.setRewardPunishScore(rewardPunishScore);
newData.setRewardPunishScoreState(rewardPunishScoreState);
//总分
//当以上四条都达标时 则总分达标
Integer totalState = PartyMemberEvaluateScoreBean.SCORE_STATE_NOTPASS;
if(learnState==orgLifeState && learnState==lzlzState && learnState==PartyMemberEvaluateScoreBean.SCORE_STATE_PASS && rewardPunishScoreState==PartyMemberEvaluateScoreBean.SCORE_STATE_PASS){
totalState = PartyMemberEvaluateScoreBean.SCORE_STATE_PASS;
}
newData.setTotalScoreState(totalState);//设置总得分状态
String totalScore = df.format(learnScoref+orglifeScoref+lzlzScoref+rewardPunishScore);//总分
newData.setTotalScore(Float.valueOf(totalScore));//设置总得分
}
private Integer getDutyNum(String dutyID,String loginID) throws NoAuthorizedFieldException{
if(dutyID != null && !"".equals(dutyID)){
Duty dp = dutyService.findInfoById(dutyID);
if(dp!=null){
if(dp.getHpfw()==1){
return dp.getDutyMemberid().split(",").length;
}else{
String belongOrgID = "";
//AuthorizedDetails details = (AuthorizedDetails)UserHolder.getUserDetails();
List<String> groupIDs = partyMemberService.findUserGroupID(loginID);
String groupID = "";
if(groupIDs != null && groupIDs.size() > 0){
groupID = groupIDs.get(0);
}
if(groupID != null && !"".equals(groupID)){
belongOrgID = groupID;
}else{
//PartyOrganization currentPartyOrg = (PartyOrganization)details.getCustomDetails(ShConstant.CURRENT_PARTY_ORGANZATION);
belongOrgID = partyMemberService.getOrgIdByloginId(loginID);
}
List<String> userIDList = partyMemberService.findUserIDByPoAaID(belongOrgID);
if(dp != null){
String[] userIds = dp.getDutyMemberid().split(",");
List<String> userIDArr = new ArrayList<String>();
for(String userID : userIds){
if(userIDList.contains(userID)){
userIDArr.add(userID);
}
}
return userIDArr.size();
}
}
}
}
return 0;
}
}
|
/*
* Copyright 2019 Adrian Reimer
*
* 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.mygdx.music;
import com.badlogic.gdx.audio.Sound;
import com.mygdx.enums.Sounds;
/**
* Handles the Sound Effects (short sounds/non music related)
* @author Adrian Reimer
*
*/
public class SoundEffect{
private static final float SWORD_SWING_BASE_VOLUME = 0.2f;
private static final float GOLD_BASE_VOLUME = 0.15f;
private static final float BOTTLE_BASE_VOLUME = 0.1f;
private float soundEffectMaster;
private Sound swordSwing;
private Sound gold;
private Sound bottle;
/**
* SoundEffect constructor.
* @param soundInterface | {@link SoundInterface}.
*/
public SoundEffect(final SoundInterface soundInterface) {
soundEffectMaster = 1f;
swordSwing = soundInterface.getSound(Sounds.SWORD_SWING);
gold = soundInterface.getSound(Sounds.GOLD);
bottle = soundInterface.getSound(Sounds.BOTTLE);
}
public void setSoundEffectMaster(float soundEffectMaster) {
this.soundEffectMaster = soundEffectMaster;
}
public float getSoundEffectMaster() {
return soundEffectMaster;
}
/**
* plays the sword swing sound.
*/
public void playSwordSwing () {
swordSwing.play(SWORD_SWING_BASE_VOLUME * soundEffectMaster);
}
/**
* plays the gold collect sound.
*/
public void playGold () {
gold.play(GOLD_BASE_VOLUME * soundEffectMaster);
}
/**
* plays the bottle drink sound.
*/
public void playBottle() {
bottle.play(BOTTLE_BASE_VOLUME * soundEffectMaster);
}
}
|
package test_funzionali;
import static org.junit.Assert.*;
import java.util.Calendar;
import org.junit.Before;
import org.junit.Test;
import sistema.*;
public class UC12EliminareUnGestoreCinema {
ApplicazioneAmministratoreSistema adminApp;
Calendar adminBirthday;
Calendar managerBirthday;
@Before
public void setUp() throws Exception {
adminBirthday = Calendar.getInstance();
adminBirthday.set(1975, 2, 5);
managerBirthday = Calendar.getInstance();
managerBirthday.set(1980, 0, 1);
adminApp = new ApplicazioneAmministratoreSistema("Anna",
"Bianchi", "BNCNNA75C45D969Q", adminBirthday, "AnnaBianchi", "0000",
"anna.bianchi@gmail.com");
adminApp.login("AnnaBianchi", "0000");
adminApp.resetApplication();
// Registrazione gestore
adminApp.registraNuovoGestoreCinema("Luca", "Rossi", "RSSLCU80A01D969P",
managerBirthday, "luca.rossi@gmail.com");
}
// Scenario principale: Eliminare un Gestore Cinema
@Test
public void UC12test1() {
// 2. L'Applicazione Amministratore Sistema chiede all'Amministratore Sistema
// lo username del Gestore Cinema
// 3. L'Amministratore Sistema inserisce i dati richiesti
// 4. L'Applicazione Amministratore Sistema valida i dati inseriti
assertNotNull(ApplicazioneAmministratoreSistema.getRegisteredGestoreCinema("RSSLCU80A01D969P"));
// 6. L'Amministratore Sistema conferma di voler eliminare il profilo
// 7. L'Applicazione Amministratore Sistema effettua la cancellazione del profilo
assertTrue(adminApp.removeGestoreCinema("RSSLCU80A01D969P"));
}
// Scenario alternativo 3a: L'Amministratore Sistema decide di annullare l’operazione
@Test
public void UC12test2() {
// 2. L'Applicazione Amministratore Sistema chiede all'Amministratore Sistema
// lo username del Gestore Cinema
// di inserire i parametri registrazione Gestore Cinema
// 3a. L'Amministratore Sistema decide di annullare l’operazione
return;
}
// Scenario alternativo 4a: L'Applicazione Amministratore Sistema non valida i dati
@Test
public void UC12test3() {
// 2. L'Applicazione Amministratore Sistema chiede all'Amministratore Sistema
// lo username del Gestore Cinema
// 3. L'Amministratore Sistema inserisce i dati richiesti
// 4a. L'Applicazione Amministratore Sistema non valida i dati
String wrongUsername = "wrongUsername";
assertNull(ApplicazioneAmministratoreSistema.getRegisteredGestoreCinema(wrongUsername));
// Andare al passo 2 dello scenario principale
}
// Scenario alternativo 6a: L'Amministratore non conferma l'operazione
@Test
public void UC12test4() {
// 2. L'Applicazione Amministratore Sistema chiede all'Amministratore Sistema
// lo username del Gestore Cinema
// 3. L'Amministratore Sistema inserisce i dati richiesti
// 4. L'Applicazione Amministratore Sistema valida i dati inseriti
assertNotNull(ApplicazioneAmministratoreSistema.getRegisteredGestoreCinema("RSSLCU80A01D969P"));
// 6. L'Amministratore Sistema non conferma di voler eliminare il profilo
return;
}
}
|
package org.jboss.shrinkwrap.resolver.example;
/**
* A component for creating personal greetings.
*/
public class Greeter {
public String createGreeting(String name) {
return "Hello, " + name + "!";
}
} |
package com.hx.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import com.hx.entity.SysUser;
import com.hx.model.MainDataModel;
import com.hx.utils.page.object.BaseConditionVO;
/**
*
* @Description: 用户 业务层
* @author Administrator
* @date: 2019年12月24日下午2:19:37
*/
public interface SysUserService extends BaseService<SysUser, Integer>
{
@Override
List<SysUser> selectBySelective(SysUser friend);
List<SysUser> selectBySelective();
/**
* 根据条件分页查询用户列表
*
* @param model 用户信息
* @return 用户信息集合信息
*/
List<SysUser> selectUserList(MainDataModel model);
/**
* 通过用户名查询用户
*
* @param userName 用户名
* @return 用户对象信息
*/
public SysUser selectUserByUserName(String userName);
/**
* 新增用户信息
*
* @param user 用户信息
* @return 结果
*/
public int insertUser(SysUser user);
/**
* 修改用户信息
*
* @param user 用户信息
* @return 结果
*/
public int updateUser(SysUser user);
/**
* 通过用户ID删除用户
*
* @param userId 用户ID
* @return 结果
*/
public int deleteUserById(Long userId);
/**
* 校验用户名称是否唯一
*
* @param userName 用户名称
* @return 结果
*/
public String checkUserNameUnique(String userName);
PageInfo<SysUser> selectForPage(BaseConditionVO baseConditionVO);
}
|
import java.util.*;
//import java.lang.*;
//import java.io.*;
class RevBits
{
// you need treat n as an unsigned value
public int reverseBits(int n)
{
String inputB = Integer.toBinaryString(n);
int length = inputB.length();
StringBuilder outputB = new StringBuilder();
int i =0;
System.out.println(inputB.toString());
for(i=0;i<length;i++)
{
outputB.append(Character.toString(inputB.charAt(length-i-1)));
}
if(length < 32)
{
for(i=length;i<32;i++)
outputB.append("0");
}
System.out.println(outputB.toString());
Long output = Long.parseLong(outputB.toString(),2);
return output.intValue();
}
public static void main(String[] args)
{
RevBits rv = new RevBits();
System.out.println(rv.reverseBits(43261596));
}
} |
package shashi.sort;
public class CountingSort {
public static void main(String[] args){
int []A={2,2,4,6,3,5,1,3,0};
int l=A.length;
countingSort(A, l);
}
static void countingSort(int []A, int l){
int []B=new int [l];
int []C=new int [l];
for(int i=0; i<l; i++){
C[A[i]]++;
}
for(int i=1; i<l; i++){
C[i]=C[i]+C[i-1];
}
for(int i=l-1; i>=0; i--){
B[C[A[i]]-1]=A[i];
C[A[i]]=C[A[i]]-1;
}
for(int b:B){
System.out.print(b+" ");
}
}
}
|
package com.Appthuchi.Appqlthuchi.ui.khoanchi.fragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.Appthuchi.Appqlthuchi.DAO.KhoanChiDAO;
import com.Appthuchi.Appqlthuchi.DAO.LoaichiDAO;
import com.Appthuchi.Appqlthuchi.R;
import com.Appthuchi.Appqlthuchi.adapter.KhoanChiAdapter;
import com.Appthuchi.Appqlthuchi.moder.KhoanChi;
import com.Appthuchi.Appqlthuchi.moder.LoaiChi;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class KhoanChiConFragment extends Fragment {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
private EditText editMa,edtSoTien,edtMoTa;
private TextView tvNgayChi;
private Button btnChonNgay,btnAdd,btnHuy;
private Spinner spinLoaiChi;
private List<LoaiChi> loaiChiList;
private LoaichiDAO loaichiDAO;
private KhoanChiDAO khoanChiDAO;
private List<KhoanChi> khoanChiList;
private KhoanChiAdapter khoanChiAdapter;
private ListView lvKhoanChi;
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.khoanchifragmet,container,false);
FloatingActionButton fab = view.findViewById(R.id.fab);
loaichiDAO = new LoaichiDAO(getActivity());
khoanChiDAO = new KhoanChiDAO(getActivity());
lvKhoanChi = view.findViewById(R.id.lvKhoanChi);
try {
hienThi();
} catch (ParseException e) {
e.printStackTrace();
}
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
return view;
}
public void showDialog(){
final Dialog add_khoanchi_layout = new Dialog(getContext());
add_khoanchi_layout.setTitle("Thêm khoản chi");
add_khoanchi_layout.setContentView(R.layout.new_item_khoanchi);
spinLoaiChi = add_khoanchi_layout.findViewById(R.id.spinLoaiChi);
edtSoTien = add_khoanchi_layout.findViewById(R.id.edtSoTien);
tvNgayChi = add_khoanchi_layout.findViewById(R.id.tvNgayChi);
edtMoTa = add_khoanchi_layout.findViewById(R.id.edtMoTa);
btnChonNgay = add_khoanchi_layout.findViewById(R.id.btnChonNgay);
//Spiner
loaiChiList = new ArrayList<>();
loaiChiList = loaichiDAO.getALLLoaiChi();
ArrayAdapter<LoaiChi> arrayAdapter= new ArrayAdapter<LoaiChi>(getActivity(),android.R.layout.simple_spinner_item,loaiChiList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinLoaiChi.setAdapter(arrayAdapter);
spinLoaiChi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
loaiChiList.get(spinLoaiChi.getSelectedItemPosition()).getTenLoaiChi();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Chọn Ngày
btnChonNgay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar lich = Calendar.getInstance();
DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
tvNgayChi.setText(dayOfMonth + "-" +(month+1) + "-" + year);
}
},lich.get(Calendar.YEAR)
,lich.get(Calendar.MONTH)
,lich.get(Calendar.DAY_OF_MONTH));
pickerDialog.show();
}
});
btnAdd = add_khoanchi_layout.findViewById(R.id.btnAdd);
btnHuy = add_khoanchi_layout.findViewById(R.id.btnHuy);
//Thêm data
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
add();
add_khoanchi_layout.cancel();
} catch (ParseException e) {
e.printStackTrace();
}
}
});
btnHuy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
add_khoanchi_layout.cancel();
}
});
add_khoanchi_layout.show();
}
public void add() throws ParseException {
KhoanChi khoanChi = new KhoanChi();
khoanChi.setLoaiChi(spinLoaiChi.getSelectedItem().toString().trim());
khoanChi.setSoTien(edtSoTien.getText().toString().trim());
khoanChi.setNgayChi(tvNgayChi.getText().toString());
khoanChi.setMoTa(edtMoTa.getText().toString().trim());
long result = khoanChiDAO.insertKhoanChi(khoanChi);
if (result>0){
Toast.makeText(getActivity(),"Thành Công",Toast.LENGTH_SHORT).show();
hienThi();
}else {
Toast.makeText(getActivity(),"thêm thất bại",Toast.LENGTH_SHORT).show();
}
}
public void hienThi() throws ParseException {
khoanChiList = khoanChiDAO.getAllKhoanChi();
khoanChiAdapter = new KhoanChiAdapter(getActivity(),khoanChiList);
lvKhoanChi.setAdapter(khoanChiAdapter);
}
}
|
package Test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.apache.xerces.util.SynchronizedSymbolTable;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;
public class SampleTest {
@BeforeSuite
public void beforeSuite() {
System.out.println("Before Test Suit");
}
@BeforeTest
public void beforeTest() {
System.out.println("Before Any Test");
}
@BeforeClass
public void beforeClass() {
System.out.println("Before ny class");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("Before any test method ");
}
@Test
public void TestFun() {
System.out.println("Testing Code");
}
@AfterMethod
public void afterMethod() {
System.out.println("After any test method");
}
@AfterClass
public void afterClass() {
System.out.println("After every class ");
}
@AfterTest
public void afterTest() {
System.out.println("After every test belongs to a one class");
}
@AfterSuite
public void afterSuite() {
System.out.println("after All test are Executed belogs to class");
}
}
|
package com.tencent.mm.plugin.offline.b;
import android.database.Cursor;
import com.tencent.mm.plugin.offline.a.r;
import com.tencent.mm.sdk.e.e;
import com.tencent.mm.sdk.e.i;
import com.tencent.mm.sdk.platformtools.x;
public final class a extends i<r> {
public static final String[] diD = new String[]{i.a(r.dhO, "OfflineOrderStatus")};
public e diF;
public a(e eVar) {
super(eVar, r.dhO, "OfflineOrderStatus", null);
this.diF = eVar;
}
public final r bkW() {
int i = 1;
r rVar = null;
x.i("MicroMsg.OfflineOrderStatusStorage", "in getLastestOrder: orders count: %d, latest 3 orders: %s", new Object[]{Integer.valueOf(bkY()), bkX()});
Cursor b = this.diF.b("SELECT * FROM OfflineOrderStatus WHERE status!=-1 ORDER BY rowid DESC LIMIT 1", null, 2);
if (b != null) {
b.moveToFirst();
if (b.isAfterLast()) {
i = 0;
}
if (i != 0) {
rVar = new r();
rVar.d(b);
}
b.close();
if (rVar != null) {
x.i("MicroMsg.OfflineOrderStatusStorage", "getLastestOrder status = " + rVar.field_status);
} else {
x.i("MicroMsg.OfflineOrderStatusStorage", "getLastestOrder null");
}
}
return rVar;
}
public final r IX(String str) {
r rVar = null;
Cursor b = this.diF.b("select * from OfflineOrderStatus where reqkey=?", new String[]{str}, 2);
if (b != null) {
b.moveToFirst();
x.i("MicroMsg.OfflineOrderStatusStorage", "in getOrderStatusByTranId: cursor.isAfterLast() = " + b.isAfterLast());
if (!b.isAfterLast()) {
rVar = new r();
rVar.d(b);
}
b.close();
}
return rVar;
}
public final void b(r rVar) {
if (rVar.field_reqkey == null) {
x.e("MicroMsg.OfflineOrderStatusStorage", "status.field_reqkey is null");
return;
}
int i;
Cursor b = this.diF.b("select * from OfflineOrderStatus where reqkey=?", new String[]{rVar.field_reqkey}, 2);
if (b == null) {
i = 0;
} else {
b.moveToFirst();
i = !b.isAfterLast() ? 1 : 0;
b.close();
}
if (i == 0) {
x.i("MicroMsg.OfflineOrderStatusStorage", "saveOfflineOrderStatus: insert reqKey: %s, status: %d ", new Object[]{rVar.field_reqkey, Integer.valueOf(rVar.field_status)});
b(rVar);
return;
}
x.i("MicroMsg.OfflineOrderStatusStorage", "saveOfflineOrderStatus: update reqKey: %s, status: %d ", new Object[]{rVar.field_reqkey, Integer.valueOf(rVar.field_status)});
c(rVar, new String[0]);
}
public final void IY(String str) {
r IX = IX(str);
if (IX != null) {
IX.field_status = -1;
} else {
IX = new r();
IX.field_reqkey = str;
IX.field_status = -1;
}
b(IX);
}
public final String bkX() {
Cursor b = this.diF.b(String.format("SELECT * FROM %s ORDER BY %s DESC LIMIT %d;", new Object[]{"OfflineOrderStatus", "rowid", Integer.valueOf(3)}), null, 2);
String str = "";
if (b == null) {
x.e("MicroMsg.OfflineOrderStatusStorage", "getAllOrdersInfo: error.cursor is null\n");
} else {
int i = 0;
while (b.moveToNext()) {
int i2 = i + 1;
if (i2 > 3) {
break;
}
for (i = 0; i < b.getColumnCount(); i++) {
str = str + b.getColumnName(i) + ": " + b.getString(i) + ", ";
}
str = str + ";";
i = i2;
}
b.close();
}
return str;
}
public final int bkY() {
int i = 0;
Cursor b = this.diF.b(String.format("SELECT COUNT(*) FROM %s;", new Object[]{"OfflineOrderStatus"}), null, 2);
if (b == null) {
x.e("MicroMsg.OfflineOrderStatusStorage", "getOrdersCount: error.cursor is null\n");
} else {
if (b.moveToNext() && b.getColumnCount() > 0) {
i = b.getInt(0);
}
b.close();
}
return i;
}
}
|
package com.mobilephone.foodpai.util;
import android.util.Log;
import com.mobilephone.foodpai.bean.UserBean;
import com.mobilephone.foodpai.bean.bmobbean.CollectBean;
import java.util.List;
import java.util.Map;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;
/**
* Created by Administrator on 2016/11/4.
* 单例模式工具类,getInstance()拿到此类实例
*/
public class DaoBmobUtil {
private static final String TAG = "DaoBmobUtil-test";
private static DaoBmobUtil daoBmobUtil = new DaoBmobUtil();
public static DaoBmobUtil getInstance() {
return daoBmobUtil;
}
private DaoBmobUtil() {
}
//修改用户信息
public void onUpdate(UserBean userBean, final OnUpdate onUpdate) {
UserBean currentUser = BmobUser.getCurrentUser(UserBean.class);
userBean.update(currentUser.getObjectId(), new UpdateListener() {
@Override
public void done(BmobException e) {
onUpdate.done(e);
}
});
}
//用户登录
public void onLogin(UserBean userBean, final OnDaoLogin onDaoLogin) {
userBean.login(new SaveListener<UserBean>() {
@Override
public void done(UserBean userBean, BmobException e) {
onDaoLogin.done(userBean, e);
}
});
}
//查询用户数据
public void onQuery(final OnDaoQuery onDaoQuery) {
UserBean user = UserBean.getCurrentUser(UserBean.class);
if (user!=null) {
BmobQuery<CollectBean> Query = new BmobQuery<>();
Query.addWhereEqualTo("Collect", user);
Query.findObjects(new FindListener<CollectBean>() {
@Override
public void done(List<CollectBean> list, BmobException e) {
onDaoQuery.onQuery(list, e);
}
});
}
}
//增加用户收藏数据
public void onAdd(String title, String link,String imgurl,String calory,String code, final OnDaoAdd onDaoAdd) {
UserBean user = UserBean.getCurrentUser(UserBean.class);
Log.e(TAG, "onAdduser: "+user);
if (user!=null) {
String objectId = user.getObjectId();
Log.e(TAG, "onAddobjectId: "+objectId);
CollectBean collectBean = new CollectBean();
collectBean.setTitle(title);
collectBean.setLink(link);
collectBean.setImgUrl(imgurl);
collectBean.setCalory(calory);
collectBean.setCode(code);
collectBean.setCollect(user);
collectBean.save(new SaveListener<String>() {
@Override
public void done(String s, BmobException e) {
onDaoAdd.onAdd(s, e);
}
});
}
}
//删除用户收藏数据
public void onDelete(Map<String, String> map, String title, final OnDelete onDelete) {
String objectId = map.get(title);
Log.e(TAG, "onDelete: ");
CollectBean collectBean = new CollectBean();
collectBean.setObjectId(objectId);
collectBean.delete(new UpdateListener() {
@Override
public void done(BmobException e) {
onDelete.onDelete(e);
}
});
}
//单文件上传
/**
* @param bmobFile BmobFile bmobFile = new BmobFile(new File(picPath));
* @param onDaoUpLoadfile 状态回调
*/
public void upLoadFile(BmobFile bmobFile, final OnDaoUpLoadfile onDaoUpLoadfile) {
bmobFile.uploadblock(new UploadFileListener() {
@Override
public void done(BmobException e) {
onDaoUpLoadfile.done(e);
}
@Override
public void onProgress(Integer value) {
onDaoUpLoadfile.onProgress(value);
}
});
}
//批量上传
public void upLoadeFiles(String[] filePaths, final OnDaoUpLoadFiles onDaoUpLoadFiles) {
BmobFile.uploadBatch(filePaths, new UploadBatchListener() {
/**
*1、files-上传完成后的BmobFile集合,是为了方便大家对其上传后的数据进行操作,例如你可以将该文件保存到表中
*2、urls-上传文件的完整url地址
*if (urls.size() == filePaths.length) {//如果数量相等,则代表文件全部上传完成
*do something
*}
* @param files
* @param urls
*/
@Override
public void onSuccess(List<BmobFile> files, List<String> urls) {
onDaoUpLoadFiles.onSuccess(files, urls);
}
/**
*
* @param curIndex--表示当前第几个文件正在上传
* @param curPercent--表示当前上传文件的进度值(百分比)
* @param total--表示总的上传文件数
* @param totalPercent--表示总的上传进度(百分比)
*/
@Override
public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
onDaoUpLoadFiles.onProgress(curIndex, curPercent, total, totalPercent);
}
/**
* Log.e(TAG, "onError: " + "错误码" + statuscode + ",错误描述:" + errormsg);
* @param statuscode
* @param errormsg
*/
@Override
public void onError(int statuscode, String errormsg) {
onDaoUpLoadFiles.onError(statuscode, errormsg);
}
});
}
//修改用户信息接口回调
public interface OnUpdate {
void done(BmobException e);
}
//用户登录接口
public interface OnDaoLogin {
void done(UserBean userBean, BmobException e);
}
//单文件上传回调
public interface OnDaoUpLoadfile {
void done(BmobException e);
void onProgress(Integer value);
}
//批量上传的回调
public interface OnDaoUpLoadFiles {
void onSuccess(List<BmobFile> files, List<String> urls);
void onProgress(int curIndex, int curPercent, int total, int totalPercent);
void onError(int statuscode, String errormsg);
}
//查询的接口回调
public interface OnDaoQuery {
void onQuery(List<CollectBean> list, BmobException e);
}
//增加数据的接口
public interface OnDaoAdd {
void onAdd(String s, BmobException e);
}
//删除数据的接口
public interface OnDelete {
void onDelete(BmobException e);
}
}
|
package com.smalaca.bank.domain.account;
import java.math.BigDecimal;
public class AccountDto {
private final Long id;
private final String number;
private final BigDecimal amount;
private final String currency;
AccountDto(Long id, String number, BigDecimal amount, String currency) {
this.id = id;
this.number = number;
this.amount = amount;
this.currency = currency;
}
public Long getId() {
return id;
}
public String getNumber() {
return number;
}
public BigDecimal getAmount() {
return amount;
}
public String getCurrency() {
return currency;
}
}
|
package com.jt.service;
import com.jt.vo.EasyUIImage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {
@Value("${image.localFileDir}")
private String localFileDir;
@Value("${image.urlPath}")
private String urlPath;
/**
* 1.判断文件是否为图片 jpg|png|gif
* 2.防止恶意程序上传 判断图片固有属性 宽度和高度
* 3.将图片分目录存储 按照时间进行存储 yyyy/MM//dd
* 4.解决文件重名问题 UUID
* @param uploadFile
* @return
*/
@Override
public EasyUIImage uploadFile(MultipartFile uploadFile) {
EasyUIImage uiImage = new EasyUIImage();
//1.获取图片名称 abc.jpg
String fileName = uploadFile.getOriginalFilename().toLowerCase();
//2.利用正则表达式判断后缀
if (!fileName.matches("^.+\\.(jpg|png|gif)$")){
uiImage.setError(1);//表示不是正经图片
return uiImage;
}
//3.获取图片的宽度和高度
try {
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
if (height==0 || width==0){
//如果宽度和高度为0,则程序终止
uiImage.setError(1);
return uiImage;
}
uiImage.setWidth(width).setHeight(height);
//4.以时间格式进行数据存储yyyy/MM/dd
String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
//准备文件上传路径
String localDir = localFileDir + dateDir;
File dirFile = new File(localDir);
if (!dirFile.exists()){
//如果文件不存在,则创建文件夹
dirFile.mkdirs();
}
String uuid = UUID.randomUUID().toString().replace("-","");
String fileType = fileName.substring(fileName.lastIndexOf("."));
String realFileName = uuid + fileType;
/*
文件上传
*/
String realPath = localDir + "/" + realFileName;
File realFilePath = new File(realPath);
uploadFile.transferTo(realFilePath);
System.out.println("上传成功!!!");
uiImage.setUrl(urlPath + dateDir + "/" + realFileName);
} catch (IOException e) {
e.printStackTrace();
uiImage.setError(1); //程序出错,上传终止
}
return uiImage;
}
}
|
/*
* Copyright (C), 2013-2014, 上海汽车集团股份有限公司
* FileName: Connector.java
* Author: wanglijun
* Date: 2014年8月11日 下午10:03:46
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.adapter.connector.api;
import com.xjf.wemall.api.exception.AdapterException;
/**
* 接口连接声明类 <br>
* 接口连接声明类
*
* @author wanglijun
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public interface Connector {
/***
*
* 功能描述: 发送请求并收响应对象
* 〈功能详细描述〉
*
* @param object 请求对象
* @return 响应对象
* @throws AdapterException 接口适器异常
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
public Object sendRequestResponse(Object object) throws AdapterException;
}
|
package com.funlib.thread;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolUtily {
private static int RUNNING_THREAD_MAX_NUM = 6; // 同时运行的线程最大个数
private static int THREAD_IN_POOL_MAX_NUM = 10; // 线程池中最大线程个数
private static int THREAD_IDLE_TIME = 1; // 线程空闲时间,到期,被干掉,应该尽量小
private static TimeUnit IDLE_TIME_UNIT = TimeUnit.MILLISECONDS;
private static BlockingQueue<Runnable> sQueue;
private static ThreadPoolExecutor sExecutor;
private ThreadPoolUtily() {
}
public static void init() {
sQueue = new LinkedBlockingQueue<Runnable>();// 使用动态增加队列,防止线程超过最大数后,线程池抛出异常
sExecutor = new ThreadPoolExecutor(RUNNING_THREAD_MAX_NUM,
THREAD_IN_POOL_MAX_NUM, THREAD_IDLE_TIME, IDLE_TIME_UNIT,
sQueue);
}
/**
* 执行新任务,任务可能不会立即执行
*
* @param task
*/
public static void executorTask(Runnable task) {
sExecutor.execute(task);
}
/**
* 退出线程池
*/
public static void quit() {
sExecutor.shutdown();
}
/**
* 如果任务尚未开始,remove
*
* @param task
*/
public static void removeTask(Runnable task) {
sExecutor.remove(task);
sExecutor.getQueue().clear();
}
}
|
package tasks;
public class order {
}
|
package hhc.common.entity.base;
import java.io.Serializable;
/**
* @author hhc
*/
public class KeyValuePair implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6761291511139593128L;
private String key;
private Double value;
public KeyValuePair() {}
public KeyValuePair(String key, Double value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
|
package unalcol.agents.examples.labyrinth.teseo;
import unalcol.agents.Agent;
import unalcol.agents.examples.labyrinth.Labyrinth;
import unalcol.agents.examples.labyrinth.LabyrinthDrawer;
import unalcol.agents.examples.labyrinth.LabyrinthPercept;
import unalcol.agents.simulate.util.SimpleLanguage;
import unalcol.types.collection.vector.Vector;
public class TeseoLabyrinth extends Labyrinth {
public TeseoLabyrinth(Vector<Agent> _agents, int[][] _structure, SimpleLanguage _language) {
super(_agents, _structure, _language);
}
public TeseoLabyrinth(Agent agent, int[][] _structure, SimpleLanguage _language) {
super(agent, _structure, _language);
}
protected LabyrinthPercept getPercept(int x, int y) {
return new TeseoPercept(structure[x][y], language);
}
public Labyrinth copy() {
return new TeseoLabyrinth(agents, structure.clone(), language);
}
public boolean edit(int X, int Y) {
boolean flag = super.edit(X, Y);
if (!flag) {
X -= LabyrinthDrawer.MARGIN;
Y -= LabyrinthDrawer.MARGIN;
int x = X / LabyrinthDrawer.CELL_SIZE;
int y = Y / LabyrinthDrawer.CELL_SIZE;
if (0 <= x && x < LabyrinthDrawer.DIMENSION && 0 <= y && y < LabyrinthDrawer.DIMENSION) {
structure[x][y] ^= (1 << 4);
flag = true;
} else {
flag = false;
}
}
return flag;
}
}
|
package vlad.fp.services.asynchronous.api;
import vlad.fp.lib.Task;
import vlad.fp.services.model.EmailAddress;
import vlad.fp.services.model.ReportID;
public interface EmailServiceF {
Task<Void> sendReport(EmailAddress emailAddress, ReportID reportID);
}
|
package com.linkedbook.entity;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
@DynamicInsert
@AllArgsConstructor
@NoArgsConstructor
@Getter @Setter
@Entity
@Table(name = "area")
public class AreaDB {
@Id
@Column(name = "id", nullable = false, updatable = false)
@GeneratedValue(strategy = IDENTITY)
private int id;
@Column(name = "sido", nullable = false, length = 45)
private String sido;
@Column(name = "sigungu", nullable = false, length = 45)
private String sigungu;
@Column(name = "dongmyeonri", nullable = false, length = 45)
private String dongmyeonri;
}
|
package es.uma.sportjump.sjs.web.beans;
public class EventCalendarCompleteBean {
private Long id;
private String title;
private String start;
private TrainingBean training;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public TrainingBean getTraining() {
return training;
}
public void setTraining(TrainingBean training) {
this.training = training;
}
}
|
package com.music.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CartController {
@RequestMapping("/add")
public ModelAndView addToCart(@RequestParam(value = "name", required = false, defaultValue = "world") String name)
{
ModelAndView mv=new ModelAndView("AddCart");
return mv;
}
@RequestMapping("/chck")
public ModelAndView chckOut(@RequestParam(value = "name", required = false, defaultValue = "world") String name)
{
ModelAndView mv=new ModelAndView("CheckOut");
return mv;
}
@RequestMapping("/pay")
public ModelAndView payCash(@RequestParam(value = "name", required = false, defaultValue = "world") String name)
{
ModelAndView mv=new ModelAndView("Payment");
return mv;
}
@RequestMapping("/deal")
public ModelAndView confirmDeal(@RequestParam(value = "name", required = false, defaultValue = "world") String name)
{
ModelAndView mv=new ModelAndView("Confirm");
return mv;
}
}
|
package com.tencent.mm.ui.chatting;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.model.au;
class AppAttachDownloadUI$1 implements OnMenuItemClickListener {
final /* synthetic */ AppAttachDownloadUI tGp;
AppAttachDownloadUI$1(AppAttachDownloadUI appAttachDownloadUI) {
this.tGp = appAttachDownloadUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
if (AppAttachDownloadUI.a(this.tGp) != null) {
au.DF().c(AppAttachDownloadUI.a(this.tGp));
}
this.tGp.finish();
return true;
}
}
|
package de.dhbw.studientag.tours;
import java.util.ArrayList;
import java.util.List;
/*
* This java class is from google-collections
* https://code.google.com/p/google-collections/issues/attachmentText?id=71&aid=-7147814569069805842&name=Permutations.java
*/
/**
* The Permutations class provides an iteration of all permutations of an list
* of objects. Each permutation is simply an ordered list of the group.
* <p>
* For example, to see all of the ways we can select a school representative and an
* alternate from a list of 4 children, begin with an array of names::
* <blockquote><pre>
* List<Children> children = Collections.asList({Leonardo, Monica, Nathan, Olivia});
* </pre></blockquote>
* To see all 2-permutations of these 4 names, create and use a Permutations enumeration:
* <blockquote><pre>
* Permutations<Children> c = new Permutations<Children>(children, 2);
* while (c.hasNext()) {
* List<Children> perm = c.next();
* for (int i = 0; i < perm.size(); i++) {
* System.out.print(perm.get(i) + );
* }
* System.out.println();
* }
* </pre></blockquote>
* This will print out:
* <blockquote><pre>
* Leonardo Monica
* Leonardo Nathan
* Leonardo Olivia
* Monica Leonardo
* Monica Nathan
* Monica Olivia
* Nathan Leonardo
* Nathan Monica
* Nathan Olivia
* Olivia Leonardo
* Olivia Monica
* Olivia Nathan
* </pre></blockquote>
*
*/
public class Permutations<E> implements java.util.Iterator<List<E>>{
private List<E> inList;
private int n, m;
private int[] index;
private boolean hasMore = true;
/**
* Create a Permutation to iterate through all possible lineups
* of the supplied array of Objects.
*
* @param Object[] inArray the group to line up
* @exception CombinatoricException Should never happen
* with this interface
*
*/
public Permutations(List<E> inList){
this(inList, inList.size());
}
/**
* Create a Permutation to iterate through all possible lineups
* of the supplied array of Objects.
*
* @param Object[] inArray the group to line up
* @param inArray java.lang.Object[], the group to line up
* @param m int, the number of objects to use
* @exception CombinatoricException if m is greater than
* the length of inArray, or less than 0.
*/
public Permutations(List<E> inList, int m){
this.inList = inList;
this.n = inList.size();
this.m = m;
assert this.n >= m && m >= 0;
/**
* index is an array of ints that keep track of the next
* permutation to return. For example, an index on a permutation
* of 3 things might contain {1 2 0}. This index will be followed
* by {2 0 1} and {2 1 0}.
* Initially, the index is {0 ... n - 1}.
*/
this.index = new int[this.n];
for (int i = 0; i < this.n; i++) {
this.index[i] = i;
}
/**
* The elements from m to n are always kept ascending right
* to left. This keeps the dip in the interesting region.
*/
reverseAfter(m - 1);
}
/**
* @return true, unless we have already returned the last permutation.
*/
public boolean hasNext(){
return this.hasMore;
}
/**
* Move the index forward a notch. The algorithm first finds the
* rightmost index that is less than its neighbor to the right. This
* is the dip point. The algorithm next finds the least element to
* the right of the dip that is greater than the dip. That element is
* switched with the dip. Finally, the list of elements to the right
* of the dip is reversed.
* <p>
* For example, in a permutation of 5 items, the index may be
* {1, 2, 4, 3, 0}. The dip is 2 the rightmost element less
* than its neighbor on its right. The least element to the right of
* 2 that is greater than 2 is 3. These elements are swapped,
* yielding {1, 3, 4, 2, 0}, and the list right of the dip point is
* reversed, yielding {1, 3, 0, 2, 4}.
* <p>
* The algorithm is from Applied Combinatorics, by Alan Tucker.
*
*/
private void moveIndex(){
// find the index of the first element that dips
int i = rightmostDip();
if (i < 0) {
this.hasMore = false;
return;
}
// find the least greater element to the right of the dip
int leastToRightIndex = i + 1;
for (int j = i + 2; j < this.n; j++){
if (this.index[j] < this.index[leastToRightIndex] && this.index[j] > this.index[i]){
leastToRightIndex = j;
}
}
// switch dip element with least greater element to its right
int t = this.index[i];
this.index[i] = this.index[leastToRightIndex];
this.index[leastToRightIndex] = t;
if (this.m - 1 > i){
// reverse the elements to the right of the dip
reverseAfter(i);
// reverse the elements to the right of m - 1
reverseAfter(this.m - 1);
}
}
/**
* @return java.lang.Object, the next permutation of the original Object array.
* <p>
* Actually, an array of Objects is returned. The declaration must say just Object,
* because the Permutations class implements Iterator, which declares that the
* next() returns a plain Object.
* Users must cast the returned object to (Object[]).
*/
public List<E> next(){
if (!this.hasMore){
return null;
}
List<E> list = new ArrayList<E>(this.m);
for (int i = 0; i < this.m; i++){
int thisIndexI = this.index[i];
E element = this.inList.get(thisIndexI);
list.add(element);
}
moveIndex();
return list;
}
/**
* Reverse the index elements to the right of the specified index.
*/
private void reverseAfter(int i){
int start = i + 1;
int end = this.n - 1;
while (start < end){
int t = this.index[start];
this.index[start] = this.index[end];
this.index[end] = t;
start++;
end--;
}
}
/**
* @return int the index of the first element from the right
* that is less than its neighbor on the right.
*/
private int rightmostDip(){
for (int i = this.n - 2; i >= 0; i--){
if (this.index[i] < this.index[i+1]){
return i;
}
}
return -1;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
|
/**
*
*/
package io.github.liuzm.distribute.registy.support;
import java.util.concurrent.locks.ReentrantLock;
import io.github.liuzm.distribute.common.model.Node;
import io.github.liuzm.distribute.registy.RegistryNode;
import io.github.liuzm.distribute.registy.RegistryNodeFactory;
/**
* @author xh-liuzhimin
*
*/
public abstract class AbstractRegistryNodeFactory implements RegistryNodeFactory {
private static final ReentrantLock LOCK = new ReentrantLock();
protected RegistryNode registry;
/**
*
* @param node
* @return
*/
public RegistryNode getRegistryNode(Node node) {
LOCK.lock();
try {
if (registry != null) {
return registry;
}
registry = createRegistry(node);
if (registry == null) {
throw new IllegalStateException("Can not create registry " + node);
}
return registry;
} finally {
LOCK.unlock();
}
}
protected abstract RegistryNode createRegistry(Node node);
}
|
package com.Arrays;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class cutTheStick {
static int[] toIntArray(List<Integer> list){
int[] ret = new int[list.size()];
for(int i = 0;i < ret.length;i++)
ret[i] = list.get(i);
return ret;
}
// Complete the cutTheSticks function below.
static int[] cutTheSticks(int[] arr) {
List<Integer> list = new ArrayList<>();
int min = Integer.MAX_VALUE;
int size = arr.length;
for(int i = 0; i < size; i++){
if(min > arr[i]){
min = arr[i];
}
}
int newMin = Integer.MAX_VALUE;
boolean flag = true;
int sticksCut = 0;
while(flag){
flag = false;
for(int i = 0; i < size; i++){
if(arr[i] > 0){
arr[i] -= min;
flag = true;
sticksCut++;
}
if(newMin > arr[i] && arr[i] != 0)
newMin = arr[i];
}
min = newMin;
newMin = Integer.MAX_VALUE;
if(sticksCut == 0){
break;
}
list.add(sticksCut);
sticksCut = 0;
}
return toIntArray(list);
}
//METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
public static int[] cellCompete(int[] cells, int days)
{
// INSERT YOUR CODE HERE
int size = cells.length;
int[] dummyCells = new int[size];
for(int i = 0; i < days; i++){
System.arraycopy(cells, 0, dummyCells, 0, size);
if(dummyCells[1] == 0){
cells[0] = 0;
}else{
cells[0] = 1;
}
if(dummyCells[size - 2] == 0){
cells[size - 1] = 0;
}else{
cells[size - 1] = 1;
}
for(int j = 1; j < size - 1; j++){
if((dummyCells[j - 1] == 0 && dummyCells[j+1] == 0) || (dummyCells[j - 1] == 1 && dummyCells[j+1] == 1)){
cells[j] = 0;
}else{
cells[j] = 1;
}
}
}
return cells;
}
public static int generalizedGCD(int arr[])
{
// INSERT YOUR CODE HERE
int size = arr.length;
int min = Integer.MAX_VALUE;
for(int i = 0; i < size; i++){
if(min > arr[i]){
min = arr[i];
}
}
for(int j = min; j > 0; j--){
boolean flag = true;
for(int i = 0; i < size; i++){
if(arr[i] % j != 0){
flag = false;
break;
}
}
if(flag){
min = j;
break;
}
}
return min;
}
private static Scanner scanner = null;
static {
try {
scanner = new Scanner( new FileInputStream(new File("input/dummy")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
int[] arr = new int[]{2,3,4,5,6};
// int n = scanner.nextInt();
// scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
//
// int[] arr = new int[n];
//
// String[] arrItems = scanner.nextLine().split(" ");
// scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
//
// for (int i = 0; i < n; i++) {
// int arrItem = Integer.parseInt(arrItems[i]);
// arr[i] = arrItem;
// }
//
// int[] result = cutTheSticks(arr);
//
// for (int i = 0; i < result.length; i++) {
// System.out.println(String.valueOf(result[i]));
//
// if (i != result.length - 1) {
// System.out.println();
// }
// }
generalizedGCD( arr );
System.out.println();
scanner.close();
}
}
|
package com.drzewo97.ballotbox.core.model.candidateprotocolvotes;
import com.drzewo97.ballotbox.core.model.candidate.Candidate;
import com.drzewo97.ballotbox.core.model.candidatesvotescountwardprotocol.CandidatesVotesCountWardProtocol;
import javax.persistence.*;
@Entity
public class CandidateProtocolVotes {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Candidate candidate;
private Integer votesCount;
@ManyToOne
private CandidatesVotesCountWardProtocol candidatesVotesCountWardProtocol;
public CandidateProtocolVotes(Candidate candidate) {
this.candidate = candidate;
}
public CandidateProtocolVotes() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Candidate getCandidate() {
return candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
public Integer getVotesCount() {
return votesCount;
}
public void setVotesCount(Integer votesCount) {
this.votesCount = votesCount;
}
public CandidatesVotesCountWardProtocol getCandidatesVotesCountWardProtocol() {
return candidatesVotesCountWardProtocol;
}
public void setCandidatesVotesCountWardProtocol(CandidatesVotesCountWardProtocol candidatesVotesCountWardProtocol) {
this.candidatesVotesCountWardProtocol = candidatesVotesCountWardProtocol;
}
}
|
package multithreading;
import sun.nio.ch.ThreadPool;
/**
* @author malf
* @description 测试自定义线程池
* @project how2jStudy
* @since 2020/10/22
*/
public class TestMalfThreadPool {
public static void main(String[] args) {
MalfThreadPool pool = new MalfThreadPool();
for (int i = 0; i < 5; i++) {
Runnable task = new Runnable() {
@Override
public void run() {
}
};
pool.add(task);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
|
class Solution {
public static void main(String args[]){
int[] arr = new int[]{1,3,5,6};
//If the target is not present, return index if it was inserted in ascending order for the target.
System.out.println(searchInsert(arr, 2)); //1
}
public int searchInsert(int[] arr, int target) {
int low = 0, mid, high = arr.length-1;
while(low<=high){
mid = (low+high)/2;
if(arr[mid] == target){
return mid;
}
else if(arr[low] == target){
return low;
}else if(arr[high] == target){
return high;
}
else if(target < arr[low]){
return low;
}
else if(target > arr[high]){
return high+1;
}
else if(arr[mid]>arr[high]){
if(target > arr[low] && target < arr[mid]){
high = mid -1;
}else{
low = mid +1;
}
}
else if(target > arr[mid] && target < arr[high]){
low = mid +1;
}
else{
high = mid -1;
}
}
return -1;
}
}
|
package com.plter.lib.java.db;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface IDbQueryCallback {
void onResult(ResultSet resultSet) throws SQLException;
}
|
package com.gnomikx.www.gnomikx.Data;
import com.google.firebase.firestore.Exclude;
import com.google.firebase.firestore.ServerTimestamp;
import java.util.Date;
/**
* Class to act as the object for the details of the query(POJO).
*/
public class QueryDetails {
private String title;
private String body;
private String username;
private String userID;
private String response;
@Exclude
private String documentId;
@ServerTimestamp
private Date timestamp;
public QueryDetails(){
//necessary empty public constructor
}
public QueryDetails(String title, String body, String username, String userID,String documentID, Date timestamp, String response){
this.title = title;
this.body = body;
this.username = username;
this.userID = userID;
this.documentId = documentID;
this.timestamp = timestamp;
this.response = response;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getUsername() {
return username;
}
public String getUserID() {
return userID;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
public void setUsername(String username) {
this.username = username;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getDocumentId() {
return documentId;
}
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
|
import java.util.*;
class JumpingNumber {
public List<String> solve(int start, int end) {
int len = 0;
int num = end;
while (num > 0) {
num /= 10;
len++;
}
List<String> result = new LinkedList<>();
dfs(result, start, end, len, 0);
bfs(result, start, end);
return result;
}
private void bfs(List<String> result, int start, int end) {
Queue<Integer> queue = new LinkedList();
for (int i = 1; i <= 9; i++) {
queue.offer(i);
}
while (!queue.isEmpty()) {
Integer top = queue.poll();
if (top >= start && top <= end) {
result.add(String.valueOf(top));
}
int last = top % 10;
if (last == 0) {
if (top * 10 + 1 <= end) {
queue.offer(top * 10 + 1);
}
} else if (last == 9) {
if (top * 10 + 8 <= end) {
queue.offer(top * 10 + 8);
}
} else {
if (top * 10 + last + 1<= end) {
queue.offer(top * 10 + last + 1);
}
if (top * 10 + last - 1 <= end) {
queue.offer(top * 10 + last - 1);
}
}
}
}
private void dfs(List<String> result, int start, int end, int len, int num) {
if (num >= start && num <= end) {
result.add(String.valueOf(num));
}
if (len == 0) {
return;
}
if (num == 0) {
for (int i = 1; i <= 9; i++) {
dfs(result, start, end, len - 1, i);
}
return;
}
int last = num % 10;
if (last == 0) {
dfs(result, start, end, len - 1, num * 10 + 1);
} else if (last == 9) {
dfs(result, start, end, len - 1, num * 10 + 8);
} else {
dfs(result, start, end, len - 1, num * 10 + last + 1);
dfs(result, start, end, len - 1, num * 10 + last - 1);
}
}
public static void main(String[] args) {
JumpingNumber test = new JumpingNumber();
int start = Integer.parseInt(args[0]);
int end = Integer.parseInt(args[1]);
System.out.println(String.join(",", test.solve(start, end)));
}
}
|
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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.apache.log4j;
import org.slf4j.MDC;
import java.util.Stack;
/**
* A log4j's NDC implemented in terms of SLF4J MDC primitives.
*
* @since SLF4J 1.6.0
*/
public class NDC {
public final static String PREFIX = "NDC";
public static void clear() {
int depth = getDepth();
for (int i = 0; i < depth; i++) {
String key = PREFIX + i;
MDC.remove(key);
}
}
@SuppressWarnings("rawtypes")
public static Stack cloneStack() {
return null;
}
@SuppressWarnings("rawtypes")
public static void inherit(Stack stack) {
}
static public String get() {
return null;
}
public static int getDepth() {
int i = 0;
while (true) {
String val = MDC.get(PREFIX + i);
if (val != null) {
i++;
} else {
break;
}
}
return i;
}
public static String pop() {
int next = getDepth();
if (next == 0) {
return "";
}
int last = next - 1;
String key = PREFIX + last;
String val = MDC.get(key);
MDC.remove(key);
return val;
}
public static String peek() {
int next = getDepth();
if (next == 0) {
return "";
}
int last = next - 1;
String key = PREFIX + last;
String val = MDC.get(key);
return val;
}
public static void push(String message) {
int next = getDepth();
MDC.put(PREFIX + next, message);
}
static public void remove() {
clear();
}
static public void setMaxDepth(int maxDepth) {
}
}
|
package Module2_OOP.ExtraTasks.Lesson4.E_ticket;
public class Order {
private int orderId;
private User user;
private Ticket ticket;
public Order(int orderId, User user, Ticket ticket) {
this.orderId = orderId;
this.user = user;
this.ticket = ticket;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Ticket getTicket() {
return ticket;
}
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", user=" + user +
", ticket=" + ticket +
'}';
}
}
|
package com.realcom.helloambulance.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.realcom.helloambulance.dao.AddMembersUserDao;
import com.realcom.helloambulance.pojo.AddFamilyMembers;
@Repository("addmemberservices")
public class AddMemberServices {
@Autowired
AddMembersUserDao addusermembersdao;
public void addMembersUserMethodService(AddFamilyMembers add) {
addusermembersdao.addfamilymembersmethoddao(add);
}
public int GetId(String Email_Id) {//for foregn key id
System.out.println("service"+Email_Id);
return addusermembersdao.GetId(Email_Id);
}
public String getUserName(int userid) {
return addusermembersdao.getUserName(userid);
}
public List<AddFamilyMembers> listaddmembers(int userid) {
return addusermembersdao.listfamilymembers(userid);
}
/********************* mailid exits *********************************************/
@Transactional
public Boolean isEmailExist(String emailId,int id) {
return addusermembersdao.isEmailExist(emailId,id);
}
////////////////////****mobile exits/////////////////////////////////////////////////
@Transactional
public Boolean isMobileExist(String mobileNumber,int id) {
return addusermembersdao.isMobileExist(mobileNumber,id);
}
public List<AddFamilyMembers> addmembersdetails(String name) {
return addusermembersdao.membersdetails(name);
}
public void UpdateMember(String id) {
addusermembersdao.updatememberDao(id);
}
public List<AddFamilyMembers> EditMember(int id) {
return addusermembersdao.editmemberdetails( id);
}
public void updateMemberprofile(int id,AddFamilyMembers addmember) {
addusermembersdao.updatedmember(id,addmember);
}
} |
package com.example.hellosharedpreferences;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class ApplicationPreferences {
private static SharedPreferences mSharedPref;
static final String KEYNAME = "nombre";
private ApplicationPreferences() {
}
// Asigna la base de datps que se llama MYPREFS
public static void init(Context context) {
if(mSharedPref == null){
mSharedPref = context.getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);
}
}
// guarda lo que hay dentro del edittext
public static void saveName(String name) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(KEYNAME, name);
prefsEditor.apply();
}
public static String loadName() {
return mSharedPref.getString(KEYNAME, "");
}
}
|
import java.util.concurrent.LinkedBlockingQueue;
public class CustomThreadPool {
private final LinkedBlockingQueue<Runnable> queue;
private final int poolSize;
private final Worker[] workers;
private volatile boolean isShutdown = false;
public CustomThreadPool(int poolSize) {
this.poolSize = poolSize;
queue = new LinkedBlockingQueue<>();
workers = new Worker[poolSize];
for(int i=0;i<poolSize;i++){
workers[i] = new Worker();
workers[i].start();
}
}
public void execute(Runnable task) {
if(!isShutdown) {
synchronized (queue) {
queue.add(task);
queue.notify();
}
}
}
public void shutdown(){
isShutdown = true;
/*while(true) {
while (!queue.isEmpty()) {
}
for(int i=0;i<poolSize;i++){
workers[i].interrupt();
}
}*/
}
private class Worker extends Thread{
public void run(){
Runnable task;
while(!isShutdown) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName());
task = queue.poll();
}
try {
task.run();
} catch (Exception e) {
}
}
}
}
}
|
package com.kashu.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kashu.domain.Product;
import com.kashu.domain.temp.ProductSearchParams;
import com.kashu.pager.Page;
import com.kashu.repository.ProductRepository;
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public Product insert(Product product) {
Product p = null;
try{
p = productRepository.insert(product);
}catch(Exception e){
e.printStackTrace();
}
return p;
}
@Override
public Integer insert(List<Product> products) {
Integer insert_rows_count = 0;
try{
insert_rows_count = productRepository.insert(products);
}catch(Exception e){
e.printStackTrace();
}
return insert_rows_count;
}
@Override
public Product update(Product product) {
Product p = null;
try{
p = productRepository.update(product);
}catch(Exception e){
e.printStackTrace();
}
return p;
}
@Override
public Boolean delete(Long id) {
Boolean b = false;
try{
b = productRepository.delete(id);
}catch(Exception e){
e.printStackTrace();
}
return b;
}
public ProductRepository getProductRepository() {
return productRepository;
}
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}
@Override
public Long count(ProductSearchParams searchParams) {
Long result = 0l;
try{
result = productRepository.count(searchParams);
}catch(Exception e){
e.printStackTrace();
}
return result;
}
@Override
public Boolean isThisPageExisted(ProductSearchParams searchParams) {
Integer totalRows = count(searchParams).intValue();
Integer pageNumber = searchParams.getPageNumber(); // user requested page number
Integer pageSize = searchParams.getPageSize();
Integer maxPageNumber = (totalRows % pageSize == 0) ? (totalRows / pageSize) : ((totalRows / pageSize) + 1);
return ((pageNumber > 0)&&(pageNumber <= maxPageNumber)) ? true : false;
}
@Override
public Page<Product> getPage(ProductSearchParams searchParams) {
Page<Product> page = new Page<Product>(searchParams);
List<Product> products = null;
Long totalRows = 0l;
try{
products = productRepository.find(searchParams);
totalRows = productRepository.count(searchParams);
}catch(Exception e){
e.printStackTrace();
}
page.setElements(products);
page.setTotalRows(totalRows);
return page;
}
@Override
public Product find(Long id) {
Product product = null;
try{
product = productRepository.find(id);
}catch(Exception e){
e.printStackTrace();
}
return product;
}
}
|
package project.graphic;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import project.object.C_Urbano;
import project.object.Settore;
public class GestionFrame extends JFrame{
private static final long serialVersionUID = 1L;
private C_Urbano cUrbano;
private int cooX = -1;
private int cooY = -1;
private JTextArea settoreSelezionato;
private boolean flag = false;
public GestionFrame(C_Urbano cUrbano) {
this.cUrbano = cUrbano;
add(infoSettSelected(), BorderLayout.NORTH);
add(sectorPanel());
add(controlPanel(), BorderLayout.SOUTH);
}
private JPanel infoSettSelected() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Settore Selezionato:");
settoreSelezionato = new JTextArea(1, 2);
panel.add(label);
panel.add(settoreSelezionato);
return panel;
}
private JPanel sectorPanel() {
JPanel generalPanel = new JPanel();
generalPanel.setLayout(new GridLayout(2, 3));
for(int i = 0; i < C_Urbano.ROWS; i++)
for(int j = 0; j < C_Urbano.COLS; j++) {
SectorPanel sect = new SectorPanel(this.cUrbano.getSettore(i, j), i, j);
generalPanel.add(sect);
}
return generalPanel;
}
private JPanel controlPanel() {
JPanel controlPanel = new JPanel();
controlPanel.add(invecchiamentoButton());
controlPanel.add(catastrofeButton());
controlPanel.add(restaurazione());
controlPanel.add(modificaButton());
return controlPanel;
}
private JButton invecchiamentoButton() {
JButton invecchiamento = new JButton("Invecchiamento");
invecchiamento.addActionListener((y)->{
cUrbano.simulazioneTempo();
});
return invecchiamento;
}
private JButton catastrofeButton() {
JButton catastrofe = new JButton("Catastrofe");
catastrofe.addActionListener((y)->{
cUrbano.catastrofe();
});
return catastrofe;
}
private JButton restaurazione() {
JButton restaura = new JButton("Restaurazione Settore");
restaura.addActionListener((z)->{
if(flag == true)
cUrbano.getSettore(cooX, cooY).restaurazioneSettore();
else
System.out.println("Settore non Selezionato");
});
return restaura;
}
private JButton modificaButton() {
JButton modifica = new JButton("Modifica");
modifica.addActionListener((y)->{
if(flag) {
ModificaFrame modificaFrame = new ModificaFrame(cUrbano.getSettore(cooX, cooY));
modificaFrame.setVisible(true);
modificaFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
modificaFrame.setSize(500, 500);
}
});
return modifica;
}
class SectorPanel extends JPanel{
private static final long serialVersionUID = 1L;
private int x;
private int y;
private Settore settore;
public SectorPanel(Settore sect, int x, int y) {
int z;
this.settore = sect;
this.x = x;
this.y = y;
if(x != 0) {
z = (x*Settore.COLS) + y;
}
else
z = y+1;
JLabel label = new JLabel("" + z);
add(label);
setBorder(new EtchedBorder());
setBackground(Color.red);
addMouseListener(new MousePath());
}
public Settore getLotto() {
return this.settore;
}
public int getRow() {
return this.x;
}
public int getCol() {
return this.y;
}
public void setRow(int x) {
this.x = x;
}
public void setCol(int y) {
this.y = y;
}
public void setLotto(Settore sect) {
this.settore = sect;
}
class MousePath implements MouseListener{
public void mouseClicked(MouseEvent e) {
cooX = getRow();
cooY = getCol();
flag = true;
int z;
if(x != 0) {
z = (x*Settore.COLS) + y;
}
else
z = y+1;
settoreSelezionato.setText(z+"");
}
public void mouseEntered(MouseEvent e) {
setBackground(Color.green);
}
public void mouseExited(MouseEvent e) {
setBackground(Color.red);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
}
|
package com.qd.mystudy.helloworld;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Created by liqingdong on 2014/8/30.
*/
public class HelloWorld {
static final private Log log = LogFactory.getLog(HelloWorld.class);
static public void main(String[] args)
{
System.out.println("hello world");
log.debug("debug");
log.info("info");
CanalPacket.RowData.Builder rd = CanalPacket.RowData.newBuilder();
rd.setEventType(CanalPacket.EventType.INSERT);
CanalPacket.FieldData.Builder fd = CanalPacket.FieldData.newBuilder();
fd.setEventType(CanalPacket.EventType.INSERT);
fd.setIsKey(true);
fd.setIsUpdate(true);
fd.setName("abc");
fd.setOldValue(com.google.protobuf.ByteString.copyFromUtf8("abc"));
rd.addSupportedCompressions(fd);
CanalPacket.FieldData.Builder fd1 = CanalPacket.FieldData.newBuilder();
fd1.setEventType(CanalPacket.EventType.INSERT);
fd1.setIsKey(true);
fd1.setIsUpdate(false);
fd1.setName("def");
fd1.setOldValue("11.1");
System.out.println(fd1.getOldValue());
CanalPacket.FieldData bfd1 = fd1.build();
byte[] bbfd1 = bfd1.toByteArray();
try {
CanalPacket.FieldData bbbfd1 = CanalPacket.FieldData.parseFrom(bbfd1);
System.out.println(bbbfd1.getOldValue());
bfd1.hashCode();
if(bfd1.equals(bbbfd1)){
System.out.println("same");
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
rd.addSupportedCompressions(fd1);
System.out.println(rd.toString());
HelloWorldRuning.start();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("stop...");
HelloWorldRuning.stop();
try {
HelloWorldRuning.thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
}
});
boolean running = true;
while (running) {
String str1 = null;
int a1 = 1, a2 = 0;
int c = a1 / a2;
}
try {
// throw new RuntimeException();
throw new OutOfMemoryError();
// str1.charAt(0);
}
catch (Throwable e){
e.printStackTrace();
}
System.out.println("main exit");
}
}
|
package com.hs.doubaobao.model.Approval;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hs.doubaobao.R;
import com.hs.doubaobao.base.AppBarActivity;
import com.hs.doubaobao.bean.ApprovalBean;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 作者:zhanghaitao on 2017/9/15 15:50
* 邮箱:820159571@qq.com
*
* @describe:审批界面
*/
public class ApprovalActivity extends AppBarActivity implements ApprovalContract.View {
private ApprovalContract.Presenter presenter;
private Map<String, Object> map;
private Button mNotPass;
private EditText mText;
private Button mClose;
private Button mSubmit;
private LinearLayout dialogView;
private String showRightType;
private String id;
private int type;
private TextView mOpinion;
private TextView mQuota;
private EditText mOpinionText;
private Button mPass;
private Button mSave;
private EditText mQuotaText;
private String mApproveContent;
private String mRiskControl;
private String mManagerRation;
private int mApproveStatus;
private int mApprove = 0;
private LinearLayout mQuotaItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_approval);
setTitleTextColor(R.color.textAggravating);
setStatusBarBackground(R.drawable.ic_battery_bg);
isShowRightView(false);
initView();
Intent intent = getIntent();
showRightType = intent.getStringExtra("ShowRightType");
mApproveStatus = intent.getIntExtra("ApproveStatus", 0);
mApproveContent = intent.getStringExtra("Content");
mRiskControl = intent.getStringExtra("riskControl");
mManagerRation = intent.getStringExtra("managerRation");
id = intent.getStringExtra("ID");
if (TextUtils.isEmpty(showRightType)) {
} else
if (showRightType.equals("RISK")) {
setTitle(getString(R.string.risk_control));
mOpinion.setText("风控意见:");
mQuota.setText("风控定额:");
if (mApproveStatus == 1) {
mOpinionText.setText(mApproveContent);
mQuotaText.setText(mRiskControl);
}
type = 3;
} else
if (showRightType.equals("MANAGER")) {
setTitle(getString(R.string.general_manager));
mOpinion.setText("总经理意见:");
mQuota.setText("总经理定额:");
if (mApproveStatus == 1) {
mOpinionText.setText(mApproveContent);
mQuotaText.setText(mManagerRation);
}
type = 4;
}else
if (showRightType.equals("DEPARTMENT")) {
setTitle("部门初审");
mOpinion.setText("部门经理意见:");
mQuotaItem.setVisibility(View.GONE);
type = 7;
} else
if (showRightType.equals("STORE")) {
setTitle("门店一审");
mOpinion.setText("门店意见:");
mQuotaItem.setVisibility(View.GONE);
type = 1;
}
mClose.setOnClickListener(this);
mSubmit.setOnClickListener(this);
mNotPass.setOnClickListener(this);
mPass.setOnClickListener(this);
mSave.setOnClickListener(this);
dialogView.setOnClickListener(this);
//将Presenter和View进行绑定
new ApprovalPresener(this, this);
}
private void loadData(int status, String content, String riskControl, String remark) {
map = new LinkedHashMap<>();
map.put("id", id);//借款id
map.put("type", type);//1:初审人员审批,2:家访审批,3:风控人员审批,:4:总经理审批
map.put("status", status);//1:同意,2:不同意,3:保存
if (!TextUtils.isEmpty(content)) {
map.put("content", content);//通过审批内容
}
if (!TextUtils.isEmpty(riskControl)) {
if (riskControl.startsWith(".")) {
riskControl = "0" + riskControl;
}
map.put("riskControl", riskControl);//通过的定额
}
if (!TextUtils.isEmpty(remark)) {
map.put("remark", remark);//不通过的理由
}
presenter.getData(map);
}
private void initView() {
mOpinion = (TextView) findViewById(R.id.approval_opinion);
mQuota = (TextView) findViewById(R.id.approval_quota);
mQuotaItem = (LinearLayout) findViewById(R.id.approval_quota_item);
mOpinionText = (EditText) findViewById(R.id.approval_opinion_text);
mQuotaText = (EditText) findViewById(R.id.approval_quota_text);
mPass = (Button) findViewById(R.id.approval_pass);
mSave = (Button) findViewById(R.id.approval_save);
mNotPass = (Button) findViewById(R.id.approval_not_pass);
dialogView = (LinearLayout) findViewById(R.id.approval_not_pass_reason);
mText = (EditText) findViewById(R.id.dailog_reason);
mClose = (Button) findViewById(R.id.dialog_close);
mSubmit = (Button) findViewById(R.id.dialog_submit);
}
@Override
public void onClick(View v) {
super.onClick(v);
int id = v.getId();
String content = mOpinionText.getText().toString().trim();
String riskControl = mQuotaText.getText().toString().trim();
String remark = mText.getText().toString().trim();
switch (id) {
case R.id.approval_pass:
//通过
mApprove = 1;
checkNull(1, content, riskControl);
break;
case R.id.approval_save:
//保存
// loadData(3,content,riskControl,"");
mApprove = 3;
checkNull(3, content, riskControl);
break;
case R.id.approval_not_pass:
dialogView.setVisibility(View.VISIBLE);
mText.requestFocus();
break;
case R.id.dialog_submit:
//不通过
if (TextUtils.isEmpty(remark)) {
Toast.makeText(this, "请填写不通过理由", Toast.LENGTH_SHORT).show();
} else {
mApprove = 2;
loadData(2, "", "", remark);
}
break;
case R.id.dialog_close:
dialogView.setVisibility(View.GONE);
break;
case R.id.approval_not_pass_reason:
dialogView.setVisibility(View.GONE);
break;
}
}
void checkNull(int status, String content, String riskControl) {
if (status != 3 && TextUtils.isEmpty(content)) {
Toast.makeText(this, "请填写意见", Toast.LENGTH_SHORT).show();
} else if (status != 3
&& TextUtils.isEmpty(riskControl)
&&(showRightType.equals("MANAGER")||showRightType.equals("RISK"))) {
Toast.makeText(this, "请填写金额", Toast.LENGTH_SHORT).show();
} else {
loadData(status, content, riskControl, "");
}
}
@Override
public void setData(ApprovalBean bean) {
String[] aar = {"您没有任何操作", "审批成功", "审批成功", "保存成功"};
Toast.makeText(this, aar[mApprove], Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void setError(String text) {
String[] aar = {"您没有任何操作", "审批失败", "审批失败", "保存成功"};
Toast.makeText(this, aar[mApprove] + ",请稍后再试", Toast.LENGTH_SHORT).show();
}
@Override
public void setPresenter(ApprovalContract.Presenter presenter) {
this.presenter = presenter;
}
}
|
package com.isen.regardecommeilfaitbeau;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class today_weatherFragment extends Fragment {
static TextView temperature_id;
static TextView city_id;
static TextView weatherDescription_id;
TextView tempUnit_id;
static ImageView weatherDescriptionIcon_id;
EditText cityInput_id;
static today_weatherFragment instance;
public static today_weatherFragment getInstance() {
if(instance==null)
instance=new today_weatherFragment();
return instance;
}
public today_weatherFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View itemView=inflater.inflate(R.layout.fragment_today_weather, container, false);
weatherDescriptionIcon_id=(ImageView)itemView.findViewById(R.id.weatherDescriptionIcon_id);
temperature_id=(TextView) itemView.findViewById(R.id.temperature_id);
city_id=(TextView)itemView.findViewById(R.id.city_id);
weatherDescription_id=(TextView)itemView.findViewById(R.id.weatherDescription_id);
tempUnit_id=(TextView)itemView.findViewById(R.id.tempUnit_id);
return itemView;
}
}
|
package com.tencent.mm.plugin.freewifi.ui;
import com.tencent.mm.protocal.c.ep;
public class FreeWifiFrontPageUI$b {
public ep jng;
}
|
package com.tencent.mm.pluginsdk.f;
import com.tencent.mm.a.e;
import com.tencent.mm.sdk.platformtools.x;
class i$1 implements Runnable {
i$1() {
}
public final void run() {
x.i("MicroMsg.UpdateUtil", "delete apk file. on worker thread");
e.co(i.ccn());
}
}
|
package com.example.roushan.railwayenquiry.Activities;
import android.app.DatePickerDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.example.roushan.railwayenquiry.Fragments.TrainsBtnStnFragment;
import com.example.roushan.railwayenquiry.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class TrainBtnStationsActivity extends AppCompatActivity {
private EditText setFromCode;
private EditText setToCode;
private EditText setDate;
private Button search;
private SimpleDateFormat dateFormatter;
private SimpleDateFormat jsonDate;
private DatePickerDialog setDateDialog;
public static String getFromCode;
public static String getToCode;
public static String getDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_train_btn_stations);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
jsonDate = new SimpleDateFormat("dd-MM", Locale.US);
setViewsToActivity();
onClickSetDate();
onClickSearchButton();
}
private void setViewsToActivity() {
setFromCode = (EditText) findViewById(R.id.source_stationCode);
setToCode = (EditText) findViewById(R.id.destination_stationCode);
setDate = (EditText) findViewById(R.id.set_date);
search = (Button) findViewById(R.id.search_trains);
}
private void onClickSetDate() {
setDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setDateDialog.show();
}
});
Calendar myCalendar = Calendar.getInstance();
setDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, month, dayOfMonth);
setDate.setText(dateFormatter.format(newDate.getTime()));
getDate = jsonDate.format(newDate.getTime());
}
}, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
}
private void onClickSearchButton() {
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isNetworkAvailable()) {
getFromCode = setFromCode.getText().toString();
getToCode = setToCode.getText().toString();
String checkDate = setDate.getText().toString();
if(getFromCode.length() != 3) {
setFromCode.setError("Please enter correct code.");
}
if (getToCode.length() != 3) {
setToCode.setError("Please enter correct code.");
}
if (checkDate.isEmpty()) {
Toast.makeText(TrainBtnStationsActivity.this, "Date field is not set.", Toast.LENGTH_SHORT).show();
}
if (getFromCode.length() == 3 && getToCode.length() == 3 && !checkDate.isEmpty()) {
TrainsBtnStnFragment fragment = new TrainsBtnStnFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.trains_fragment_container, fragment);
transaction.commit();
}
} else {
Toast.makeText(TrainBtnStationsActivity.this, "Network unavailable. Please check and try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
}
|
package com.yuliia.vlasenko.imagesearcher.api.auth;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class AuthRequest {
private String apiKey;
}
|
import javax.swing.*;
import java.awt.*;
public class WaveHandler {
private String message;
private int currentWave;
private int messageX;
private int messageY;
private int messageFade;
public WaveHandler(){
//testing purposes
currentWave = 1; //subtract 1 to get level
currentWave--; //don't make fun of me
}
public void startWave(){
currentWave++; //starts at 1
setMessage("Level "+currentWave,-1);
switch(currentWave){
case(1): //6 enemy1
Game.enemies.addEnemy(Window.getWidth()/2, -500, new Enemy1());
Game.enemies.addEnemy(-1, -1000, new Enemy1());
Game.enemies.addEnemy(-1, -1500, new Enemy1());
Game.enemies.addEnemy(-1, -2000, new Enemy1());
break;
case(2): //8 enemy2
Game.enemies.addEnemy(100,-500, new Enemy2());
Game.enemies.addEnemy(380,-750, new Enemy2());
Game.enemies.addEnemy(100,-1000, new Enemy2());
Game.enemies.addEnemy(380,-1250, new Enemy2());
break;
case(3):
Game.enemies.addEnemy(-1,-300, new Enemy3());
Game.enemies.addEnemy(-1,-400, new Enemy3());
Game.enemies.addEnemy(-1,-500, new Enemy3());
Game.enemies.addEnemy(-1,-600, new Enemy3());
break;
case(4):
Game.enemies.addEnemy(-1,-500, new Enemy4());
Game.enemies.addEnemy(-1,-1000, new Enemy4());
Game.enemies.addEnemy(-1,-1500, new Enemy4());
Game.enemies.addEnemy(-1,-2000, new Enemy4());
break;
case(5):
for (int i = 0; i < 15; i++){
Game.enemies.addEnemy((Window.getWidth()/2), -(i*50), new Enemy5());
}
Game.enemies.addEnemy(Window.getWidth()/2,-500,new EnemyBoss1());
break;
case(6):
for (int i = 0; i < 10; i++){
Game.enemies.addEnemy((Window.getWidth()/2), -(i*250), new Enemy6());
}
break;
case(7):
break;
case(8):
break;
case(9):
break;
case(10):
break;
}
}
public void endWave(){
Window.panel.setPanelState(0);
Window.panel.editor.setMoney(Game.player.getMoney());
Game.player.resetFireBullet();
Game.player.setShieldOn(false);
Game.bullets.removeAll();
}
public void gameOver(){
endWave();
currentWave--;
Window.panel.game.setGameOver(true);
//reset player gameOver state to end loop
//Game.player.setHeartPosition("bottom");
//Game.player.resetPlayerMatrix();
Window.panel.editor.setMatrix(Game.player.getMatrix());
//Game.player.resetMoney();
Game.player.resetHeart();
Game.player.setShield(0);
//Game.player.resetCannon();
Game.enemies.removeAll();
}
public void draw(Graphics2D g){
if (messageFade > 0){
g.setColor(new Color(255,255,255,messageFade));
g.drawString(message,messageX,messageY);
}
}
public void update(){
if (messageFade-2 > 0) messageFade-=2;
else messageFade = 0;
messageY--;
}
public void setMessage(String message, int x){
this.message=message;
if (x == -1) messageX = 210;
else messageX = x;
messageY = Window.getHeight()/2;
messageFade = 255;
}
}
|
package mycommands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import commandManagement.BaseSubCommandHandler;
import commandManagement.SubCommand;
public class HelpCommand extends SubCommand {
public HelpCommand(BaseSubCommandHandler hrbBaseHandler) {
super("help", "/hrb help", hrbBaseHandler, "?");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args,
int depth) {
// TODO Auto-generated method stub
return false;
}
}
|
package com.igitras.codegen.common.next;
import com.igitras.codegen.common.next.annotations.NotNull;
/**
* Created by mason on 1/5/15.
*/
public interface CgDirectoryContainer extends CgNamedElement {
/**
* Returns the array of all directories (under all source roots in the project)
* corresponding to the package.
*
* @return the array of directories.
*/
@NotNull
CgDirectory[] getDirectories();
}
|
package com.doublea.talktify.backgroundTools;
/**
* Interface used to listen for events and wait for them to complete
*/
public interface CompletionListener {
public void onStart(); // When task starts
public void onSuccess(); // When task succeeds
public void onFailure(); // When task fails
}
|
package com.hebe.vo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class DetailDomain extends DiaryEntity {
private String nickname;
private String introduction;
private String profileimg;
private int isFav;
}
|
package it.unibz.testhunter.tests;
import it.unibz.testhunter.CommandFactory;
import it.unibz.testhunter.action.ActionAddProject;
import it.unibz.testhunter.action.ActionCheckProject;
import it.unibz.testhunter.action.ActionCommandHelp;
import it.unibz.testhunter.action.ActionHelp;
import it.unibz.testhunter.action.ActionListPlugins;
import it.unibz.testhunter.action.ActionListProjects;
import it.unibz.testhunter.action.ActionProject;
import it.unibz.testhunter.action.ICommandAction;
import it.unibz.testhunter.cmd.CmdAddProject;
import it.unibz.testhunter.cmd.CmdCheckProject;
import it.unibz.testhunter.cmd.CmdListCommands;
import it.unibz.testhunter.cmd.CmdListPlugins;
import it.unibz.testhunter.cmd.CmdListProjects;
import it.unibz.testhunter.cmd.CmdProject;
import it.unibz.testhunter.cmd.Command;
import it.unibz.testhunter.shared.TException;
import it.unibz.testhunter.svc.EntityManagerTransactionalInterceptor;
import it.unibz.testhunter.svc.SvcPlugin;
import it.unibz.testhunter.svc.SvcPluginDirectoryJar;
import it.unibz.testhunter.svc.Transactional;
import java.net.URL;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
public class TestCommands {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Injector injector = Guice.createInjector(new AbstractModule() {
// Actions Module
@Override
protected void configure() {
bind(ICommandAction.class).annotatedWith(
Names.named("cmd-help")).to(ActionCommandHelp.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdListProjects.name)).to(
ActionListProjects.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdAddProject.name)).to(
ActionAddProject.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdListCommands.name)).to(ActionHelp.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdCheckProject.name)).to(
ActionCheckProject.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdListPlugins.name)).to(
ActionListPlugins.class);
bind(ICommandAction.class).annotatedWith(
Names.named(CmdProject.name)).to(ActionProject.class);
}
}, new AbstractModule() {
// Module Services
@Override
protected void configure() {
EntityManagerTransactionalInterceptor interceptor = new EntityManagerTransactionalInterceptor();
bind(EntityManager.class).toInstance(
Persistence.createEntityManagerFactory(
"testhunter_test").createEntityManager());
requestInjection(interceptor);
bind(SvcPlugin.class).to(SvcPluginDirectoryJar.class);
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(Transactional.class),
interceptor);
}
});
CommandFactory.registerCommandProvider(CmdListCommands.name, injector
.getInstance(CmdListCommands.class).getProvider());
CommandFactory.registerCommandProvider(CmdListProjects.name, injector
.getInstance(CmdListProjects.class).getProvider());
CommandFactory.registerCommandProvider(CmdAddProject.name, injector
.getInstance(CmdAddProject.class).getProvider());
CommandFactory.registerCommandProvider(CmdListPlugins.name, injector
.getInstance(CmdListPlugins.class).getProvider());
CommandFactory.registerCommandProvider(CmdCheckProject.name, injector
.getInstance(CmdCheckProject.class).getProvider());
CommandFactory.registerCommandProvider(CmdProject.name, injector
.getInstance(CmdProject.class).getProvider());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void checkRegisteredCommands() {
System.out.println("checkRegisteredCommands:");
for (String cmd : CommandFactory.getRegisteredCommands()) {
System.out.println(cmd);
}
System.out.flush();
}
@Test
public void cmdHelp() throws Exception {
Command cmd = CommandFactory.createCommand("help");
cmd.execute();
}
@Test
public void cmdAddProjectNoOptions() throws Exception {
Command cmd = CommandFactory.createCommand("add-project");
try {
cmd.execute();
} catch (TException e) {
System.out.println(e.getUserMsg());
}
}
@Test
public void cmdAddProjectHelp() throws Exception {
Command cmd = CommandFactory.createCommand("add-project");
cmd.setHelpOption(true);
cmd.execute();
}
@Test
public void cmdAddProject() throws Exception {
Command cmd = CommandFactory.createCommand("add-project");
cmd.setCmdOption("name", "test project");
cmd.setCmdOption("url", new URL(
"http://hudson.testrun.org/job/pytest-xdist"));
cmd.setCmdOption("plugin",
UUID.fromString("b398d1ed-1251-471d-8fc3-e01f6169649e"));
cmd.execute();
}
@Test
public void cmdListProjects() throws Exception {
Command cmd = CommandFactory.createCommand("list-projects");
cmd.execute();
}
@Test
public void cmdListPlugins() throws Exception {
Command cmd = CommandFactory.createCommand("list-plugins");
cmd.execute();
}
@Test
public void cmdChkProject() throws Exception {
Command cmd = CommandFactory.createCommand("chk-project");
cmd.setCmdOption("id", new Long(1));
cmd.execute();
}
@Test
public void cmdGrabProject() throws Exception {
Command cmd = CommandFactory.createCommand("project");
cmd.setCmdOption("id", new Long(1));
cmd.setCmdOption("clear", new Boolean(true));
cmd.execute();
}
}
|
package pl.luwi.series.tasks;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import pl.luwi.series.reducer.OrderedPoint;
import pl.luwi.series.reducer.PointSegment;
public class ReduceTask extends CommunicatingThread<LinkedBlockingQueue<PointSegment>, LinkedBlockingQueue<PointSegment>> {
double epsilon;
ConcurrentHashMap<Integer, OrderedPoint<?>> results;
public ReduceTask(LinkedBlockingQueue<PointSegment> inputQueue, LinkedBlockingQueue<PointSegment> outputQueue, double epsilon, ConcurrentHashMap<Integer, OrderedPoint<?>> results) {
super(inputQueue, outputQueue);
this.epsilon = epsilon;
this.results = results;
}
@Override
public void process(LinkedBlockingQueue<PointSegment> inputQueue, LinkedBlockingQueue<PointSegment> outputQueue)
throws Exception {
PointSegment segment = null;
while ((segment = inputQueue.poll(timeOut, TimeUnit.MICROSECONDS)) != null){
if(segment.bestdistance > epsilon){
for (PointSegment pointSegment : segment.split()) {
outputQueue.add(pointSegment);
}
} else {
for (OrderedPoint<?> point : segment.asList()) {
results.put(point.getIndex(), point);
}
}
}
}
}
|
package com.smartwerkz.bytecode.vm.methods;
import com.smartwerkz.bytecode.vm.Frame;
import com.smartwerkz.bytecode.vm.OperandStack;
import com.smartwerkz.bytecode.vm.RuntimeDataArea;
public class SignalRaise0 implements NativeMethod {
@Override
public void execute(RuntimeDataArea rda, Frame frame, OperandStack otherOperandStack) {
}
}
|
import java.util.Scanner;
public class RecursionFIB {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
scn.close();
System.out.println(fib(num));
}
public static int fib(int n) {
if(n==1 || n==2) {
return 1;
}
if(n==0) {
return n;
}
int fnm1 = fib(n-1);
int fnm2 = fib(n-2);
int fn = fnm2 + fnm1 ;
return fn;
}
}
|
package edu.byu.cs.superasteroids.model;
/**
* Created by Azulius on 2/23/16.
*/
public class ShipPartAttachable extends ShipPart {
private int attachX;
private int attachY;
public int getAttachX() {
return attachX;
}
public void setAttachX(int attachX) {
this.attachX = attachX;
}
public int getAttachY() {
return attachY;
}
public void setAttachY(int attachY) {
this.attachY = attachY;
}
}
|
package com.egen.order.dao;
import com.egen.order.entity.PaymentInfo;
import com.egen.order.entity.ShippingAddress;
import org.springframework.data.repository.CrudRepository;
public interface PaymentInfoRepository extends CrudRepository<PaymentInfo, Long> {
}
|
package com.tyss.cg.exceptions;
import java.util.Scanner;
public class CustomExceptionTester2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = scanner.nextInt();
scanner.close();
try {
System.out.println(10 / num);
} catch (Exception e) {
throw new InvalidNumCustomException("Any Message");
}
System.out.println("change 0please");
}
}
|
package crosby.binary.file;
import java.io.IOException;
import java.io.InputStream;
import com.google.protobuf.ByteString;
/**
* A FileBlockPosition that remembers what file this is so that it can simply be
* dereferenced
*/
public class FileBlockReference extends FileBlockPosition {
/**
* Convenience cache for storing the input this reference is contained
* within so that it can be cached
*/
protected InputStream input;
protected FileBlockReference(String type, ByteString indexdata) {
super(type, indexdata);
}
public FileBlock read() throws IOException {
return read(input);
}
static FileBlockPosition newInstance(FileBlockBase base, InputStream input,
long offset, int length) {
FileBlockReference out = new FileBlockReference(base.type,
base.indexdata);
out.datasize = length;
out.data_offset = offset;
out.input = input;
return out;
}
}
|
package com.tencent.mm.plugin.account.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
class LoginHistoryUI$18 implements OnCancelListener {
final /* synthetic */ LoginHistoryUI eRA;
LoginHistoryUI$18(LoginHistoryUI loginHistoryUI) {
this.eRA = loginHistoryUI;
}
public final void onCancel(DialogInterface dialogInterface) {
}
}
|
package org.jboss.perf.test.server.controller;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.inject.Produces;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.jboss.perf.test.server.controller.forms.UnitForm;
import org.jboss.perf.test.server.dao.AttrDao;
import org.jboss.perf.test.server.dao.AttrResultDao;
import org.jboss.perf.test.server.dao.ThresholdDao;
import org.jboss.perf.test.server.dao.UnitDao;
import org.jboss.perf.test.server.model.Attr;
import org.jboss.perf.test.server.model.Threshold;
import org.jboss.perf.test.server.model.Unit;
@ManagedBean
@ViewScoped
public class UnitBean implements Serializable {
private static final long serialVersionUID = 1L;
@EJB(lookup="java:app/PerfServer/UnitDaoImpl")
private UnitDao unitDao;
@EJB (lookup="java:app/PerfServer/AttrResultDaoImpl")
private AttrResultDao attrResultDao;
@EJB(lookup="java:app/PerfServer/AttrDaoImpl")
private AttrDao attrDao;
@EJB(lookup="java:app/PerfServer/ThresholdDaoImpl")
private ThresholdDao thresholdDao;
@ManagedProperty(value="#{unitForm}")
private UnitForm form;
@Named
@Produces
private List<Unit> units;
@PostConstruct
public void init() {
units = unitDao.getUnits();
}
public void setForm(UnitForm form) {
this.form = form;
}
public List<Unit> getUnits() {
return units;
}
public void setUnit(List<Unit> units) {
this.units = units;
}
public void saveUnit() {
FacesMessage msg;
String name = form.getName().toUpperCase();
if (unitDao.getUnitByName(name) != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unit " + name + " already exists.", null);
} else {
unitDao.save(new Unit(name));
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Unit " + name + " successfully saved.", null);
}
FacesContext.getCurrentInstance().addMessage("form_add:name", msg);
form.clear();
}
private FacesMessage checkUnitUsage(Unit unit) {
FacesMessage msg = null;
Threshold threshold = thresholdDao.getLocalThresholdByUnitId(unit.getId());
if (threshold != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unit " + unit.getName() + " cannot be deleted. It is used for some local threshold.", null);
} else {
threshold = thresholdDao.getGlobalThresholdByUnitId(unit.getId());
if (threshold != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unit " + unit.getName() + " cannot be deleted. It is used for global threshold.", null);
} else {
if (attrResultDao.getFirstUsedAttrResultByUnitId(unit.getId()) != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unit " + unit.getName() + " cannot be deleted. It is already used for performance data.", null);
} else {
Attr attr = attrDao.getAttrByUnit(unit.getName());
if (attr != null) {
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unit " + unit.getName() + " cannot be deleted. It is used for attribute " + attr.getName() + ".", null);
}
}
}
}
return msg;
}
public void deleteUnit(Unit unit) {
FacesMessage msg = checkUnitUsage(unit);
if (msg == null) {
unitDao.remove(unit);
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Unit " + unit.getName() + " was deleted.", null);
}
FacesContext.getCurrentInstance().addMessage("form_list:delete", msg);
form.clear();
}
} |
package com.aidn5.antigriefer.gui;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.aidn5.antigriefer.config.References;
import com.aidn5.antigriefer.services.GuiHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraftforge.fml.client.config.GuiSlider;
import net.minecraftforge.fml.client.config.GuiSlider.ISlider;
public class BlocksListenerGui extends GuiHandler {
private List<List<String>> hoverText;
private int sliderTriggerOn = 12;
public BlocksListenerGui(Minecraft mc) {
super(mc);
sliderTriggerOn = Integer.parseInt(References.settings.get("ag-trigger_on", "12"));
}
public void initGui_() {
buttonList = new ArrayList();
hoverText = new ArrayList();
buttonList.add(new GuiButton(1, width / 2 - 70, height / 2 - 66, 140, 20,
"BlocksListener" + checkStatus(References.settings.get("ag-bl", "ON").equals("ON"))));
hoverText.add(toolTipText(new String[] { "Toggle this feature ON/OFF." }));
buttonList.add(new GuiSlider(2, width / 2 - 70, height / 2 - 44, 140, 20, "Trigger on: ", " blocks", 5, 30,
sliderTriggerOn, false, true, new ISlider() {
@Override
public void onChangeSliderValue(GuiSlider slider) {
sliderTriggerOn = slider.getValueInt();
slider.setValue(sliderTriggerOn);
}
}));
hoverText.add(
toolTipText(new String[] { "Get trigger when (the number)", "blocks get destroyed in one event." }));
buttonList.add(new GuiButton(3, width / 2 - 70, height / 2 - 22, 140, 20,
"Show warning" + checkStatus(References.settings.get("ag-warning", "ON").equals("ON"))));
hoverText.add(toolTipText(new String[] { "Show warning when someone trigger it till 80%" }));
buttonList.add(new GuiButton(4, width / 2 - 70, height / 2, 140, 20,
"Demote to guest" + checkStatus(References.settings.get("ag-demote", "On").equals("ON"))));
hoverText.add(toolTipText(new String[] { "Demote the griefer." }));
buttonList.add(new GuiButton(5, width / 2 - 70, height / 2 + 22, 140, 20,
"onUnownSituation" + checkStatus(References.settings.get("ag-unkown_situation", "ON").equals("ON"))));
hoverText.add(toolTipText(new String[] { "On 150% and no action had been taken against the griefer,",
"the mod will make the plot un-edit-able.", "", "If the 'Unkown' still griefs till 200% then",
"the mod will send you somewhere else", "to prevent EVERYONE from building.",
"Enable it. This is your last hope", "when the mod can't find who is REALLY griefing." }));
buttonList.add(new GuiButton(6, width / 2 - 70, height / 2 + 44, 140, 20,
"SmartMode" + checkStatus(References.settings.get("ag-smart_mode", "ON").equals("ON"))));
hoverText.add(toolTipText(new String[] { "BETA: let an AI determire (from the collected data)",
"whether they/there are/is griefer or not." }));
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
super.actionPerformed(button);
if (button.enabled) {
if (button.id == 1) {
References.settings.set("ag-bl", (References.settings.get("ag-bl", "ON").equals("ON") ? "OFF" : "ON"));
} else if (button.id == 3) {
References.settings.set("ag-warning",
(References.settings.get("ag-warning", "ON").equals("ON") ? "OFF" : "ON"));
} else if (button.id == 4) {
References.settings.set("ag-demote",
(References.settings.get("ag-demote", "ON").equals("ON") ? "OFF" : "ON"));
} else if (button.id == 5) {
References.settings.set("ag-unkown_situation",
(References.settings.get("ag-unkown_situation", "ON").equals("ON") ? "OFF" : "ON"));
} else if (button.id == 6) {
References.settings.set("ag-smart_mode",
(References.settings.get("ag-smart_mode", "ON").equals("ON") ? "OFF" : "ON"));
}
}
initGui_();
}
@Override
public void onGuiClosed() {
References.settings.set("ag-trigger_on", sliderTriggerOn + "");
super.onGuiClosed();
}
private List<String> toolTipText(String[] string) {
List<String> list = new ArrayList<String>();
for (String tip : string) {
list.add(tip);
}
return list;
}
@Override
public void initGui() {
initGui_();
super.initGui();
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
super.drawScreen(mouseX, mouseY, partialTicks);
for (int i = 0; i < buttonList.size(); i++) {
if (buttonList.get(i) instanceof GuiButton) {
GuiButton btn = buttonList.get(i);
if (btn.isMouseOver()) {
drawHoveringText(hoverText.get(i), mouseX, mouseY);
}
}
}
}
}
|
package com.fmachinus.practice.service;
import com.fmachinus.practice.entity.Order;
import java.time.LocalDateTime;
import java.util.List;
public interface OrderService {
Order add(Order order);
Order replaceAt(Long id, Order newOrder);
void delete(Long id);
List<Order> findAll();
List<Order> findAllById(List<Long> id);
boolean existsById(Long id);
Order findById(Long id);
List<Order> findByCustomerId(Long customerId);
List<Order> findByProductId(Long productId);
List<Order> findByCustomerIdAndProductId(Long customerId, Long productId);
List<Order> findByPurchaseDateLessThan(LocalDateTime date);
List<Order> findByPurchaseDateGreaterThan(LocalDateTime date);
List<Order> findByPurchaseDateBetween(LocalDateTime date1, LocalDateTime date2);
}
|
package hw4.node;
import hw4.Scenario;
import hw4.Transaction;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class CompliantNode implements Node {
private final Set<Transaction> seenTxs = new HashSet<>();
public static final NodeFactory FACTORY = new NodeFactory() {
@Override
public Node newNode(Scenario scenario) {
return new CompliantNode(scenario);
}
@Override
public String toString() {
return "CompliantNode";
}
};
public CompliantNode(Scenario scenario) {
}
@Override
public void setTrustedNodes(boolean[] trustedNodeFlag) {
}
@Override
public void setInitialTransactions(Set<Transaction> initialTransactions) {
seenTxs.addAll(initialTransactions);
}
@Override
public Set<Transaction> getProposalsForTrustingNodes() {
return Collections.unmodifiableSet(seenTxs);
}
@Override
public void receiveFromTrustedNodes(Set<Candidate> candidates) {
seenTxs.addAll(candidates.stream().map(c -> c.tx).collect(Collectors.toSet()));
}
}
|
package com.hsnam.spring.file.web;
import com.hsnam.spring.file.model.BoardModel;
import com.hsnam.spring.file.model.FileModel;
import com.hsnam.spring.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@Slf4j
@RequestMapping("/api/v1/file")
@RestController
public class FileUploadDownloadController {
@Autowired
private FileService fileService;
@RequestMapping(value = "/{scope}/upload/" , method = RequestMethod.POST)
public ResponseEntity addploadFile(@RequestBody MultipartFile file, @PathVariable("scope") String scope){
try{
log.info(file.getName());
FileModel fileModel = fileService.store(file, scope);
return ResponseEntity.ok(fileModel);
}catch (Exception e){
log.info(e.getMessage());
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value = "/{scope}/upload-list" , method = RequestMethod.POST)
public ResponseEntity addUploadFileList(@RequestParam("file") MultipartFile[] file, @PathVariable("scope") String scope){
try{
log.info("file length ={}",file.length);
return ResponseEntity.ok().build();
}catch (Exception e){
log.info(e.getMessage());
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}//end of uploadFileList
@PostMapping("/insert/{scope}")
public ResponseEntity addFileInfo(@PathVariable("scope") String scope, @RequestParam("file")String fileName){
try{
fileService.moveTempToUpload(fileName,scope);
return ResponseEntity.ok().build();
}catch (IOException io){
log.info(io.getMessage());
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}//end of addFileInfo
@DeleteMapping("/{scope}/delete")
public ResponseEntity deleteFile(@PathVariable("scope") String scope, @RequestParam("file") String fileId){
return ResponseEntity.ok().build();
}//end of deleteFile
@DeleteMapping("/{scipe}/delete-list")
public ResponseEntity deleteFileList(@PathVariable("scope") String scope, @RequestParam("file") List<String> fileId){
return ResponseEntity.ok().build();
}
}
|
package Model;
import Entity.daftarpembeli;
import Entity.BarangEntity;
import java.text.ParseException;
import java.util.ArrayList;
public class DaftarModel implements ModelInterface {
private ArrayList<daftarpembeli> daftarArrayList;
public DaftarModel() {
daftarArrayList = new ArrayList<daftarpembeli>();
}
public void insertDataDaftar(daftarpembeli daftar) {
daftarArrayList.add(daftar);
}
public ArrayList<daftarpembeli>getDaftarArrayList() {
return daftarArrayList;
}
public int size() {
return daftarArrayList.size();
}
@Override
public void view() {
for (daftarpembeli daftar : daftarArrayList) {
System.out.println("==============================================");
System.out.println("nama : " + daftar.getPembeli().getNama()+"\nPassword : " + daftar.getPembeli().getPassword()
+ "\nAlamat : "+daftar.getPembeli().getAlamat()+"\n Baju : "+BarangEntity.nama[daftar.getindexBarang()]
+ "\n isVerified : ");
if(daftar.isIsVerified()==false) {
System.out.println("Belum Di Verifikasi Penjual");
} else {
System.out.println("Sudah Di Verifikasi Penjual");
}
System.out.println("==============================================");
}
}
@Override
public int cekData(String nama, String password) {
int loop = 0;
if(daftarArrayList.size() == 0) {
loop = -1;
} else {
for (int i=0; i<daftarArrayList.size(); i++) {
if (daftarArrayList.get(i).getPembeli().getNama().equals(nama)) {
loop = i;
break;
} else {
loop = -2;
}
}
}
return loop;
}
public daftarpembeli showDaftarPembeli(int index) {
return daftarArrayList.get(index);
}
public void updateIsVerified(int index,daftarpembeli DaftarPembeli) {
daftarArrayList.set(index, DaftarPembeli);
}
public void hapuspembeliModel(int index) {
daftarArrayList.remove(daftarArrayList.get(index));
}
public ArrayList <daftarpembeli> alldatapembeli() {
return daftarArrayList;
}
private int cariBarang(String Barang){
int index=-1;
for(int i=0;i <daftarArrayList.size();i++) {
if(Barang.equals(daftarArrayList.get(i).getPembeli().getNama()))
index=i;
}
return index;
}
public void update(String Barang, int Barangupdate){
int data;
if(cariBarang(Barang)!=-1){
daftarArrayList.get(cariBarang(Barang)).setIndexBarang(Barangupdate);
data = 1;
}
else {
data = 0;
}
}
}
|
import java.util.ArrayList;
public class Teste {
public static void main(String[] args) {
Gerente gerente = new Gerente ("Luiz","Recife PE", "12345678901",0,0.40);
Vendedor vendedor1 = new Vendedor ("Claudio","Recife PE","18346648901",0,gerente,50000.00,0.03);
Vendedor vendedor2 = new Vendedor ("Amanda","Recife PE","52545272901",0,gerente,60000.00,0.03);
ArrayList<Vendedor> listaVendedores = new ArrayList<>();
listaVendedores.add(vendedor1);
listaVendedores.add(vendedor2);
gerente.setListaVendedores(listaVendedores);
System.out.println("Vendendor 1 = Nome: "+vendedor1.getNome()+" Valor Total de Vendas: "+vendedor1.getValorVenda()+" Salario: "+vendedor1.getSalario());
System.out.println("Vendendor 2 = Nome: "+vendedor2.getNome()+" Valor Total de Vendas: "+vendedor2.getValorVenda()+" Salario: "+vendedor2.getSalario());
System.out.println("Gerente = Nome: " +gerente.getNome()+" Salario: "+gerente.getSalario());
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.d;
import com.tencent.mm.plugin.appbrand.jsapi.d.f.b;
import com.tencent.mm.plugin.appbrand.jsapi.h;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.q.f;
import com.tencent.mm.plugin.appbrand.r.c;
import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.v.g;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
class f$5 extends AppBrandInputInvokeHandler {
final /* synthetic */ int doP;
final /* synthetic */ WeakReference fQJ;
final /* synthetic */ String fQK;
final /* synthetic */ f fQP;
f$5(f fVar, WeakReference weakReference, int i, String str) {
this.fQP = fVar;
this.fQJ = weakReference;
this.doP = i;
this.fQK = str;
}
public final void onInputDone(String str, int i, boolean z, boolean z2) {
if (this.fQP.aiW()) {
c.az(this);
}
if (this.fQJ.get() != null) {
try {
String jSONObject = new JSONObject().put("value", c.vT(str)).put("inputId", getInputId()).put("cursor", i).toString();
if (z) {
((p) this.fQJ.get()).j("onKeyboardConfirm", jSONObject, 0);
}
if (!z2) {
((p) this.fQJ.get()).j("onKeyboardComplete", jSONObject, 0);
}
} catch (Throwable e) {
x.e("MicroMsg.JsApiShowKeyboard", "dispatch input done, exp = %s", new Object[]{bi.i(e)});
}
if (!z2) {
aiX();
}
}
}
public final void onInputInitialized() {
if (this.fQJ.get() != null) {
int inputId = getInputId();
Map hashMap = new HashMap(1);
hashMap.put("inputId", Integer.valueOf(inputId));
((p) this.fQJ.get()).E(this.doP, this.fQP.f("ok", hashMap));
f.L(inputId, this.fQK);
f.a(inputId, (p) this.fQJ.get());
}
}
public final void onRuntimeFail() {
c.az(this);
if (this.fQJ.get() != null) {
((p) this.fQJ.get()).E(this.doP, this.fQP.f("fail", null));
aiX();
}
}
public final void onBackspaceWhenValueEmpty() {
p pVar = (p) this.fQJ.get();
if (pVar != null) {
try {
int inputId = getInputId();
b bVar = new b();
JSONObject put = new JSONObject().put("value", "").put("data", f.kJ(inputId)).put("cursor", 0).put("inputId", inputId).put("keyCode", 8);
h a = bVar.a(pVar);
a.mData = put.toString();
a.ahM();
} catch (Exception e) {
x.e("MicroMsg.JsApiShowKeyboard", "onBackspaceWhenValueEmpty, e = %s", new Object[]{e});
}
}
}
public final void kL(int i) {
try {
p pVar = (p) this.fQJ.get();
if (pVar != null) {
pVar.j("onKeyboardShow", g.Dc().D("inputId", getInputId()).D("height", f.lO(i)).toString(), 0);
}
} catch (Exception e) {
}
}
private void aiX() {
p pVar = (p) this.fQJ.get();
if (pVar != null && pVar.gns != null) {
com.tencent.mm.plugin.appbrand.widget.input.g.apm().p(pVar.gns);
}
}
}
|
package com.trainingmarket.action;
import java.io.IOException;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.trainingmarket.service.LoginService;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String email = request.getParameter("LoginEmail");
request.getSession().setAttribute("email",email);
String password =request.getParameter("password");
String homePageUrl = request.getContextPath()+"/servlet/HomePageViewServlet";
String checkEmail = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(checkEmail);
if(email == null || email.trim() == ""){
request.setAttribute("error", "邮箱不能为空|倒数<meta http-equiv='refresh' content='3;url="+homePageUrl +"'>");
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request, response);
}else
{
Matcher matcher = regex.matcher(email);
boolean checkResult = matcher.matches();
if(!checkResult){
request.setAttribute("error","邮箱格式不正确<meta http-equiv='refresh' content='3;url="+homePageUrl +"'>");
request.setAttribute("judgeLogin", "false");
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request,response);
}else if(password == null || email.trim()==""){
request.setAttribute("error", "密码不能为空<meta http-equiv='refresh' content='3;url="+homePageUrl +"'>");
request.setAttribute("judgeLogin", "false");
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request,response);
}else{
LoginService loginService = new LoginService();
try {
if(loginService.judgeEmail(email, password)){
request.setAttribute("judgeLogin", "true");
request.setAttribute("success", "登录成功<meta http-equiv='refresh' content='3;url="+homePageUrl +"'>");
request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
}else{
request.setAttribute("judgeLogin", "false");
request.setAttribute("error", "登录失败<meta http-equiv='refresh' content='3;url="+homePageUrl +"'>");
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request,response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.example.marek.komunikator.messages;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.marek.komunikator.ActivityManager;
import com.example.marek.komunikator.MyBaseActivity;
import com.example.marek.komunikator.R;
import com.example.marek.komunikator.controllers.config.Request;
import com.example.marek.komunikator.controllers.config.Response;
import com.example.marek.komunikator.model.Message;
import com.example.marek.komunikator.model.MessageList;
import com.example.marek.komunikator.userSettings.tasks.NewMessageTask;
import com.example.marek.komunikator.userSettings.tasks.ResponseTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import java.util.List;
public class MessageActivity extends MyBaseActivity {
private ArrayAdapter<Message> messageAdapter;
protected ResponseTask mAuthTask = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
EditText et = (EditText) findViewById(R.id.editText);
et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
addToList(v.getText().toString());
v.setText(null);
return false;
}
});
List<Message> list = MessageList.getMessageList();
messageAdapter = new MessageAdapter(this, list);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(messageAdapter);
}
@Override
public void onResponse(Response response) {
if (response.getApiPath().equals("/messageNotification")){
mAuthTask = new NewMessageTask(response, this);
mAuthTask.execute((Void) null);
}
}
@Override
public void resetDataAfterResponse() {
mAuthTask = null;
}
@Override
public void executeAfterResponse(boolean success) {
if (success){
messageAdapter.notifyDataSetChanged();
}
}
private void addToList(String text){
Request request = new Request("/sendMessage");
try {
String body = null;
if (text != null) {
body = new JSONObject().put("userNick", MessageList.friendName)
.put("message", text).toString();
}
request.setBody(body);
} catch (JSONException e) {
e.printStackTrace();
}
ActivityManager.webSocket.send(request.getRequest());
Message msg = new Message(text, new Date());
messageAdapter.add(msg);
}
}
|
package com.jx.sleep_dg.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.jx.sleep_dg.R;
import com.jx.sleep_dg.base.BaseMainFragment;
import com.jx.sleep_dg.ble.BleUtils;
import com.jx.sleep_dg.protocol.BleComUtils;
import com.jx.sleep_dg.utils.LogUtil;
import com.jx.sleep_dg.view.BorderButton;
/**
* 床位温度
*/
public class DeviceTempFragment extends BaseMainFragment implements View.OnClickListener {
private ImageView ivChuang;
private BorderButton mLevel1;
private BorderButton mLevel2;
private BorderButton mLevel3;
private BorderButton mLevel4;
private BorderButton mLevel5;
private int index = 0;
public static DeviceTempFragment newInstance() {
Bundle args = new Bundle();
DeviceTempFragment fragment = new DeviceTempFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_temp;
}
@Override
public void onBindView(View view) {
ivChuang = view.findViewById(R.id.iv_chuang);
mLevel1 = (BorderButton) view.findViewById(R.id.level_1);
mLevel2 = (BorderButton) view.findViewById(R.id.level_2);
mLevel3 = (BorderButton) view.findViewById(R.id.level_3);
mLevel4 = (BorderButton) view.findViewById(R.id.level_4);
mLevel5 = (BorderButton) view.findViewById(R.id.level_5);
mLevel1.setOnClickListener(this);
mLevel2.setOnClickListener(this);
mLevel3.setOnClickListener(this);
mLevel4.setOnClickListener(this);
mLevel5.setOnClickListener(this);
view.findViewById(R.id.btn_jian).setOnClickListener(this);
view.findViewById(R.id.btn_add).setOnClickListener(this);
onIndexChange(index);
}
@Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btn_jian:
if (index > 0) {
index--;
}
break;
case R.id.btn_add:
if (index < 5) {
index++;
}
break;
case R.id.level_1:
index = 1;
break;
case R.id.level_2:
index = 2;
break;
case R.id.level_3:
index = 3;
break;
case R.id.level_4:
index = 4;
break;
case R.id.level_5:
index = 5;
break;
}
LogUtil.i("index:" + index);
onIndexChange(index);
BleComUtils.sendJiare(BleUtils.convertDecimalToBinary("" + index));
}
//床的变化和按钮变化
private void onIndexChange(int index) {
mLevel1.setNormalColor(Color.TRANSPARENT);
mLevel2.setNormalColor(Color.TRANSPARENT);
mLevel3.setNormalColor(Color.TRANSPARENT);
mLevel4.setNormalColor(Color.TRANSPARENT);
mLevel5.setNormalColor(Color.TRANSPARENT);
switch (index) {
case 0:
ivChuang.setImageResource(R.mipmap.warmbed_0);
break;
case 1:
ivChuang.setImageResource(R.mipmap.warmbed_1);
mLevel1.setNormalColor(Color.parseColor("#6e6fff"));
break;
case 2:
ivChuang.setImageResource(R.mipmap.warmbed_2);
mLevel1.setNormalColor(Color.parseColor("#6e6fff"));
mLevel2.setNormalColor(Color.parseColor("#8d52be"));
break;
case 3:
ivChuang.setImageResource(R.mipmap.warmbed_3);
mLevel1.setNormalColor(Color.parseColor("#6e6fff"));
mLevel2.setNormalColor(Color.parseColor("#8d52be"));
mLevel3.setNormalColor(Color.parseColor("#b1347e"));
break;
case 4:
ivChuang.setImageResource(R.mipmap.warmbed_4);
mLevel1.setNormalColor(Color.parseColor("#6e6fff"));
mLevel2.setNormalColor(Color.parseColor("#8d52be"));
mLevel3.setNormalColor(Color.parseColor("#b1347e"));
mLevel4.setNormalColor(Color.parseColor("#c31f52"));
break;
case 5:
ivChuang.setImageResource(R.mipmap.warmbed_5);
mLevel1.setNormalColor(Color.parseColor("#6e6fff"));
mLevel2.setNormalColor(Color.parseColor("#8d52be"));
mLevel3.setNormalColor(Color.parseColor("#b1347e"));
mLevel4.setNormalColor(Color.parseColor("#c31f52"));
mLevel5.setNormalColor(Color.parseColor("#d90d28"));
break;
}
}
}
|
package com.company;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import javax.swing.*;
import java.awt.image.BufferedImage;
/**
* Created by leon on 25.06.16.
*/
public class Utils {
public static BufferedImage IplImageToBufferedImage(opencv_core.IplImage src) {
OpenCVFrameConverter.ToIplImage grabberConverter = new OpenCVFrameConverter.ToIplImage();
Java2DFrameConverter paintConverter = new Java2DFrameConverter();
org.bytedeco.javacv.Frame frame = grabberConverter.convert(src);
return paintConverter.getBufferedImage(frame,1);
}
public static opencv_core.IplImage BufferedImageToIplImage(BufferedImage src)
{
OpenCVFrameConverter.ToIplImage iplConverter = new OpenCVFrameConverter.ToIplImage();
Java2DFrameConverter java2dConverter = new Java2DFrameConverter();
return iplConverter.convert(java2dConverter.convert(src));
}
public void CreateFileForNN(String path){
}
public static void showImage(BufferedImage img)
{
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
JLabel label = new JLabel( new ImageIcon(img));
dialog.add( label );
dialog.pack();
dialog.setVisible(true);
}
public static void showText(String text)
{
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
JLabel label = new JLabel(text);
dialog.add( label );
dialog.pack();
dialog.setVisible(true);
}
}
|
package com.ssm.wechatpro.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.UploadService;
@Controller
public class UploadController {
@Resource
private UploadService uploadService;
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("post/UploadController/insertImgFile")
@ResponseBody
public void insertImgFile(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFiles") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("post/UploadController/insertImgFileOne")
@ResponseBody
public void insertImgFileOne(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesOne") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("post/UploadController/insertImgFileTwo")
@ResponseBody
public void insertImgFileTwo(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesTwo") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("post/UploadController/insertImgFileThree")
@ResponseBody
public void insertImgFileThree(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesThree") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("post/UploadController/insertImgFileFour")
@ResponseBody
public void insertImgFileFour(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesFour") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 上传图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("/post/UploadController/insertImgFileFive")
@ResponseBody
public void insertImgFileFive(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesFive") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFile(inputObject, outputObject, files);
}
/**
* 微信上传会员卡背景图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("/post/UploadController/insertImgFileWechatOne")
@ResponseBody
public void insertImgFileWechatOne(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesFivebackground") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFileWechat(inputObject, outputObject, files);
}
/**
* 微信上传会员卡logo图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("/post/UploadController/insertImgFileWechatTwo")
@ResponseBody
public void insertImgFileWechatTwo(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesFivelogo") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFileWechat(inputObject, outputObject, files);
}
/**
* 微信上传会员卡简介图片
* @param inputObject
* @param outputObject
* @param files
* @throws Exception
*/
@RequestMapping("/post/UploadController/insertImgFileWechatThree")
@ResponseBody
public void insertImgFileWechatThree(InputObject inputObject,OutputObject outputObject,@RequestParam("imgFilesFiveimage") CommonsMultipartFile files) throws Exception {
uploadService.insertImgFileWechat(inputObject, outputObject, files);
}
}
|
package com.lalagrass.soundgenerator;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final static int volumeScaleBound = 2000;
private final static double volumeScale = 0.9;
private static volatile double volumeFactor = 0;
private static volatile int noteFactor = -1;
private final static int sampleRate = 44100;
private double[] fastSin = new double[sampleRate];
private final static int maxF = 1600;
private Button bStart;
private TextView tFreq;
private SeekBar seekBar;
private static volatile boolean isPlaying = false;
private static volatile int _frequency = 220;
private static volatile double incr = (double)220 / 44100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bStart = (Button) findViewById(R.id.buttonStart);
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (noteFactor == 1) {
bStart.setText("Start");
noteFactor = -1;
} else if (noteFactor == -1) {
bStart.setText("Stop");
noteFactor = 1;
}
}
});
tFreq = (TextView) findViewById(R.id.textFreq);
tFreq.setText(_frequency + "Hz");
seekBar = (SeekBar) findViewById(R.id.seekbar);
seekBar.setProgress(_frequency);
seekBar.setMax(maxF);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0) {
_frequency = 1;
} else {
_frequency = progress;
}
noteFactor = 1;
tFreq.setText(_frequency + "Hz");
incr = (double)_frequency / 44100;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
for (int i = 0 ; i < fastSin.length; i++) {
fastSin[i] = Math.sin(Math.PI * i * 2/ fastSin.length);
}
}
@Override
protected void onPause() {
isPlaying = false;
noteFactor = -1;
bStart.setText("Start");
super.onPause();
}
@Override
protected void onResume() {
isPlaying = true;
bStart.setText("Start");
new Generator().execute();
super.onResume();
}
private class Generator extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
AudioTrack audioTrack;
short generatedSnd[];// = new byte[2 * numSamples];
int _bufSize;
_bufSize = AudioTrack.getMinBufferSize(sampleRate,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT);
_bufSize *= 2;
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, _bufSize,
AudioTrack.MODE_STREAM);
generatedSnd = new short[_bufSize];
audioTrack.play();
double offset = 0;
while (isPlaying) {
for (int i = 0; i < generatedSnd.length; i++) {
offset += incr;
if (offset > 1)
offset -= 1;
volumeFactor += noteFactor;
if (volumeFactor > volumeScaleBound)
volumeFactor = volumeScaleBound;
else if (volumeFactor < 0)
volumeFactor = 0;
generatedSnd[i] = (short) (volumeScale * volumeFactor / volumeScaleBound * Short.MAX_VALUE * Math.sin(2 * Math.PI * offset));
}
audioTrack.write(generatedSnd, 0, generatedSnd.length);
}
audioTrack.stop();
audioTrack.release();
return null;
}
}
}
|
package net.praqma.jenkins.plugin.drmemory;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.Builder;
import net.praqma.drmemory.DrMemory;
import net.praqma.drmemory.DrMemoryResult;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestBuilder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class DrMemoryBuildActionTest {
@Rule
public JenkinsRule jr = new JenkinsRule();
@Test
public void testJEP200() throws Exception {
Node s = jr.createOnlineSlave();
final String in = getClass().getClassLoader().getResource( "results.txt" ).getFile();
FreeStyleProject fp = jr.createFreeStyleProject("JEP-200");
fp.setAssignedNode(s);
AbstractBuild<?,?> r = jr.buildAndAssertSuccess(fp);
DrMemoryBuildAction drMemory = new DrMemoryBuildAction(r);
DrMemoryResult res = DrMemoryResult.parse(new File(in));
drMemory.addResult(res);
r.addAction(drMemory);
r.save();
}
/*
*/
}
|
package com.oxycab.provider.ui.activity.email;
import com.oxycab.provider.base.MvpView;
import com.oxycab.provider.data.network.model.User;
public interface EmailIView extends MvpView {
void onSuccess(User token);
void onError(Throwable e);
}
|
package com.example.filmictionary;
public class Movie {
private String mTitle;
private String mImageUrl;
private String mReleaseDate;
private String mCast;
private Double mImdbRatings;
private String mStoryLine;
public Movie(String title, String imageUrl, String releaseDate, String cast, Double imdbRatings, String storyLine){
mTitle = title;
mImageUrl = imageUrl;
mReleaseDate = releaseDate;
mCast = cast;
mImdbRatings = imdbRatings;
mStoryLine = storyLine;
}
public String getmTitle() {
return mTitle;
}
public String getmImageUrl() {
return mImageUrl;
}
public String getmReleaseDate() {
return mReleaseDate;
}
public String getmCast() {
return mCast;
}
public Double getmImdbRatings() {
return mImdbRatings;
}
public String getmStoryLine(){return mStoryLine;}
}
|
package com.fang.example.db;
import com.fang.example.db.htree.FastIterator;
import com.fang.example.db.htree.HTree;
import com.fang.example.db.manager.RecordManager;
import com.fang.example.db.manager.RecordManagerFactory;
import java.io.IOException;
import java.util.Properties;
/**
* Created by andy on 6/26/16.
*/
public class Main {
static RecordManager _recman;
public static void queryAll(HTree hashtable)
throws Exception
{
// Display content
System.out.println( "contents: " );
FastIterator iter = hashtable.keys();
String name = (String) iter.next();
while ( name != null ) {
System.out.println(" " + name);
name = (String) iter.next();
}
System.out.println();
}
public static void insert(HTree hashtable)
throws Exception
{
// insert keys and values
System.out.println();
hashtable.put( "k1", "v1" );
hashtable.put( "k2", "v2" );
hashtable.put( "k3", "v3" );
queryAll(hashtable);
System.out.println();
String key = (String) hashtable.get( "k1" );
System.out.println( "key are " + key );
_recman.commit();
System.out.println();
System.out.print( "Remove" );
hashtable.remove( "k2" );
_recman.commit();
System.out.println( " done." );
queryAll(hashtable);
hashtable.remove("k1");
_recman.rollback();
queryAll(hashtable);
// cleanup
_recman.close();
}
public static void main( String[] args ) throws Exception {
// create or open fruits record manager
_recman = RecordManagerFactory.createRecordManager("db");
long recid = _recman.getNamedObject( "test2" );
HTree hashtable;
if ( recid != 0 ) {
System.out.println( "load Db." );
hashtable = HTree.load( _recman, recid );
queryAll(hashtable);
} else {
System.out.println( "Create DB." );
hashtable = HTree.createInstance( _recman );
_recman.setNamedObject( "test2", hashtable.getRecid() );
}
try {
insert(hashtable);
} catch ( IOException ioe ) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package assgn.JianKai;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JOptionPane;
import listLink.ListLink;
import listLink.ListLinkInt;
import listLink.store;
public class AddMenu extends javax.swing.JFrame {
store save;
ListLinkInt <MenuClass>mArray;
public AddMenu() {
initComponents();
}
public AddMenu(store save) {
this.save = save;
this.setTitle("Add Menu");
this.setVisible(true);
this.setLocationRelativeTo(null);
initComponents();
if(save.getCurMenu().getSize()!=0)
foodid.setText(save.getCurAff().getAid()+"F"+save.getMenuCount(save.getCurMenu().get(save.getCurMenu().getSize()).getFoodid()));
else
foodid.setText(save.getCurAff().getAid()+"F1");
foodid.setEditable(false);
restaurantname.setText(save.getCurAff().getResname());
restaurantname.setEditable(false);
}
@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();
clearbutton = new javax.swing.JButton();
addbutton = new javax.swing.JButton();
foodname = new javax.swing.JTextField();
restaurantname = new javax.swing.JTextField();
fooddescription = new javax.swing.JTextField();
foodprice = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
foodstatus = new javax.swing.JComboBox<>();
jLabel7 = new javax.swing.JLabel();
foodid = new javax.swing.JTextField();
back = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Add Menu");
jLabel2.setText("Food Name");
jLabel3.setText("Restaurant Name");
jLabel4.setText("Food Description");
jLabel5.setText("Price (RM)");
clearbutton.setText("Clear");
clearbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearbuttonActionPerformed(evt);
}
});
addbutton.setText("Add");
addbutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addbuttonActionPerformed(evt);
}
});
foodname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
foodnameActionPerformed(evt);
}
});
jLabel6.setText("Food Status");
foodstatus.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Available","Not available" }));
jLabel7.setText("Food ID");
back.setText("Back");
back.setToolTipText("");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(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(98, 98, 98)
.addComponent(clearbutton)
.addGap(57, 57, 57)
.addComponent(addbutton))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel5))
.addComponent(jLabel7))
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(foodname)
.addComponent(fooddescription)
.addComponent(foodprice)
.addComponent(foodstatus, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(restaurantname, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
.addComponent(foodid))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addComponent(back)))))
.addGap(40, 40, 40))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(back))
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(foodid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(foodname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(restaurantname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(fooddescription, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(foodprice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(foodstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(clearbutton)
.addComponent(addbutton))
.addGap(25, 25, 25))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void foodnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_foodnameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_foodnameActionPerformed
private void clearbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearbuttonActionPerformed
// TODO add your handling code here:
foodname.setText("");
fooddescription.setText("");
foodprice.setText("");
}//GEN-LAST:event_clearbuttonActionPerformed
private void addbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addbuttonActionPerformed
// TODO add your handling code here:
Calendar now = Calendar.getInstance();
String themonth = new SimpleDateFormat("MMM").format(now.getTime());
String theyear = new SimpleDateFormat("YYYY").format(now.getTime());
MenuClass mc = new MenuClass(foodid.getText(),foodname.getText(),fooddescription.getText(),foodprice.getText(),foodstatus.getSelectedItem().toString(),save.getCurAff().getAid(),themonth,theyear);
if (mc.checkfn() && mc.checkdesc() && mc.checkprice())
{
save.getCurMenu().add(mc);
save.getMenu().add(mc);
JOptionPane.showMessageDialog(this, "Add successful");
this.setVisible(false);
AllAffiliatePage a = new AllAffiliatePage(save);
}
else
{
JOptionPane.showMessageDialog(this, "" + mc.toString());
}
}//GEN-LAST:event_addbuttonActionPerformed
private void backActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backActionPerformed
// TODO add your handling code here:
this.setVisible(false);
AllAffiliatePage a = new AllAffiliatePage(save);
}//GEN-LAST:event_backActionPerformed
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(AddMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddMenu.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 AddMenu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addbutton;
private javax.swing.JButton back;
private javax.swing.JButton clearbutton;
private javax.swing.JTextField fooddescription;
private javax.swing.JTextField foodid;
private javax.swing.JTextField foodname;
private javax.swing.JTextField foodprice;
private javax.swing.JComboBox<String> foodstatus;
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.JTextField restaurantname;
// End of variables declaration//GEN-END:variables
}
|
package com.ai.slp.order.api.ordertradecenter.param;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import com.ai.opt.base.vo.BaseInfo;
public class OrdProductDetailInfo extends BaseInfo{
private static final long serialVersionUID = 1L;
/**
* 销售商id
*/
private Long supplierId;
/**
* 运费
*/
private long freight;
/**
* 商品信息
*/
private List<OrdProductInfo> ordProductInfoList;
/**
* 订单费用明细信息
*/
private List<OrdFeeTotalProdInfo> ordFeeTotalProdInfo;
/**
* 发票信息
*/
private OrdInvoiceInfo ordInvoiceInfo;
public List<OrdProductInfo> getOrdProductInfoList() {
return ordProductInfoList;
}
public void setOrdProductInfoList(List<OrdProductInfo> ordProductInfoList) {
this.ordProductInfoList = ordProductInfoList;
}
public Long getSupplierId() {
return supplierId;
}
public void setSupplierId(Long supplierId) {
this.supplierId = supplierId;
}
public List<OrdFeeTotalProdInfo> getOrdFeeTotalProdInfo() {
return ordFeeTotalProdInfo;
}
public void setOrdFeeTotalProdInfo(List<OrdFeeTotalProdInfo> ordFeeTotalProdInfo) {
this.ordFeeTotalProdInfo = ordFeeTotalProdInfo;
}
public long getFreight() {
return freight;
}
public void setFreight(long freight) {
this.freight = freight;
}
public OrdInvoiceInfo getOrdInvoiceInfo() {
return ordInvoiceInfo;
}
public void setOrdInvoiceInfo(OrdInvoiceInfo ordInvoiceInfo) {
this.ordInvoiceInfo = ordInvoiceInfo;
}
}
|
package negocio.libreria;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//import jakarta.persistence.EntityManager;
//import jakarta.persistence.EntityManagerFactory;
//import jakarta.persistence.EntityTransaction;
//import jakarta.persistence.LockModeType;
//import jakarta.persistence.NoResultException;
//import jakarta.persistence.Persistence;
//import jakarta.persistence.Query;
//import jakarta.persistence.TypedQuery;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.LockModeType;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class SALibreriaImp implements SALibreria {
public static final String SELECT_ALL_QUERY = "SELECT * FROM libreria";
public Integer altaLibreria(TransferLibreria tLibreria) throws Exception {
int result = -1;
EntityManagerFactory emf = Persistence.createEntityManagerFactory("BSA_COD");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
TypedQuery<EntityLibreria> namedQuery = em.createNamedQuery("Libreria.findByNombre", EntityLibreria.class).setParameter("nombre", tLibreria.getNombre());
EntityLibreria auxLibreria;
try {
auxLibreria = namedQuery.getSingleResult();
} catch (NoResultException e) {
auxLibreria = null;
}
if (auxLibreria == null) {
auxLibreria = new EntityLibreria();
auxLibreria.setNombre(tLibreria.getNombre());
auxLibreria.setDireccion(tLibreria.getDireccion());
auxLibreria.setActivo(tLibreria.getActivo());
em.persist(auxLibreria);
transaction.commit();
result = em.createNamedQuery("Libreria.findByNombre", EntityLibreria.class).setParameter("nombre", tLibreria.getNombre()).getSingleResult().getId();
} else if (auxLibreria.getActivo()) {
transaction.rollback();
result = -5;
} else {
transaction.rollback();
result = -10;
}
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
emf.close();
}
return result;
}
public void bajaLibreria(Integer idLibreria) throws ClassNotFoundException, Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("BSA_COD");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
EntityLibreria libreria = em.find(EntityLibreria.class, idLibreria);
if (libreria == null) {
throw new Exception("Libreria inexistente, revisa el Id.");
}
em.lock(libreria, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
libreria.setActivo(false);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
emf.close();
}
}
public Integer modificarLibreria(TransferLibreria tLibreria) throws ClassNotFoundException, Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("BSA_COD");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
EntityLibreria auxLibreria = em.find(EntityLibreria.class, tLibreria.getId());
if (auxLibreria == null)
throw new Exception("Libreria inexistente, revisa el ID.");
em.lock(auxLibreria, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
auxLibreria.setNombre(tLibreria.getNombre());
auxLibreria.setDireccion(tLibreria.getDireccion());
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
emf.close();
}
return tLibreria.getId();
}
public TransferLibreria mostrarLibreria(Integer idLibreria) throws ClassNotFoundException, Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("BSA_COD");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
TransferLibreria tLibreria = null;
EntityLibreria libreria = em.find(EntityLibreria.class, idLibreria);
if (libreria == null) {
transaction.rollback();
throw new Exception("La libreria no existe, revisa el ID.");
}
tLibreria = libreria.toTransfer();
em.close();
emf.close();
return tLibreria;
}
public Collection<TransferLibreria> listarLibrerias() throws ClassNotFoundException, Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("BSA_COD");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Collection<TransferLibreria> res = new ArrayList<TransferLibreria>();
try {
List<EntityLibreria> list = em.createNamedQuery("Libreria.findAll", EntityLibreria.class).getResultList();
for (EntityLibreria entity : list) {
res.add(entity.toTransfer());
}
} finally {
em.close();
emf.close();
}
return res;
}
} |
package pl.luwi.series.distributed;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
import javax.jms.JMSException;
public interface RegistrationService extends Remote {
<P extends OrderedPoint> List<P> reduce(List<P> points, double epsilon) throws InterruptedException, JMSException, RemoteException;
List<Integer> getLineIDs() throws RemoteException;
Double getEpsilon(Integer calculationID) throws RemoteException;
public <P extends OrderedPoint> void submitResult(int RDPid, int lineID, List<P> result) throws RemoteException;
public <P extends OrderedPoint> void submitExpectation(int RDPid, int lineID) throws RemoteException;
}
|
package com.tencent.mm.plugin.subapp.ui.friend;
class b$4 implements Runnable {
final /* synthetic */ String dhh;
final /* synthetic */ b orO;
b$4(b bVar, String str) {
this.orO = bVar;
this.dhh = str;
}
public final void run() {
a.g(b.a(this.orO), this.dhh, false);
}
}
|
package com.tb24.fn.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.TooltipCompat;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.tb24.fn.R;
import com.tb24.fn.event.CalendarDataLoadedEvent;
import com.tb24.fn.event.ProfileUpdatedEvent;
import com.tb24.fn.model.AthenaProfileAttributes;
import com.tb24.fn.model.CalendarTimelineResponse;
import com.tb24.fn.model.EpicError;
import com.tb24.fn.model.FortItemStack;
import com.tb24.fn.model.FortMcpProfile;
import com.tb24.fn.model.FortMcpResponse;
import com.tb24.fn.model.assetdata.FortChallengeBundleItemDefinition;
import com.tb24.fn.model.assetdata.FortQuestItemDefinition;
import com.tb24.fn.model.command.FortRerollDailyQuest;
import com.tb24.fn.model.command.SetPartyAssistQuest;
import com.tb24.fn.util.ItemUtils;
import com.tb24.fn.util.JsonUtils;
import com.tb24.fn.util.LoadingViewController;
import com.tb24.fn.util.Utils;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import retrofit2.Call;
import retrofit2.Response;
public class ChallengeBundleActivity extends BaseActivity {
public static final String VALUE_DAILY_CHALLENGES = "_daily__challenges";
private static final Map<String, String> cheatsheetUrls = new HashMap<>();
static {
// credit to u/thesquatingdog for the original cheatsheets
cheatsheetUrls.put("ChallengeBundle:questbundle_s9_week_001", "https://i.redd.it/eoa6qwoe8fx21.jpg");
cheatsheetUrls.put("ChallengeBundle:questbundle_s9_week_002", "https://i.redd.it/s5o3wgbqdly21.jpg");
cheatsheetUrls.put("ChallengeBundle:questbundle_s9_week_003", "https://i.redd.it/hkczsox5pyz21.jpg");
cheatsheetUrls.put("ChallengeBundle:questbundle_s9_week_004", "https://i.redd.it/gieae2lcjc131.jpg");
}
private RecyclerView list;
private ChallengeAdapter adapter;
private LoadingViewController lc;
private FortMcpProfile profileData;
private Map<String, FortItemStack> questsFromProfile = new HashMap<>();
private Call<FortMcpResponse> callReroll;
private Call<FortMcpResponse> callPartyAssist;
private String cheatsheetUrl;
private FortChallengeBundleItemDefinition challengeBundleDef;
private CalendarTimelineResponse.ActiveEvent calendarEventTag;
private JsonObject attributesFromProfile;
public static FortQuestItemDefinition populateQuestView(BaseActivity activity, View view, FortItemStack item) {
TextView questTitle = view.findViewById(R.id.quest_title);
View questProgressParent = view.findViewById(R.id.quest_progress_parent);
ProgressBar questProgressBar = view.findViewById(R.id.quest_progress_bar);
TextView questProgressText = view.findViewById(R.id.quest_progress_text);
View questRewardParent = view.findViewById(R.id.quest_reward_parent);
ImageView rewardIcon = view.findViewById(R.id.quest_reward_icon);
TextView rewardText = view.findViewById(R.id.quest_reward_text);
boolean done = item.attributes != null && JsonUtils.getStringOr("quest_state", item.attributes, "").equals("Claimed");
view.findViewById(R.id.quest_main_container).setAlpha(done ? 0.6F : 1.0F);
view.findViewById(R.id.quest_done).setVisibility(done ? View.VISIBLE : View.GONE);
view.findViewById(R.id.quest_done_check_mark).setVisibility(done ? View.VISIBLE : View.GONE);
FortQuestItemDefinition quest = (FortQuestItemDefinition) item.getDefData();
if (quest == null) {
questProgressParent.setVisibility(View.GONE);
questRewardParent.setVisibility(View.GONE);
questTitle.setText("Unknown Quest: " + item.templateId);
return null;
} else if (done) {
questProgressParent.setVisibility(View.GONE);
} else {
questProgressParent.setVisibility(View.VISIBLE);
}
questTitle.setText(quest.DisplayName);
int completion = 0;
int max = 0;
String backendNameSuffix = quest.GameplayTags != null && Arrays.binarySearch(quest.GameplayTags.gameplay_tags, "Quest.Metadata.Glyph") >= 0 ? item.templateId.substring(item.templateId.lastIndexOf('_')) : "";
for (FortQuestItemDefinition.Objective objective : quest.Objectives) {
if (item.attributes != null) {
String backendName = "completion_" + objective.BackendName.toLowerCase();
if (item.attributes.has(backendName)) {
completion += item.attributes.get(backendName).getAsInt();
} else if (item.attributes.has(backendName + backendNameSuffix)) {
completion += item.attributes.get(backendName + backendNameSuffix).getAsInt();
}
}
max += objective.Count;
}
if (quest.ObjectiveCompletionCount != null) {
max = quest.ObjectiveCompletionCount;
}
questProgressBar.setMax(max);
questProgressBar.setProgress(completion);
questProgressText.setText(TextUtils.concat(Utils.color(String.format("%,d", completion), Utils.getTextColorPrimary(activity)), " / ", String.format("%,d", max)));
if (quest.Rewards == null || quest.Rewards.length == 0) {
questRewardParent.setVisibility(View.GONE);
TooltipCompat.setTooltipText(questRewardParent, null);
} else {
questRewardParent.setVisibility(View.VISIBLE);
FortItemStack rewardItem = quest.Rewards[0].asItemStack();
JsonElement jsonElement = activity.getThisApplication().itemRegistry.get(rewardItem.templateId);
int size;
if (rewardItem.getIdCategory().equals("AccountResource") || rewardItem.quantity > 1) {
size = 36;
rewardText.setVisibility(View.VISIBLE);
} else {
size = 56;
rewardText.setVisibility(View.GONE);
}
size = (int) Utils.dp(activity.getResources(), size);
rewardIcon.setLayoutParams(new LinearLayout.LayoutParams((int) Utils.dp(activity.getResources(), 56), size));
if (jsonElement != null) {
JsonObject jsonObject = jsonElement.getAsJsonArray().get(0).getAsJsonObject();
Bitmap bitmapImageFromItemStackData = ItemUtils.getBitmapImageFromItemStackData(activity, rewardItem, jsonObject);
rewardIcon.setImageBitmap(bitmapImageFromItemStackData);
questRewardParent.setVisibility(bitmapImageFromItemStackData == null ? View.GONE : View.VISIBLE);
TooltipCompat.setTooltipText(questRewardParent, JsonUtils.getStringOr("DisplayName", jsonObject, ""));
} else {
TooltipCompat.setTooltipText(questRewardParent, null);
}
rewardText.setText(String.format("%,d", rewardItem.quantity));
}
return quest;
}
private static int modifyRGB(int color, Float sBy, Float vBy) {
float[] out = new float[3];
ColorUtils.colorToHSL(color, out);
out[1] *= sBy == null ? 1.0F : sBy;
out[2] *= vBy == null ? 1.0F : vBy;
return ColorUtils.HSLToColor(out);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_loadable_recycler_view);
setupActionBar();
list = findViewById(R.id.main_recycler_view);
list.setLayoutManager(new LinearLayoutManager(ChallengeBundleActivity.this));
list.setBackgroundColor(0x40003468);
lc = new LoadingViewController(this, list, "Challenge data not found") {
@Override
public boolean shouldShowEmpty() {
return adapter == null;
}
};
refreshUi();
getThisApplication().eventBus.register(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onProfileUpdated(ProfileUpdatedEvent event) {
if (event.profileId.equals("athena")) {
refreshUi();
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onCalendarDataLoaded(CalendarDataLoadedEvent event) {
refreshUi();
}
@Override
public void onDestroy() {
super.onDestroy();
getThisApplication().eventBus.unregister(this);
if (callReroll != null) {
callReroll.cancel();
}
if (callPartyAssist != null) {
callPartyAssist.cancel();
}
}
private void refreshUi() {
if ((profileData = getThisApplication().profileManager.getProfileData("athena")) == null) {
lc.loading();
return;
}
String bundleTemplateId = getIntent().getStringExtra("a");
questsFromProfile.clear();
List<QuestEntry> data = new ArrayList<>();
if (bundleTemplateId.equals("Quest:" + VALUE_DAILY_CHALLENGES)) {
setTitle("Daily");
for (Map.Entry<String, FortItemStack> entry : profileData.items.entrySet()) {
if (entry.getValue().getIdCategory().equals("Quest") && entry.getValue().getDefData() != null && entry.getValue().getDefData().export_type.equals("AthenaDailyQuestDefinition") && entry.getValue().attributes != null && JsonUtils.getStringOr("quest_state", entry.getValue().attributes, "").equals("Active")) {
questsFromProfile.put(entry.getKey(), entry.getValue());
data.add(new DefaultQuestEntry(this, entry.getValue().getIdName(), null));
}
}
} else {
JsonElement a = getThisApplication().itemRegistry.get(bundleTemplateId);
if (a == null) {
lc.content();
return;
}
for (Map.Entry<String, FortItemStack> entry : profileData.items.entrySet()) {
if (entry.getValue().templateId.equals(bundleTemplateId)) {
attributesFromProfile = entry.getValue().attributes;
break;
}
}
if (attributesFromProfile == null) {
lc.content();
return;
}
for (JsonElement jsonElement : attributesFromProfile.get("grantedquestinstanceids").getAsJsonArray()) {
String s = jsonElement.getAsString();
questsFromProfile.put(s, profileData.items.get(s));
}
challengeBundleDef = getThisApplication().gson.fromJson(a.getAsJsonArray().get(0), FortChallengeBundleItemDefinition.class);
setTitle(Utils.color(challengeBundleDef.DisplayName, 0xFFFFFFFF));
getWindow().setStatusBarColor(challengeBundleDef.DisplayStyle.PrimaryColor.toPackedARGB());
getSupportActionBar().setBackgroundDrawable(new TitleBackgroundDrawable(this, challengeBundleDef.DisplayStyle));
List<CompletionRewardQuestEntry> completionRewardQuestEntries = new ArrayList<>();
for (FortChallengeBundleItemDefinition.BundleCompletionReward bundleCompletionReward : challengeBundleDef.BundleCompletionRewards) {
boolean add = false;
for (FortChallengeBundleItemDefinition.Reward reward : bundleCompletionReward.Rewards) {
if (!reward.RewardType.equals("EAthenaRewardItemType::HiddenReward")) {
add = true;
}
}
if (add) {
completionRewardQuestEntries.add(new CompletionRewardQuestEntry(bundleCompletionReward));
}
}
if (!completionRewardQuestEntries.isEmpty()) {
data.add(new HeaderQuestEntry("Completion Rewards"));
data.addAll(completionRewardQuestEntries);
}
data.add(new HeaderQuestEntry("Challenges"));
data.addAll(Lists.transform(Arrays.asList(challengeBundleDef.QuestInfos), new Function<FortChallengeBundleItemDefinition.QuestInfo, QuestEntry>() {
@Override
public QuestEntry apply(@NullableDecl FortChallengeBundleItemDefinition.QuestInfo input) {
return new DefaultQuestEntry(ChallengeBundleActivity.this, null, input);
}
}));
if (challengeBundleDef.CalendarEventTag != null && getThisApplication().calendarDataBase != null) {
for (CalendarTimelineResponse.ActiveEvent activeEvent : getThisApplication().calendarDataBase.channels.get("client-events").states[0].activeEvents) {
if (activeEvent.eventType.equals(challengeBundleDef.CalendarEventTag)) {
calendarEventTag = activeEvent;
break;
}
}
}
if (cheatsheetUrls.containsKey(bundleTemplateId)) {
cheatsheetUrl = cheatsheetUrls.get(bundleTemplateId);
}
}
if (adapter == null) {
list.setAdapter(adapter = new ChallengeAdapter(this, data));
} else {
adapter.updateData(data);
}
lc.content();
}
private String findItemId(String templateId) {
for (Map.Entry<String, FortItemStack> entry : profileData.items.entrySet()) {
if (entry.getValue().templateId.equals(templateId)) {
return entry.getKey();
}
}
return null;
}
private void fillQuestDefsRecursive(FortQuestItemDefinition questDef, List<FortQuestItemDefinition> outQuestDefs) {
if (questDef == null) {
return;
}
outQuestDefs.add(questDef);
if (questDef.Rewards == null) {
return;
}
for (FortQuestItemDefinition.Reward reward : questDef.Rewards) {
FortItemStack stack = reward.asItemStack();
if (stack.getIdCategory().equals("Quest")) {
fillQuestDefsRecursive((FortQuestItemDefinition) stack.getDefData(), outQuestDefs);
}
}
}
private void fillQuestItemsRecursive(FortItemStack chainedQuestItem, List<FortItemStack> outStacks) {
if (chainedQuestItem == null) {
return;
}
outStacks.add(chainedQuestItem);
String challengeLinkedQuestGiven = JsonUtils.getStringOr("challenge_linked_quest_given", chainedQuestItem.attributes, null);
if (challengeLinkedQuestGiven != null && !challengeLinkedQuestGiven.isEmpty()) {
fillQuestItemsRecursive(questsFromProfile.get(challengeLinkedQuestGiven), outStacks);
}
}
private static class ChallengeAdapter extends RecyclerView.Adapter<ChallengeViewHolder> {
private static final int VIEW_TYPE_HEADER = 1;
private static final int VIEW_TYPE_COMPLETION_REWARD = 2;
private static final int VIEW_TYPE_CHEATSHEET = 3;
private final ChallengeBundleActivity activity;
private List<QuestEntry> data;
private int expandedPosition = -1;
public ChallengeAdapter(ChallengeBundleActivity activity, List<QuestEntry> data) {
this.activity = activity;
this.data = data;
}
@NonNull
@Override
public ChallengeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View inflate = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == 0 || viewType == VIEW_TYPE_COMPLETION_REWARD) {
inflate = inflater.inflate(R.layout.quest_entry, parent, false);
((ImageView) inflate.findViewById(R.id.quest_done_check_mark)).setImageBitmap(Utils.loadTga(activity, "/Game/Athena/UI/Challenges/Art/T_UI_ChallengeCheck_64.T_UI_ChallengeCheck_64"));
} else if (viewType == VIEW_TYPE_HEADER) {
inflate = inflater.inflate(R.layout.quest_header, parent, false);
} else if (viewType == VIEW_TYPE_CHEATSHEET) {
inflate = inflater.inflate(R.layout.log_out_settings_button, parent, false);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = (int) Utils.dp(activity.getResources(), 16);
inflate.setLayoutParams(params);
}
return new ChallengeViewHolder(inflate);
}
@Override
public void onBindViewHolder(@NonNull final ChallengeViewHolder holder, final int position) {
if (getItemViewType(position) == VIEW_TYPE_CHEATSHEET) {
holder.btnCheatsheet.setText("Cheatsheet plz");
holder.btnCheatsheet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(activity.cheatsheetUrl)));
}
});
return;
}
data.get(position).bindToViewHolder(activity, this, holder, position);
}
@Override
public int getItemViewType(int position) {
return activity.cheatsheetUrl != null && position == data.size() ? VIEW_TYPE_CHEATSHEET : data.get(position).getItemViewType();
}
@Override
public int getItemCount() {
return data.size() + (activity.cheatsheetUrl != null ? 1 : 0);
}
public void updateData(List<QuestEntry> data) {
this.data = data;
notifyDataSetChanged();
}
}
private static class ChallengeViewHolder extends RecyclerView.ViewHolder {
public ViewGroup questMainContainer;
public TextView questDone;
public TextView assistText;
public TextView questTitle;
public ViewGroup questProgressParent;
public ProgressBar questProgressBar;
public TextView questProgressText;
public ViewGroup questRewardParent;
public ImageView questDoneCheck;
public ImageView questRewardIcon;
public TextView questRewardText;
public ViewGroup actions;
public Button btnAssist;
public Button btnReplace;
public Button btnCheatsheet;
public ChallengeViewHolder(View itemView) {
super(itemView);
questMainContainer = itemView.findViewById(R.id.quest_main_container);
questDone = itemView.findViewById(R.id.quest_done);
assistText = itemView.findViewById(R.id.quest_party_assist);
questTitle = itemView.findViewById(R.id.quest_title);
questProgressParent = itemView.findViewById(R.id.quest_progress_parent);
questProgressBar = itemView.findViewById(R.id.quest_progress_bar);
questProgressText = itemView.findViewById(R.id.quest_progress_text);
questRewardParent = itemView.findViewById(R.id.quest_reward_parent);
questDoneCheck = itemView.findViewById(R.id.quest_done_check_mark);
questRewardIcon = itemView.findViewById(R.id.quest_reward_icon);
questRewardText = itemView.findViewById(R.id.quest_reward_text);
actions = itemView.findViewById(R.id.quest_options);
btnAssist = itemView.findViewById(R.id.quest_btn_assist);
btnReplace = itemView.findViewById(R.id.quest_btn_replace);
btnCheatsheet = itemView.findViewById(R.id.log_out_button);
}
}
private static abstract class QuestEntry {
public abstract void bindToViewHolder(ChallengeBundleActivity activity, ChallengeAdapter adapter, RecyclerView.ViewHolder holder, int position);
public int getItemViewType() {
return 0;
}
}
private static class HeaderQuestEntry extends QuestEntry {
private final CharSequence title;
public HeaderQuestEntry(CharSequence title) {
this.title = title;
}
@Override
public void bindToViewHolder(ChallengeBundleActivity activity, ChallengeAdapter adapter, RecyclerView.ViewHolder holder, int position) {
((TextView) ((ViewGroup) holder.itemView).getChildAt(0)).setText(title);
}
@Override
public int getItemViewType() {
return ChallengeAdapter.VIEW_TYPE_HEADER;
}
}
private static class CompletionRewardQuestEntry extends QuestEntry {
private final FortChallengeBundleItemDefinition.BundleCompletionReward bundleCompletionReward;
public CompletionRewardQuestEntry(FortChallengeBundleItemDefinition.BundleCompletionReward bundleCompletionReward) {
this.bundleCompletionReward = bundleCompletionReward;
}
@Override
public void bindToViewHolder(ChallengeBundleActivity activity, ChallengeAdapter adapter, RecyclerView.ViewHolder holder_, int position) {
ChallengeViewHolder holder = (ChallengeViewHolder) holder_;
int completion = JsonUtils.getIntOr("num_progress_quests_completed", activity.attributesFromProfile, 0);
boolean done = activity.attributesFromProfile != null && completion >= bundleCompletionReward.CompletionCount;
holder.questMainContainer.setAlpha(done ? 0.6F : 1.0F);
holder.questDone.setText("Earned!");
holder.questDone.setVisibility(done ? View.VISIBLE : View.GONE);
holder.questDoneCheck.setVisibility(done ? View.VISIBLE : View.GONE);
holder.questProgressParent.setVisibility(done ? View.GONE : View.VISIBLE);
String s;
if (bundleCompletionReward.CompletionCount == -1 || bundleCompletionReward.CompletionCount == 1) {
s = "any challenge";
} else {
s = String.format((bundleCompletionReward.CompletionCount >= activity.challengeBundleDef.QuestInfos.length ? "all" : "any") + " %,d challenges", bundleCompletionReward.CompletionCount);
}
holder.questTitle.setText(TextUtils.replace("Complete %s to earn the reward item", new String[]{"%s"}, new CharSequence[]{Utils.color(s.toUpperCase(), Utils.getTextColorPrimary(activity))}));
holder.questProgressBar.setMax(bundleCompletionReward.CompletionCount == -1 ? 1 : bundleCompletionReward.CompletionCount);
holder.questProgressBar.setProgress(completion);
holder.questProgressText.setText(TextUtils.concat(Utils.color(String.format("%,d", completion), Utils.getTextColorPrimary(activity)), " / ", String.format("%,d", bundleCompletionReward.CompletionCount)));
if (bundleCompletionReward.Rewards == null || bundleCompletionReward.Rewards.length == 0) {
holder.questRewardParent.setVisibility(View.GONE);
TooltipCompat.setTooltipText(holder.questRewardParent, null);
} else {
holder.questRewardParent.setVisibility(View.VISIBLE);
FortChallengeBundleItemDefinition.Reward reward = bundleCompletionReward.Rewards[0];
JsonElement jsonElement = reward.TemplateId != null && !reward.TemplateId.isEmpty() ? activity.getThisApplication().itemRegistry.get(reward.TemplateId) : activity.getThisApplication().itemRegistry.getWithAnyNamespace(Utils.parseUPath2(reward.ItemDefinition.asset_path_name));
int size;
if (reward.Quantity > 1) {
size = 36;
holder.questRewardText.setVisibility(View.VISIBLE);
} else {
size = 56;
holder.questRewardText.setVisibility(View.GONE);
}
size = (int) Utils.dp(activity.getResources(), size);
holder.questRewardIcon.setLayoutParams(new LinearLayout.LayoutParams((int) Utils.dp(activity.getResources(), 56), size));
if (jsonElement != null) {
JsonObject jsonObject = jsonElement.getAsJsonArray().get(0).getAsJsonObject();
Bitmap bitmapImageFromItemStackData = ItemUtils.getBitmapImageFromItemStackData(activity, null, jsonObject);
holder.questRewardIcon.setImageBitmap(bitmapImageFromItemStackData);
holder.questRewardParent.setVisibility(bitmapImageFromItemStackData == null ? View.GONE : View.VISIBLE);
TooltipCompat.setTooltipText(holder.questRewardParent, JsonUtils.getStringOr("DisplayName", jsonObject, ""));
} else {
TooltipCompat.setTooltipText(holder.questRewardParent, null);
}
holder.questRewardText.setText(String.format("%,d", reward.Quantity));
}
}
@Override
public int getItemViewType() {
return ChallengeAdapter.VIEW_TYPE_COMPLETION_REWARD;
}
}
private static class DefaultQuestEntry extends QuestEntry {
private final FortChallengeBundleItemDefinition.QuestInfo entryDef;
private final List<FortQuestItemDefinition> questDefChain = new ArrayList<>();
private final List<FortItemStack> questItemChain = new ArrayList<>();
private FortItemStack activeQuestItem = null;
public DefaultQuestEntry(ChallengeBundleActivity activity, String questItemTemplateId, FortChallengeBundleItemDefinition.QuestInfo entryDef) {
this.entryDef = entryDef;
if (questItemTemplateId == null) {
questItemTemplateId = entryDef.QuestDefinition.asset_path_name.substring(entryDef.QuestDefinition.asset_path_name.lastIndexOf('/') + 1, entryDef.QuestDefinition.asset_path_name.lastIndexOf('.')).toLowerCase();
}
for (FortItemStack entry : activity.questsFromProfile.values()) {
if (entry.templateId.equals("Quest:" + questItemTemplateId)) {
activity.fillQuestItemsRecursive(entry, questItemChain);
break;
}
}
if (!questItemChain.isEmpty()) {
activeQuestItem = questItemChain.get(questItemChain.size() - 1);
activity.fillQuestDefsRecursive((FortQuestItemDefinition) questItemChain.get(0).getDefData(), questDefChain);
}
if (activeQuestItem == null) {
activeQuestItem = new FortItemStack("Quest", questItemTemplateId, 1);
}
}
@Override
public void bindToViewHolder(final ChallengeBundleActivity activity, final ChallengeAdapter adapter, RecyclerView.ViewHolder holder_, int position) {
final ChallengeViewHolder holder = (ChallengeViewHolder) holder_;
FortQuestItemDefinition quest = populateQuestView(activity, holder.itemView, activeQuestItem);
if (quest == null) {
holder.actions.setVisibility(View.GONE);
holder.itemView.setOnClickListener(null);
return;
}
boolean isChain = questDefChain.size() > 1;
String questState = activeQuestItem.attributes == null ? "" : JsonUtils.getStringOr("quest_state", activeQuestItem.attributes, "");
boolean done = questState.equals("Claimed");
final boolean isEligibleForReplacement = !done && quest.export_type.equals("AthenaDailyQuestDefinition") && questState.equals("Active") && ((AthenaProfileAttributes) activity.profileData.stats.attributesObj).quest_manager.dailyQuestRerolls > 0;
final boolean isEligibleForAssist = !done && quest.GameplayTags != null && Arrays.binarySearch(quest.GameplayTags.gameplay_tags, "Quest.Metadata.PartyAssist") >= 0;
final boolean isPartyAssisted = isEligibleForAssist && ((AthenaProfileAttributes) activity.profileData.stats.attributesObj).party_assist_quest.equals(activity.findItemId(activeQuestItem.templateId));
if (isPartyAssisted) {
BitmapDrawable drawable = new BitmapDrawable(activity.getResources(), Utils.loadTga(activity, "/Game/Athena/UI/Challenges/Art/T_UI_PartyAssist_Incoming_64.T_UI_PartyAssist_Incoming_64"));
int i = (int) Utils.dp(activity.getResources(), 24);
drawable.setBounds(0, 0, i, i);
holder.assistText.setCompoundDrawables(drawable, null, null, null);
holder.assistText.setVisibility(View.VISIBLE);
} else {
holder.assistText.setVisibility(View.GONE);
}
holder.questTitle.setText(TextUtils.concat(isChain ? Utils.color(String.format("Stage %,d of %,d", questItemChain.size(), questDefChain.size()), Utils.getTextColorPrimary(activity)) : "", (isChain ? " - " : "") + holder.questTitle.getText()));
holder.questProgressParent.setVisibility(done ? View.GONE : View.VISIBLE);
if (entryDef != null && entryDef.QuestUnlockType != null && entryDef.QuestUnlockType.equals("EChallengeBundleQuestUnlockType::DaysFromEventStart")) {
if (entryDef.UnlockValue == 100) {
holder.questTitle.setText(activity.challengeBundleDef.UniqueLockedMessage);
holder.questProgressParent.setVisibility(View.GONE);
} else if (activity.calendarEventTag != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(activity.calendarEventTag.activeSince);
calendar.add(Calendar.DAY_OF_MONTH, entryDef.UnlockValue);
long delta = calendar.getTimeInMillis() - System.currentTimeMillis();
if (delta > 0) {
long days = TimeUnit.MILLISECONDS.toDays(delta);
String s = "Unlocks in " + days + " day" + (days == 1L ? "" : "s");
if (days < 1L) {
long hours = TimeUnit.MILLISECONDS.toHours(delta % 86400000);
s = "Unlocks in " + hours + " hour" + (hours == 1L ? "" : "s");
if (hours < 1L) {
s = "Unlocking soon";
}
}
holder.questTitle.setText(TextUtils.concat(Utils.color(s, 0xFFE1564B), " - " + holder.questTitle.getText()));
}
}
}
holder.actions.setVisibility(adapter.expandedPosition == position ? View.VISIBLE : View.GONE);
holder.btnReplace.setVisibility(isEligibleForReplacement ? View.VISIBLE : View.GONE);
holder.btnAssist.setVisibility(isEligibleForAssist ? View.VISIBLE : View.GONE);
holder.btnAssist.setText("Party Assist" + (isPartyAssisted ? " \u2714" : ""));
final FortItemStack finalActiveQuestItem = activeQuestItem;
holder.btnReplace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (!isEligibleForReplacement) {
return;
}
v.setEnabled(false);
FortRerollDailyQuest payload = new FortRerollDailyQuest();
payload.questId = activity.findItemId(finalActiveQuestItem.templateId);
activity.callReroll = activity.getThisApplication().fortnitePublicService.mcp(
"FortRerollDailyQuest",
PreferenceManager.getDefaultSharedPreferences(activity).getString("epic_account_id", ""),
"athena",
activity.getThisApplication().profileManager.getRvn("athena"),
payload);
new Thread("Reroll Daily Quest Worker") {
@Override
public void run() {
try {
Response<FortMcpResponse> response = activity.callReroll.execute();
if (response.isSuccessful()) {
activity.getThisApplication().profileManager.executeProfileChanges(response.body());
} else {
Utils.dialogError(activity, EpicError.parse(response).getDisplayText());
}
} catch (IOException e) {
Utils.throwableDialog(activity, e);
} finally {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
v.setEnabled(true);
}
});
}
}
}.start();
}
});
holder.btnAssist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
if (!isEligibleForAssist) {
return;
}
v.setEnabled(false);
SetPartyAssistQuest payload = new SetPartyAssistQuest();
payload.questToPinAsPartyAssist = isPartyAssisted ? "" : activity.findItemId(finalActiveQuestItem.templateId);
activity.callPartyAssist = activity.getThisApplication().fortnitePublicService.mcp(
"SetPartyAssistQuest",
PreferenceManager.getDefaultSharedPreferences(activity).getString("epic_account_id", ""),
"athena",
activity.getThisApplication().profileManager.getRvn("athena"),
payload);
new Thread("Set Party Assist Quest Worker") {
@Override
public void run() {
try {
Response<FortMcpResponse> response = activity.callPartyAssist.execute();
if (response.isSuccessful()) {
activity.getThisApplication().profileManager.executeProfileChanges(response.body());
} else {
Utils.dialogError(activity, EpicError.parse(response).getDisplayText());
}
} catch (IOException e) {
Utils.throwableDialog(activity, e);
} finally {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
v.setEnabled(true);
}
});
}
}
}.start();
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isEligibleForReplacement || isEligibleForAssist) {
boolean newState = adapter.expandedPosition != holder.getAdapterPosition();
if (adapter.expandedPosition >= 0) {
adapter.notifyItemChanged(adapter.expandedPosition);
}
if (newState) {
adapter.expandedPosition = holder.getAdapterPosition();
adapter.notifyItemChanged(holder.getAdapterPosition());
} else {
adapter.expandedPosition = -1;
}
}
}
});
}
}
public static class TitleBackgroundDrawable extends Drawable {
private static final float HEIGHT = 12.0F;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path();
private final float density;
private final int[] colorsBackground = new int[2];
private final int[] colorsPath = new int[2];
public TitleBackgroundDrawable(Context ctx, FortChallengeBundleItemDefinition.DisplayStyle displayStyle) {
density = ctx.getResources().getDisplayMetrics().density;
// TODO gradient
colorsBackground[0] = displayStyle.PrimaryColor.toPackedARGB();
colorsBackground[1] = displayStyle.PrimaryColor.toPackedARGB();
colorsPath[0] = 0x80000000 | modifyRGB(displayStyle.AccentColor.toPackedARGB(), 0.75F, null) & 0x00FFFFFF;
colorsPath[1] = 0x80000000 | modifyRGB(displayStyle.AccentColor.toPackedARGB(), 0.75F, null) & 0x00FFFFFF;
}
@Override
public void draw(@NonNull Canvas canvas) {
Rect rect = getBounds();
float yoff = rect.height() - HEIGHT * density;
path.reset();
path.moveTo(rect.width(), yoff + HEIGHT / 3.0F * density);
path.lineTo(rect.width() / 2.0F - 2.0F * density, yoff);
path.lineTo(rect.width() / 2.0F + 2.0F * density, yoff + HEIGHT / 2.0F * density);
path.lineTo(0.0F, yoff + HEIGHT / 3.0F * density);
path.lineTo(0.0F, rect.height());
path.lineTo(rect.width(), rect.height());
path.close();
paint.setShader(new LinearGradient(0.0F, 0.0F, rect.width(), 0.0F, colorsBackground, null, Shader.TileMode.CLAMP));
canvas.drawPaint(paint);
paint.setShader(new LinearGradient(0.0F, 0.0F, rect.width(), 0.0F, colorsPath, null, Shader.TileMode.CLAMP));
canvas.drawPath(path, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
}
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.mm.plugin.sns.model.av.a;
import java.util.HashMap;
class av$b {
int dzO = 0;
long endTime = -1;
boolean kdC = false;
long nrV = -1;
final /* synthetic */ av nrW;
long nrX = -1;
int nrY = 0;
HashMap<String, a> nrZ = new HashMap();
long startTime = -1;
av$b(av avVar) {
this.nrW = avVar;
}
}
|
package BOJ;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Q11721 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
String str = br.readLine();
int len = str.length() / 10;
for (int i = 0; i < len + 1; i++) {
if (i == len)
System.out.println(str.substring((i * 10)));
System.out.println(str.substring((i * 10), (i * 10) + 10));
}
} catch (Exception e) {
}
}
}
|
/*package com.travelportal.domain.allotment;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Query;
import javax.persistence.Table;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import com.travelportal.domain.Country;
import com.travelportal.domain.Currency;
import com.travelportal.domain.HotelHealthAndSafety;
import com.travelportal.domain.HotelMealPlan;
import com.travelportal.domain.HotelProfile;
import com.travelportal.domain.rooms.HotelRoomTypes;
import com.travelportal.domain.rooms.RateMeta;
import com.travelportal.domain.rooms.RoomChildPolicies;
import com.travelportal.vm.AllotmentMarketVM;
import com.travelportal.vm.RoomType;
@Entity
@Table(name="allotment")
public class Allotment {
@Column(name="allotment_id")
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int allotmentId;
@Column(name="supplierCode")
private Long supplierCode;
@Column(name="formDate")
private Date formDate;
@Column(name="toDate")
private Date toDate;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private HotelRoomTypes roomId;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Currency currencyId;
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<RateMeta> rate;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
private List<AllotmentMarket> allotmentmarket;
public int getAllotmentId() {
return allotmentId;
}
public void setAllotmentId(int allotmentId) {
this.allotmentId = allotmentId;
}
public Long getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(Long supplierCode) {
this.supplierCode = supplierCode;
}
public Date getFormDate() {
return formDate;
}
public void setFormDate(Date formDate) {
this.formDate = formDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public Currency getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Currency currencyId) {
this.currencyId = currencyId;
}
public HotelRoomTypes getRoomId() {
return roomId;
}
public void setRoomId(HotelRoomTypes roomId) {
this.roomId = roomId;
}
public List<RateMeta> getRate() {
return rate;
}
public void setRate(List<RateMeta> rate) {
this.rate = rate;
}
public List<AllotmentMarket> getAllotmentmarket() {
return allotmentmarket;
}
public void setAllotmentmarket(List<AllotmentMarket> allotmentmarket) {
this.allotmentmarket = allotmentmarket;
}
public void addAllotmentmarket(AllotmentMarket allotmentmarket) {
if(this.allotmentmarket == null){
this.allotmentmarket = new ArrayList<>();
}
if(!this.allotmentmarket.contains(allotmentmarket))
this.allotmentmarket.add(allotmentmarket);
}
public static Allotment findById(Long supplierCode) {
try
{
return (Allotment) JPA.em().createQuery("select c from Allotment c where c.supplierCode = ?1").setParameter(1, supplierCode).getSingleResult();
}
catch(Exception ex){
return null;
}
}
public static Allotment getRateById(Long supplierCode,Date formDate,Date toDate,String currId,Long roomId) {List<Integer> rateid
Calendar c = Calendar.getInstance();
c.setTime(formDate);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
formDate = c.getTime();
c.setTime(toDate);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
toDate = c.getTime();
System.out.println("|||||||");
System.out.println(formDate);
System.out.println(toDate);
try
{
Query q = JPA.em().createQuery("select c from Allotment c where c.supplierCode = ?1 and c.formDate = ?2 and c.toDate = ?3 and c.currencyId.currencyName = ?4 and c.roomId.roomId = ?5");
q.setParameter(1, supplierCode);
q.setParameter(2, formDate);
q.setParameter(3, toDate);
q.setParameter(4, currId);
q.setParameter(5, roomId);
return(Allotment) q.getSingleResult();
}
catch(Exception ex){
return null;
}
}
public static Allotment allotmentfindById(int Code) {
try
{
return (Allotment) JPA.em().createQuery("select c from Allotment c where c.allotmentId = ?1").setParameter(1, Code).getSingleResult();
}
catch(Exception ex){
return null;
}
}
public static int deleteMarketAllotRel(int id) {
Query q = JPA.em().createNativeQuery("delete from allotment_allotmentmarket where allotmentmarket_allotmentMarket_Id = '"+id+"'");
// query.setParameter(1, id);
return q.executeUpdate();
}
public static int deleteMarketAllot(int id) {
Query query = JPA.em().createNativeQuery("delete from allotmentmarket where allotmentMarket_Id = '"+id+"'");
//query.setParameter(1, id);
return query.executeUpdate();
}
@Transactional
public void save() {
JPA.em().persist(this);
JPA.em().flush();
}
@Transactional
public void delete() {
JPA.em().remove(this);
}
@Transactional
public void merge() {
JPA.em().merge(this);
}
@Transactional
public void refresh() {
JPA.em().refresh(this);
}
}
*/ |
package br;
public class testJogo {
public static void main(String[] args) {
Soldado soldado1 = new Soldado(1,"jose",60.0);
Soldado soldado2 = new Soldado(2,"hilton", 50.0);
Cavaleiro caveleiro1 = new Cavaleiro(3, "silva", 70.0);
Jogo jogo = new Jogo();
jogo.incluir(soldado1);
jogo.incluir(soldado2);
jogo.incluir(caveleiro1);
jogo.atacar(soldado1, soldado2);
jogo.atacar(soldado2, caveleiro1);
jogo.atacar(caveleiro1, soldado1);
jogo.avaliarBatalha();
}
}
|
package com.filiereticsa.arc.augmentepf.activities;
public enum SettingsType {
EMAIL,
SPECIFIC_ATTRIBUTE
}
|
package umm3601.todos;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class TodoDatabase {
private Todo[] allTodos;
public TodoDatabase(String todoDataFile) throws IOException {
Gson gson = new Gson();
FileReader reader = new FileReader(todoDataFile);
allTodos = gson.fromJson(reader, Todo[].class);
}
/**
* Get the single todos specified by the given ID. Return
* `null` if there is no todos with that ID.
*
* @param id the ID of the desired todos
* @return the todos with the given ID, or null if there is no todos
* with that ID
*/
public Todo getTodos(String id) {
return Arrays.stream(allTodos).filter(x -> x._id.equals(id)).findFirst().orElse(null);
}
/**
* Get an array of all the todoss satisfying the queries in the params.
*
* @param queryParams map of required key-value pairs for the query
* @return an array of all the todoss matching the given criteria
*/
public Todo[] listTodos(Map<String, String[]> queryParams) {
Todo[] filteredTodos = allTodos;
// Filter status if defined
if (queryParams.containsKey("status")) {
String completedStatus = queryParams.get("status")[0];
filteredTodos = filterTodosByStatus(filteredTodos, completedStatus);
}
if (queryParams.containsKey("contains")) {
String completedBody = queryParams.get("contains")[0];
filteredTodos = filterTodosByBody(filteredTodos, completedBody);
}
if (queryParams.containsKey("owner")) {
String completedOwner = queryParams.get("owner")[0];
filteredTodos = filterTodosByOwner(filteredTodos, completedOwner);
}
if (queryParams.containsKey("limit")) {
int completedLimit = Integer.parseInt(queryParams.get("limit")[0]);
filteredTodos = filterTodosByLimit(filteredTodos, completedLimit);
}
if (queryParams.containsKey("category")) {
String completedCategory = queryParams.get("category")[0];
filteredTodos = filterTodosByCategory(filteredTodos, completedCategory);
}
if (queryParams.containsKey("orderBy")) {
String completedOrder = queryParams.get("orderBy")[0];
filteredTodos = sortTodosByOrder(filteredTodos, completedOrder);
}
// Process other query parameters here...
return filteredTodos;
}
/**
* Get an array of all the todoss having the target status.
*
* @param todos the list of todoss to filter by status
* @param status the boolean to look for
* @return an array of all the todos from the given list that have
* the status
*/
public Todo[] filterTodosByStatus(Todo[] todos, String status) {
if (status.equals("complete")) {
return Arrays.stream(todos).filter(x -> x.status).toArray(Todo[]::new);
}
else if (status.equals("incomplete")) {
return Arrays.stream(todos).filter(x -> !x.status).toArray(Todo[]::new);
}
else {
return todos;
}
}
public Todo[] filterTodosByBody(Todo[] todos, String body) {
return Arrays.stream(todos).filter(x -> x.body.contains(body)).toArray(Todo[]::new);
}
public Todo[] filterTodosByOwner(Todo[] todos, String Owner) {
return Arrays.stream(todos).filter(x -> x.owner.contains(Owner)).toArray(Todo[]::new);
}
public Todo[] filterTodosByLimit(Todo[] todos, int Limit) {
return Arrays.stream(todos).limit(Limit).toArray(Todo[]::new);
}
public Todo[] filterTodosByCategory(Todo[] todos, String category) {
return Arrays.stream(todos).filter(x -> x.category.contains(category)).toArray(Todo[]::new);
}
// public Todo[] sortTodosByOrder(Todo[] todos, String attribute) {
// if (attribute.equals("status")) {
// return Arrays.stream(todos).sorted((o1, o2)->o1.sort().getValue(). compareTo(o2.getItem().getValue())). collect(Collectors.toList());
// }
// if (attribute.equals("owner")) {
// return Arrays.stream(todos).filter(x -> x.owner.contains(allTodos)).toArray(Todo[]::new);
// }
// if (attribute.equals("body")) {
// return Arrays.stream(todos).filter(x -> x.category.contains(Category)).toArray(Todo[]::new);
// }
// }
public Todo[] sortTodosByOrder(Todo[] todos, String orderBy) {
Todo[] array = Arrays.stream(todos).sorted((o1, o2) -> {
if (orderBy.equals("owner")) {
return o1.owner.compareTo(o2.owner);
} else if (orderBy.equals("category")) {
return o1.category.compareTo(o2.category);
} else if (orderBy.equals("status")) {
return Boolean.compare(o1.status, o2.status);
} else if (orderBy.equals("body")) {
return o1.body.compareTo(o2.body);
}
else {
return 0;
}
}).toArray(Todo[]::new);
return array;
}
}
|
package com.ybg.company.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.ybg.company.domain.Department;
public class DepartmentMapper implements RowMapper<Department> {
@Override
public Department mapRow(ResultSet rs, int rowNum) throws SQLException {
Department bean = new Department();
bean.setId("id");
bean.setName(rs.getString("name"));
bean.setCompanyid(rs.getString("comanyid"));
bean.setParentid(rs.getString("parentid"));
bean.setCreatetime(rs.getString("createtime"));
return bean;
}
}
|
package dataProvider;
import java.io.FileInputStream;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
public class ArrayExcelDATaProvider {
WebDriver driver;
@BeforeTest
public void setUp() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();// browser open
driver.get("file:///C:/Users/rajat/Downloads/Selenium%20Softwares/Offline%20Website/Offline%20Website/index.html");
driver.manage().window().maximize();// to maximize the browser
}
@Test(dataProvider = "loginData")
public void test01(String uname, String pass) {
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(uname);
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys(pass);
driver.findElement(By.xpath("//button")).click();
if(driver.getTitle().equals("JavaByKiran | Dashboard"))
driver.findElement(By.xpath("/html/body/div/header/nav/div/ul/li/a")).click();
//log out button click
}
@DataProvider
public Object[][] loginData() throws Exception{
FileInputStream fis = new FileInputStream("Book1.xls");
Workbook wb= Workbook.getWorkbook(fis);
Sheet sh = wb.getSheet("login");
int row=sh.getRows();
int col=sh.getColumns();
String dataArr[][]= new String[row-1][col];
for(int i=1;i<row;i++) {
for(int j=0;j<col;j++) {
String data=sh.getCell(j,i).getContents();
dataArr[i-1][j]=data;
}
}
return dataArr; //return of DataProvider method
}//terminte DataProvider method
}//terminate main method
//Rename Sheet 1 as login
//In dataprovider,return type of method is Two Dimensional Array ex Object[][]
//throw Exception
//Excel sheet ka data store karna padega Array me say String dataArr[][]
//String dataArr[][]= new String[sh.getRows()-1][sh.getColumns()];
//loop
//array me data stored by index 0 ,so dataArr[i-1][j]=data;
//Method has return type,so return sttm must be given here ex return dataarray |
package com.pointburst.jsmusic.ui;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.pointburst.jsmusic.R;
import com.pointburst.jsmusic.adapter.MediaListAdapter;
import com.pointburst.jsmusic.adapter.MediaPagerAdapter;
import com.pointburst.jsmusic.constant.Constants;
import com.pointburst.jsmusic.events.BindMusicService;
import com.pointburst.jsmusic.listener.PMediaPlayerListener;
import com.pointburst.jsmusic.model.Album;
import com.pointburst.jsmusic.model.Media;
import com.pointburst.jsmusic.model.Result;
import com.pointburst.jsmusic.network.ServiceResponse;
import com.pointburst.jsmusic.player.MediaPlayerService;
import com.pointburst.jsmusic.player.PMediaPlayer;
import com.pointburst.jsmusic.ui.widgets.SlideLayout;
import com.pointburst.jsmusic.utils.Logger;
import de.greenrobot.event.EventBus;
import java.net.URLDecoder;
import java.util.ArrayList;
/**
* Created by FARHAN on 12/27/2014.
*/
public class MainActivity extends BaseActivity implements PMediaPlayerListener{
private MediaPlayerService mPlayerService;
private ArrayList<Media> mediaArrayList = new ArrayList<Media>();
private boolean musicBound = false;
private int mCurrentMediaIndex;
private ServiceConnection musicConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Logger.print("OnServiceConnected called");
MediaPlayerService.MediaPlayerBinder binder = (MediaPlayerService.MediaPlayerBinder) service;
//get service
mPlayerService = binder.getMediaPlayerService(mediaArrayList,mCurrentMediaIndex,MainActivity.this);
musicBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Logger.print("onServiceDisconnected called");
musicBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slider_layout);
Result result = (Result)getIntent().getSerializableExtra(Constants.RESULT_KEY);
mediaArrayList = result.getAlbums().get(0).getMedias();
mCurrentMediaIndex = getIntent().getIntExtra(Constants.CURRENT_MEDIA_INDEX,0);
((ViewPager)findViewById(R.id.media_view_pager)).setAdapter(new MediaPagerAdapter(getSupportFragmentManager(),this,mediaArrayList));
((ViewPager)findViewById(R.id.media_view_pager)).setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
updateLyric(i);
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
((ViewPager)findViewById(R.id.media_view_pager)).setOffscreenPageLimit(mediaArrayList.size());
onUpdateMpUi(mCurrentMediaIndex);
setSongListAdapter();
findViewById(R.id.playPauseButton).setOnClickListener(this);
findViewById(R.id.nextButton).setOnClickListener(this);
findViewById(R.id.previousButton).setOnClickListener(this);
}
private void setSongListAdapter(){
ListView listView = (ListView)findViewById(R.id.media_list_view);
listView.setAdapter(new MediaListAdapter(this, mediaArrayList));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((SlideLayout)findViewById(R.id.slider_layout)).closeBottomMenu(true);
onUpdateMpUi(position);
}
});
}
@Override
public void updateUi(ServiceResponse response) {
super.updateUi(response);
}
public void onEvent(Media media){
}
public void onEvent(BindMusicService service){
mCurrentMediaIndex = service.getCurrentMediaIndex();
bindMusicService();
}
/*public void onEvent(ServiceClosedEvent event){
Logger.print("Receive event from Media service that it was closed and has to be restarted");
*//*if (musicBound) {
Logger.print("unboinding");
unbindService(musicConnection);
musicBound = false;
}*//*
bindMusicService();
EventBus.getDefault().register(this);
}*/
private void bindMusicService() {
if (musicBound) {
Logger.print("un Bind from resume");
unbindService(musicConnection);
musicBound = false;
}
Intent playIntent = new Intent(this, MediaPlayerService.class);
if (iSMediaPlayerServiceRunning() && !musicBound) {
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
}
else {
startService(playIntent);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
}
}
/** Determines if the MediaPlayerService is already running.
* @return true if the service is running, false otherwise.
*/
private boolean iSMediaPlayerServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.pointburst.jsmusic.player.MediaPlayerService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
public void onInitializePlayerStart(String message) {
findViewById(R.id.loader_layout).setVisibility(View.GONE);
changePlayPauseBtn(false);
}
@Override
public void onInitializePlayerSuccess() {
findViewById(R.id.loader_layout).setVisibility(View.GONE);
changePlayPauseBtn(true);
}
@Override
public void onError() {
findViewById(R.id.loader_layout).setVisibility(View.GONE);
changePlayPauseBtn(false);
}
@Override
public void onUpdateMpUi(int index) {
mCurrentMediaIndex = index;
((ViewPager)findViewById(R.id.media_view_pager)).setCurrentItem(index);
updateLyric(index);
}
private void updateLyric(int index){
String lyrics = mediaArrayList.get(index).getLyrics();
try {
lyrics = URLDecoder.decode(lyrics,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
((TextView)findViewById(R.id.lyrics_txt_view)).setText(lyrics);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.playPauseButton:
/*if(mPlayerService.getMediaPlayer()==null)
return;
if(mPlayerService.getMediaPlayer().isPlaying()) {
changePlayPauseBtn(false);
mPlayerService.getMediaPlayer().pause();
}else {
changePlayPauseBtn(true);
mPlayerService.getMediaPlayer().start();
}*/
break;
case R.id.nextButton:
int ind = mCurrentMediaIndex + 1;
if(mediaArrayList.size()==ind)
ind = 0;
onUpdateMpUi(ind);
break;
case R.id.previousButton:
if(mCurrentMediaIndex == 0)
mCurrentMediaIndex = mediaArrayList.size()-1;
onUpdateMpUi(mCurrentMediaIndex);
break;
case R.id.shuffleButton:
break;
case R.id.repeatButton:
break;
}
}
@Override
public void onPause() {
super.onPause();
EventBus.getDefault().unregister(this);
/*if(mPlayerService!=null){
Media media = mediaArrayList.get(mCurrentMediaIndex);
mPlayerService.startNotification(media);
}*/
}
private void changePlayPauseBtn(boolean isPlaying) {
if ( isPlaying)
((ImageButton) findViewById(R.id.playPauseButton)).setImageResource(R.drawable.ic_action_pause);
else
((ImageButton) findViewById(R.id.playPauseButton)).setImageResource(R.drawable.ic_action_play);
}
@Override
protected void onResume() {
super.onResume();
Logger.print("onResume called");
EventBus.getDefault().register(this);
bindMusicService();
}
}
|
package com.tencent.smtt.sdk;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
class TbsLogReport$a {
private final String a;
private final String b;
public TbsLogReport$a(String str, String str2) {
this.a = str;
this.b = str2;
}
private static void a(File file) {
Throwable th;
RandomAccessFile randomAccessFile;
RandomAccessFile randomAccessFile2;
try {
randomAccessFile2 = new RandomAccessFile(file, "rw");
try {
int parseInt = Integer.parseInt("00001000", 2);
randomAccessFile2.seek(7);
int read = randomAccessFile2.read();
if ((read & parseInt) > 0) {
randomAccessFile2.seek(7);
randomAccessFile2.write(((parseInt ^ -1) & WebView.NORMAL_MODE_ALPHA) & read);
}
try {
randomAccessFile2.close();
} catch (IOException e) {
}
} catch (Exception e2) {
if (randomAccessFile2 != null) {
try {
randomAccessFile2.close();
} catch (IOException e3) {
}
}
} catch (Throwable th2) {
th = th2;
randomAccessFile = randomAccessFile2;
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e4) {
}
}
throw th;
}
} catch (Exception e5) {
randomAccessFile2 = null;
if (randomAccessFile2 != null) {
try {
randomAccessFile2.close();
} catch (IOException e32) {
}
}
} catch (Throwable th3) {
th = th3;
randomAccessFile = null;
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e42) {
}
}
throw th;
}
}
public void a() {
ZipOutputStream zipOutputStream;
BufferedInputStream bufferedInputStream;
Throwable th;
Throwable th2;
BufferedInputStream bufferedInputStream2;
ZipOutputStream zipOutputStream2;
FileOutputStream fileOutputStream;
FileOutputStream fileOutputStream2;
try {
fileOutputStream2 = new FileOutputStream(this.b);
try {
zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream2));
try {
byte[] bArr = new byte[2048];
String str = this.a;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(str);
try {
bufferedInputStream = new BufferedInputStream(fileInputStream, 2048);
} catch (Exception e) {
bufferedInputStream = null;
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e2) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e3) {
}
}
a(new File(this.b));
zipOutputStream.close();
fileOutputStream2.close();
} catch (Throwable th22) {
th = th22;
bufferedInputStream2 = null;
if (bufferedInputStream2 != null) {
try {
bufferedInputStream2.close();
} catch (IOException e4) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e5) {
}
}
throw th;
}
try {
zipOutputStream.putNextEntry(new ZipEntry(str.substring(str.lastIndexOf("/") + 1)));
while (true) {
int read = bufferedInputStream.read(bArr, 0, 2048);
if (read == -1) {
break;
}
zipOutputStream.write(bArr, 0, read);
}
zipOutputStream.flush();
zipOutputStream.closeEntry();
try {
bufferedInputStream.close();
} catch (IOException e6) {
}
try {
fileInputStream.close();
} catch (IOException e7) {
}
} catch (Exception e8) {
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e22) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e32) {
}
}
a(new File(this.b));
zipOutputStream.close();
fileOutputStream2.close();
} catch (Throwable th3) {
th = th3;
bufferedInputStream2 = bufferedInputStream;
if (bufferedInputStream2 != null) {
try {
bufferedInputStream2.close();
} catch (IOException e42) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e52) {
}
}
throw th;
}
} catch (Exception e9) {
bufferedInputStream = null;
fileInputStream = null;
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e222) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e322) {
}
}
a(new File(this.b));
zipOutputStream.close();
fileOutputStream2.close();
} catch (Throwable th222) {
th = th222;
bufferedInputStream2 = null;
fileInputStream = null;
if (bufferedInputStream2 != null) {
try {
bufferedInputStream2.close();
} catch (IOException e422) {
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e522) {
}
}
throw th;
}
a(new File(this.b));
try {
zipOutputStream.close();
} catch (IOException e10) {
}
try {
fileOutputStream2.close();
} catch (IOException e11) {
}
} catch (Exception e12) {
zipOutputStream2 = zipOutputStream;
fileOutputStream = fileOutputStream2;
} catch (Throwable th4) {
th222 = th4;
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e13) {
}
}
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e14) {
}
}
throw th222;
}
} catch (Exception e15) {
zipOutputStream2 = null;
fileOutputStream = fileOutputStream2;
if (zipOutputStream2 != null) {
try {
zipOutputStream2.close();
} catch (IOException e16) {
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e17) {
}
}
} catch (Throwable th5) {
th222 = th5;
zipOutputStream = null;
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e132) {
}
}
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e142) {
}
}
throw th222;
}
} catch (Exception e18) {
zipOutputStream2 = null;
fileOutputStream = null;
if (zipOutputStream2 != null) {
try {
zipOutputStream2.close();
} catch (IOException e162) {
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e172) {
}
}
} catch (Throwable th6) {
th222 = th6;
zipOutputStream = null;
fileOutputStream2 = null;
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e1322) {
}
}
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e1422) {
}
}
throw th222;
}
}
}
|
package com.gps.rahul.admin.myfragmentdemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class Fragment2 extends Fragment {
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> namelist=new ArrayList<String>();
String name;
ListView listView;
public Fragment2() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_fragment2, container, false);
Bundle bundle=getArguments();
if(bundle!=null) {
namelist = bundle.getStringArrayList("nm");
listView = (ListView) view.findViewById(R.id.lst_view);
arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, namelist);
listView.setAdapter(arrayAdapter);
}
return view;
}
}
|
/*
* 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 controller.action.postactions.personal.user;
import controller.action.postactions.personal.SetOrderStatus;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import javax.servlet.ServletException;
import model.dao.DaoEnum;
import model.dao.ServerOverloadedException;
import model.dao.SingletonPaymentTransaction;
import model.entity.Order;
import model.entity.User;
/**
*
* @author Sasha
*/
public class PayOrder extends SetOrderStatus {
/**
* Perform payment of the order
* @throws ServletException
* @throws IOException
*/
@Override
protected void doExecute() throws ServletException, IOException {
User user = (User) session.getAttribute("user");
if (user == null) {
sendRedirect(null, LOGIN_PLEASE, HOME_PAGE_LINK);
return;
}
String orderIdString = request.getParameter("orderId");
if (orderIdString == null) {
sendRedirect(null, NO_SUCH_ORDER);
return;
}
int orderId = Integer.parseInt(orderIdString);
Order order = getOrderById(orderId);
if (order == null) {
sendRedirect(null, NO_SUCH_ORDER);
return;
}
User updatedUser = getUserById(user.getId());
if ((updatedUser == null) || (updatedUser.getId() != user.getId())) {
sendRedirect(LOGIN_PLEASE, null);
return;
}
session.setAttribute("user", updatedUser);
BigDecimal price = order.getTotalPrice();
BigDecimal account = updatedUser.getAccount();
if (account.compareTo(price) < 0) {
sendRedirect("order.message.insufficientfunds", null);
return;
}
if (!remitPayment(updatedUser, order)) {
return;
}
sendRedirect("order.message.orderwaspayed", null);
}
/**
* Remit payment
* @param updatedUser user who do make payment
* @param order order under payment
* @return true if remit was successful
* @throws ServletException
* @throws IOException
*/
private boolean remitPayment(User updatedUser, Order order)
throws ServletException, IOException {
SingletonPaymentTransaction engine =
(SingletonPaymentTransaction) daoFactory.getCreator(DaoEnum.PAYMENT_TRANSACTION);
try {
if (!engine.makePayment(updatedUser, order)) {
sendRedirect(null, "order.errormessage.transactionwasnotperformed");
} else {
return true;
}
} catch (SQLException e) {
logger.info(e.getMessage());
sendRedirect(null, SQL_EXCEPTION);
} catch (ServerOverloadedException e) {
logger.info(e.getMessage());
sendRedirect(null, SERVER_OVERLOADED_EXCEPTION);
}
return false;
}
}
|
package com.ellalee.travelmaker;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CalendarSyncTest {
@Test
public void CalendarSyncTest() {
String newCalId = CalendarSync.newCalId;
assertEquals(newCalId, CalendarSync.newCalId);
}
}
|
package com.example.rsvaio.sendretreivedatafromdatabase;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button bSend,bLogin;
EditText tvName,tvAddress;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvName = (EditText)findViewById(R.id.tvName);
tvAddress = (EditText)findViewById(R.id.tvAddress);
bSend = (Button)findViewById(R.id.bSend);
bLogin = (Button)findViewById(R.id.bLogin);
tv1 = (TextView)findViewById(R.id.tv1);
bSend.setOnClickListener(this);
bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String name = tvName.getText().toString();
String address = tvAddress.getText().toString();
switch(v.getId()){
case R.id.bSend:
Post post = new Post(this);
post.execute(name,address);
break;
case R.id.bLogin:
Login login = new Login(this);
try {
String data = login.execute(name,address).get();
tv1.setText(data);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.