text stringlengths 10 2.72M |
|---|
package com.junyoung.searchwheretogoapi.constants;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum SourceType {
KAKAO(1),
NAVER(2);
private final Integer order;
}
|
package com.cl.earosb.iipzs.models;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import java.util.List;
/**
* Created by earosb on 16-10-15.
* Control de estandar es una Inspección
*/
@Table(name = "ControlEstandar")
public class ControlEstandar extends Model {
@Column(name = "causa")
public String causa;
@Column(name = "fecha")
public String fecha;
@Column(name = "fecha_title")
public String fecha_title;
@Column(name = "km_inicio")
public int km_inicio;
@Column(name = "obs")
public String obs;
@Column(name = "sync")
public boolean sync;
public ControlEstandar() {
super();
}
public static List<ControlEstandar> getAll(){
return new Select()
.from(ControlEstandar.class)
.orderBy("Id DESC")
.execute();
}
public List<Hectometro> getHectometros() {
return getMany(Hectometro.class, "controlEstandar");
}
public List<GeoVia> getGeo() {
return getMany(GeoVia.class, "controlEstandar");
}
@Override
public String toString() {
return "ControlEstandar{" +
"fecha='" + fecha + '\'' +
", km_inicio=" + km_inicio +
", sync=" + sync +
'}';
}
}
|
package ru.yandex.yamblz.ui.recyclerstuff;
import android.support.annotation.StringDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by dalexiv on 8/7/16.
*/
public class HighlightingStates {
@Retention(RetentionPolicy.SOURCE)
@StringDef({
WAS_DRAGGED,
WAS_PREV_DRAGGED
})
public @interface States{}
public static final String WAS_DRAGGED = "WAS_DRAGGED_TAG";
public static final String WAS_PREV_DRAGGED = "WAS_PREV_DRAGGED_TAG";
}
|
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Configuration options for dnsjava.
*
* <p>Boolean options:
*
* <ul>
* <li>BINDTTL - Print TTLs in BIND format
* <li>multiline - Print records in multiline format<br>
* <li>noPrintIN - Don't print the class of a record if it's IN<br>
* </ul>
*
* <p>Valued options:
*
* <ul>
* <li>tsigfudge=n - Sets the default TSIG fudge value (in seconds)
* <li>sig0validity=n - Sets the default SIG(0) validity period (in seconds)
* </ul>
*
* @author Brian Wellington
*/
public final class Options {
private static Map<String, String> table;
static {
try {
refresh();
} catch (SecurityException e) {
}
}
private Options() {}
public static void refresh() {
String s = System.getProperty("dnsjava.options");
if (s != null) {
StringTokenizer st = new StringTokenizer(s, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken();
int index = token.indexOf('=');
if (index == -1) {
set(token);
} else {
String option = token.substring(0, index);
String value = token.substring(index + 1);
set(option, value);
}
}
}
}
/** Clears all defined options */
public static void clear() {
table = null;
}
/** Sets an option to "true" */
public static void set(String option) {
if (table == null) {
table = new HashMap<>();
}
table.put(option.toLowerCase(), "true");
}
/** Sets an option to the the supplied value */
public static void set(String option, String value) {
if (table == null) {
table = new HashMap<>();
}
table.put(option.toLowerCase(), value.toLowerCase());
}
/** Removes an option */
public static void unset(String option) {
if (table == null) {
return;
}
table.remove(option.toLowerCase());
}
/** Checks if an option is defined */
public static boolean check(String option) {
if (table == null) {
return false;
}
return table.get(option.toLowerCase()) != null;
}
/** Returns the value of an option */
public static String value(String option) {
if (table == null) {
return null;
}
return table.get(option.toLowerCase());
}
/** Returns the value of an option as an integer, or -1 if not defined. */
public static int intValue(String option) {
String s = value(option);
if (s != null) {
try {
int val = Integer.parseInt(s);
if (val > 0) {
return val;
}
} catch (NumberFormatException e) {
}
}
return -1;
}
}
|
/**
* Package setting up a user dialogue based on menus and
* options. Please look at the <a href="https://github.com/alexandreMesle/CommandLine/wiki">wiki</a> *
* for a quickstart.
*/
package commandLineMenus; |
package com.bit2016.myapp.core.service;
import android.util.Log;
import com.bit2016.adroid.JSONResult;
import com.bit2016.myapp.core.domain.User;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Pack200;
/**
* Created by kickscar on 2016-12-01.
*/
public class UserService {
public List<User> fetchMockUserList() {
List<User> list = new ArrayList<User>();
// Mock Data
User user = new User();
user.setId( 1L );
user.setName( "안대혁" );
user.setPhone( "010-4761-6934" );
user.setEmail( "kickscar@gmail.com" );
user.setProfilePic("https://scontent-icn1-1.xx.fbcdn.net/v/t1.0-9/936089_1019758748039064_7187347097932848216_n.jpg?oh=ec46e4053b89bf9ea434f1cf79b6ce43&oe=58B4B3C8" );
user.setStatus( 1 );
list.add( user );
return list;
}
public List<User> fetchUserList() {
String url = "http://192.168.0.2:8088/myapp-api/api/user/list";
HttpRequest request = HttpRequest.get( url );
request.contentType( HttpRequest.CONTENT_TYPE_JSON );
request.accept( HttpRequest.CONTENT_TYPE_JSON );
request.connectTimeout( 1000 );
request.readTimeout( 30000 );
int responseCode = request.code();
if( responseCode != HttpURLConnection.HTTP_OK ) {
Log.e( "UserService", "fetchUserList() error : Not 200 OK" );
return null;
}
JSONResultUserList jsonResult = fromJSON( request, JSONResultUserList.class );
return jsonResult.getData();
}
protected <V> V fromJSON( HttpRequest request, Class<V> target ) {
V v = null;
try {
Gson gson = new GsonBuilder().create();
Reader reader = request.bufferedReader();
v = gson.fromJson(reader, target);
reader.close();
} catch( Exception ex ) {
Log.e( "UserService", "fromJSON error : " + ex );
throw new RuntimeException( ex );
}
return v;
}
private class JSONResultUserList extends JSONResult<List<User>>{};
}
|
/**
* When adding a new vehicle or model, you don't have to add new implementation classes.
*
* Wikipedia says
*
* The bridge pattern is a design pattern used in software engineering that is meant to
* "decouple an abstraction from its implementation so that the two can vary independently"
* отделять абстракцию от ее реализации, чтобы они могли независимо изменяться
*/
public class BridgeExample_01 {
public static void main(String[] args) {
Vehicle vehicle1 = new Car(new Toyota());
vehicle1.drive();
Vehicle vehicle2 = new Track(new Audi());
vehicle2.drive();
}
}
// Транспортное средство
abstract class Vehicle {
Model model;
public Vehicle(final Model model) {
this.model = model;
}
abstract void drive();
}
class Car extends Vehicle {
public Car(final Model model) {
super(model);
}
@Override
void drive() {
this.model.drive("Drive car");
}
}
class Track extends Vehicle {
public Track(final Model model) {
super(model);
}
@Override
void drive() {
this.model.drive("Drive track");
}
}
// The interface which is the vehicle model
interface Model {
void drive(String str);
}
class Audi implements Model {
@Override
public void drive(final String str) {
System.out.println(str + " (Audi)");
}
}
class Toyota implements Model {
@Override
public void drive(final String str) {
System.out.println(str + " (Toyota)");
}
}
|
package com.pwq.Enum;
/**
* @Author:WenqiangPu
* @Description
* @Date:Created in 14:24 2017/9/11
* @Modified By:
*/
public class EnumTest {
public static void main(String[] args) {
StatusCode statusCode = StatusCode.不支持初始密码登录;
System.out.println(statusCode.getCode());
System.out.println(statusCode.getMsg());
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.MethodInvoker;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* {@code ReflectionTestUtils} is a collection of reflection-based utility
* methods for use in unit and integration testing scenarios.
*
* <p>There are often times when it would be beneficial to be able to set a
* non-{@code public} field, invoke a non-{@code public} setter method, or
* invoke a non-{@code public} <em>configuration</em> or <em>lifecycle</em>
* callback method when testing code involving, for example:
*
* <ul>
* <li>ORM frameworks such as JPA and Hibernate which condone the usage of
* {@code private} or {@code protected} field access as opposed to
* {@code public} setter methods for properties in a domain entity.</li>
* <li>Spring's support for annotations such as
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired},
* {@link jakarta.inject.Inject @Inject}, and
* {@link jakarta.annotation.Resource @Resource} which provides dependency
* injection for {@code private} or {@code protected} fields, setter methods,
* and configuration methods.</li>
* <li>Use of annotations such as {@link jakarta.annotation.PostConstruct @PostConstruct}
* and {@link jakarta.annotation.PreDestroy @PreDestroy} for lifecycle callback
* methods.</li>
* </ul>
*
* <p>In addition, several methods in this class provide support for {@code static}
* fields and {@code static} methods — for example,
* {@link #setField(Class, String, Object)}, {@link #getField(Class, String)},
* {@link #invokeMethod(Class, String, Object...)},
* {@link #invokeMethod(Object, Class, String, Object...)}, etc.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 2.5
* @see ReflectionUtils
* @see AopTestUtils
*/
public abstract class ReflectionTestUtils {
private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get";
private static final Log logger = LogFactory.getLog(ReflectionTestUtils.class);
private static final boolean springAopPresent = ClassUtils.isPresent(
"org.springframework.aop.framework.Advised", ReflectionTestUtils.class.getClassLoader());
/**
* Set the {@linkplain Field field} with the given {@code name} on the
* provided {@code targetObject} to the supplied {@code value}.
* <p>This method delegates to {@link #setField(Object, String, Object, Class)},
* supplying {@code null} for the {@code type} argument.
* @param targetObject the target object on which to set the field; never {@code null}
* @param name the name of the field to set; never {@code null}
* @param value the value to set
*/
public static void setField(Object targetObject, String name, @Nullable Object value) {
setField(targetObject, name, value, null);
}
/**
* Set the {@linkplain Field field} with the given {@code name}/{@code type}
* on the provided {@code targetObject} to the supplied {@code value}.
* <p>This method delegates to {@link #setField(Object, Class, String, Object, Class)},
* supplying {@code null} for the {@code targetClass} argument.
* @param targetObject the target object on which to set the field; never {@code null}
* @param name the name of the field to set; may be {@code null} if
* {@code type} is specified
* @param value the value to set
* @param type the type of the field to set; may be {@code null} if
* {@code name} is specified
*/
public static void setField(Object targetObject, @Nullable String name, @Nullable Object value, @Nullable Class<?> type) {
setField(targetObject, null, name, value, type);
}
/**
* Set the static {@linkplain Field field} with the given {@code name} on
* the provided {@code targetClass} to the supplied {@code value}.
* <p>This method delegates to {@link #setField(Object, Class, String, Object, Class)},
* supplying {@code null} for the {@code targetObject} and {@code type} arguments.
* <p>This method does not support setting {@code static final} fields.
* @param targetClass the target class on which to set the static field;
* never {@code null}
* @param name the name of the field to set; never {@code null}
* @param value the value to set
* @since 4.2
*/
public static void setField(Class<?> targetClass, String name, @Nullable Object value) {
setField(null, targetClass, name, value, null);
}
/**
* Set the static {@linkplain Field field} with the given
* {@code name}/{@code type} on the provided {@code targetClass} to
* the supplied {@code value}.
* <p>This method delegates to {@link #setField(Object, Class, String, Object, Class)},
* supplying {@code null} for the {@code targetObject} argument.
* <p>This method does not support setting {@code static final} fields.
* @param targetClass the target class on which to set the static field;
* never {@code null}
* @param name the name of the field to set; may be {@code null} if
* {@code type} is specified
* @param value the value to set
* @param type the type of the field to set; may be {@code null} if
* {@code name} is specified
* @since 4.2
*/
public static void setField(
Class<?> targetClass, @Nullable String name, @Nullable Object value, @Nullable Class<?> type) {
setField(null, targetClass, name, value, type);
}
/**
* Set the {@linkplain Field field} with the given {@code name}/{@code type}
* on the provided {@code targetObject}/{@code targetClass} to the supplied
* {@code value}.
* <p>If the supplied {@code targetObject} is a <em>proxy</em>, it will
* be {@linkplain AopTestUtils#getUltimateTargetObject unwrapped} allowing
* the field to be set on the ultimate target of the proxy.
* <p>This method traverses the class hierarchy in search of the desired
* field. In addition, an attempt will be made to make non-{@code public}
* fields <em>accessible</em>, thus allowing one to set {@code protected},
* {@code private}, and <em>package-private</em> fields.
* <p>This method does not support setting {@code static final} fields.
* @param targetObject the target object on which to set the field; may be
* {@code null} if the field is static
* @param targetClass the target class on which to set the field; may
* be {@code null} if the field is an instance field
* @param name the name of the field to set; may be {@code null} if
* {@code type} is specified
* @param value the value to set
* @param type the type of the field to set; may be {@code null} if
* {@code name} is specified
* @since 4.2
* @see ReflectionUtils#findField(Class, String, Class)
* @see ReflectionUtils#makeAccessible(Field)
* @see ReflectionUtils#setField(Field, Object, Object)
* @see AopTestUtils#getUltimateTargetObject(Object)
*/
public static void setField(@Nullable Object targetObject, @Nullable Class<?> targetClass,
@Nullable String name, @Nullable Object value, @Nullable Class<?> type) {
Assert.isTrue(targetObject != null || targetClass != null,
"Either targetObject or targetClass for the field must be specified");
if (targetObject != null && springAopPresent) {
targetObject = AopTestUtils.getUltimateTargetObject(targetObject);
}
if (targetClass == null) {
targetClass = targetObject.getClass();
}
Field field = ReflectionUtils.findField(targetClass, name, type);
if (field == null) {
throw new IllegalArgumentException(String.format(
"Could not find field '%s' of type [%s] on %s or target class [%s]", name, type,
safeToString(targetObject), targetClass));
}
if (logger.isDebugEnabled()) {
logger.debug(String.format(
"Setting field '%s' of type [%s] on %s or target class [%s] to value [%s]", name, type,
safeToString(targetObject), targetClass, value));
}
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, targetObject, value);
}
/**
* Get the value of the {@linkplain Field field} with the given {@code name}
* from the provided {@code targetObject}.
* <p>This method delegates to {@link #getField(Object, Class, String)},
* supplying {@code null} for the {@code targetClass} argument.
* @param targetObject the target object from which to get the field;
* never {@code null}
* @param name the name of the field to get; never {@code null}
* @return the field's current value
* @see #getField(Class, String)
*/
@Nullable
public static Object getField(Object targetObject, String name) {
return getField(targetObject, null, name);
}
/**
* Get the value of the static {@linkplain Field field} with the given
* {@code name} from the provided {@code targetClass}.
* <p>This method delegates to {@link #getField(Object, Class, String)},
* supplying {@code null} for the {@code targetObject} argument.
* @param targetClass the target class from which to get the static field;
* never {@code null}
* @param name the name of the field to get; never {@code null}
* @return the field's current value
* @since 4.2
* @see #getField(Object, String)
*/
@Nullable
public static Object getField(Class<?> targetClass, String name) {
return getField(null, targetClass, name);
}
/**
* Get the value of the {@linkplain Field field} with the given {@code name}
* from the provided {@code targetObject}/{@code targetClass}.
* <p>If the supplied {@code targetObject} is a <em>proxy</em>, it will
* be {@linkplain AopTestUtils#getUltimateTargetObject unwrapped} allowing
* the field to be retrieved from the ultimate target of the proxy.
* <p>This method traverses the class hierarchy in search of the desired
* field. In addition, an attempt will be made to make non-{@code public}
* fields <em>accessible</em>, thus allowing one to get {@code protected},
* {@code private}, and <em>package-private</em> fields.
* @param targetObject the target object from which to get the field; may be
* {@code null} if the field is static
* @param targetClass the target class from which to get the field; may
* be {@code null} if the field is an instance field
* @param name the name of the field to get; never {@code null}
* @return the field's current value
* @since 4.2
* @see #getField(Object, String)
* @see #getField(Class, String)
* @see ReflectionUtils#findField(Class, String, Class)
* @see ReflectionUtils#makeAccessible(Field)
* @see ReflectionUtils#getField(Field, Object)
* @see AopTestUtils#getUltimateTargetObject(Object)
*/
@Nullable
public static Object getField(@Nullable Object targetObject, @Nullable Class<?> targetClass, String name) {
Assert.isTrue(targetObject != null || targetClass != null,
"Either targetObject or targetClass for the field must be specified");
if (targetObject != null && springAopPresent) {
targetObject = AopTestUtils.getUltimateTargetObject(targetObject);
}
if (targetClass == null) {
targetClass = targetObject.getClass();
}
Field field = ReflectionUtils.findField(targetClass, name);
if (field == null) {
throw new IllegalArgumentException(String.format("Could not find field '%s' on %s or target class [%s]",
name, safeToString(targetObject), targetClass));
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("Getting field '%s' from %s or target class [%s]", name,
safeToString(targetObject), targetClass));
}
ReflectionUtils.makeAccessible(field);
return ReflectionUtils.getField(field, targetObject);
}
/**
* Invoke the setter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> setter methods.
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to set the {@code name} property on the
* target object, you may pass either "name" or
* "setName" as the method name.
* @param target the target object on which to invoke the specified setter
* method
* @param name the name of the setter method to invoke or the corresponding
* property name
* @param value the value to provide to the setter method
* @see ReflectionUtils#findMethod(Class, String, Class[])
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
*/
public static void invokeSetterMethod(Object target, String name, Object value) {
invokeSetterMethod(target, name, value, null);
}
/**
* Invoke the setter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> setter methods.
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to set the {@code name} property on the
* target object, you may pass either "name" or
* "setName" as the method name.
* @param target the target object on which to invoke the specified setter
* method
* @param name the name of the setter method to invoke or the corresponding
* property name
* @param value the value to provide to the setter method
* @param type the formal parameter type declared by the setter method
* @see ReflectionUtils#findMethod(Class, String, Class[])
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
*/
public static void invokeSetterMethod(Object target, String name, @Nullable Object value, @Nullable Class<?> type) {
Assert.notNull(target, "Target object must not be null");
Assert.hasText(name, "Method name must not be empty");
Class<?>[] paramTypes = (type != null ? new Class<?>[] {type} : null);
String setterMethodName = name;
if (!name.startsWith(SETTER_PREFIX)) {
setterMethodName = SETTER_PREFIX + StringUtils.capitalize(name);
}
Method method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
if (method == null && !setterMethodName.equals(name)) {
setterMethodName = name;
method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
}
if (method == null) {
throw new IllegalArgumentException(String.format(
"Could not find setter method '%s' on %s with parameter type [%s]", setterMethodName,
safeToString(target), type));
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName,
safeToString(target), value));
}
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, target, value);
}
/**
* Invoke the getter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> getter methods.
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to get the {@code name} property on the
* target object, you may pass either "name" or
* "getName" as the method name.
* @param target the target object on which to invoke the specified getter
* method
* @param name the name of the getter method to invoke or the corresponding
* property name
* @return the value returned from the invocation
* @see ReflectionUtils#findMethod(Class, String, Class[])
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
*/
@Nullable
public static Object invokeGetterMethod(Object target, String name) {
Assert.notNull(target, "Target object must not be null");
Assert.hasText(name, "Method name must not be empty");
String getterMethodName = name;
if (!name.startsWith(GETTER_PREFIX)) {
getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
}
Method method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
if (method == null && !getterMethodName.equals(name)) {
getterMethodName = name;
method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
}
if (method == null) {
throw new IllegalArgumentException(String.format(
"Could not find getter method '%s' on %s", getterMethodName, safeToString(target)));
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("Invoking getter method '%s' on %s", getterMethodName, safeToString(target)));
}
ReflectionUtils.makeAccessible(method);
return ReflectionUtils.invokeMethod(method, target);
}
/**
* Invoke the method with the given {@code name} on the supplied target
* object with the supplied arguments.
* <p>This method delegates to {@link #invokeMethod(Object, Class, String, Object...)},
* supplying {@code null} for the {@code targetClass} argument.
* @param target the target object on which to invoke the specified method
* @param name the name of the method to invoke
* @param args the arguments to provide to the method
* @return the invocation result, if any
* @see #invokeMethod(Class, String, Object...)
* @see #invokeMethod(Object, Class, String, Object...)
* @see MethodInvoker
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
* @see ReflectionUtils#handleReflectionException(Exception)
*/
@Nullable
public static <T> T invokeMethod(Object target, String name, Object... args) {
Assert.notNull(target, "Target object must not be null");
return invokeMethod(target, null, name, args);
}
/**
* Invoke the static method with the given {@code name} on the supplied target
* class with the supplied arguments.
* <p>This method delegates to {@link #invokeMethod(Object, Class, String, Object...)},
* supplying {@code null} for the {@code targetObject} argument.
* @param targetClass the target class on which to invoke the specified method
* @param name the name of the method to invoke
* @param args the arguments to provide to the method
* @return the invocation result, if any
* @since 5.2
* @see #invokeMethod(Object, String, Object...)
* @see #invokeMethod(Object, Class, String, Object...)
* @see MethodInvoker
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
* @see ReflectionUtils#handleReflectionException(Exception)
*/
@Nullable
public static <T> T invokeMethod(Class<?> targetClass, String name, Object... args) {
Assert.notNull(targetClass, "Target class must not be null");
return invokeMethod(null, targetClass, name, args);
}
/**
* Invoke the method with the given {@code name} on the provided
* {@code targetObject}/{@code targetClass} with the supplied arguments.
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> methods.
* @param targetObject the target object on which to invoke the method; may
* be {@code null} if the method is static
* @param targetClass the target class on which to invoke the method; may
* be {@code null} if the method is an instance method
* @param name the name of the method to invoke
* @param args the arguments to provide to the method
* @return the invocation result, if any
* @since 5.2
* @see #invokeMethod(Object, String, Object...)
* @see #invokeMethod(Class, String, Object...)
* @see MethodInvoker
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
* @see ReflectionUtils#handleReflectionException(Exception)
*/
@SuppressWarnings("unchecked")
@Nullable
public static <T> T invokeMethod(@Nullable Object targetObject, @Nullable Class<?> targetClass, String name,
Object... args) {
Assert.isTrue(targetObject != null || targetClass != null,
"Either 'targetObject' or 'targetClass' for the method must be specified");
Assert.hasText(name, "Method name must not be empty");
try {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(targetObject);
if (targetClass != null) {
methodInvoker.setTargetClass(targetClass);
}
methodInvoker.setTargetMethod(name);
methodInvoker.setArguments(args);
methodInvoker.prepare();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Invoking method '%s' on %s or %s with arguments %s", name,
safeToString(targetObject), safeToString(targetClass), ObjectUtils.nullSafeToString(args)));
}
return (T) methodInvoker.invoke();
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
throw new IllegalStateException("Should never get here");
}
}
private static String safeToString(@Nullable Object target) {
try {
return String.format("target object [%s]", target);
}
catch (Exception ex) {
return String.format("target of type [%s] whose toString() method threw [%s]",
(target != null ? target.getClass().getName() : "unknown"), ex);
}
}
private static String safeToString(@Nullable Class<?> clazz) {
return String.format("target class [%s]", (clazz != null ? clazz.getName() : null));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package scp.controllers;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import scp.config.ConfiguracaoGlobal;
import scp.main.Principal;
public class SobreController implements Initializable {
@FXML
private ImageView imagem;
@FXML
private Label nome_empresa;
@FXML
private Label versao;
@FXML
private Label telefone;
@FXML
private Label site;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
atribuirValores();
}
private void atribuirValores(){
Image img = new Image(Principal.class.getResourceAsStream("/scp/imgs/"+ConfiguracaoGlobal.getLOGO_EMPRESA()));
imagem.setImage(img);
nome_empresa.setText(ConfiguracaoGlobal.getNOME_EMPRESA());
versao.setText("Versão : "+ConfiguracaoGlobal.getVERSAO());
telefone.setText("Contato : "+ConfiguracaoGlobal.getTELEFONE());
site.setText(ConfiguracaoGlobal.getSITE());
}
}
|
package com.kangyonggan.app.simconf.config;
import com.kangyonggan.app.simconf.exception.ConfigException;
import com.kangyonggan.app.simconf.util.PropertiesUtil;
import lombok.extern.log4j.Log4j2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* @author kangyonggan
* @since 2017/2/16
*/
@Log4j2
public class Config {
private Properties props;
/**
* @param resourcePath
* @throws ConfigException
*/
public Config(String resourcePath) throws ConfigException {
loadProperties(PropertiesUtil.getProperties("config.root.path") + resourcePath + "/config.properties");
}
/**
* 加载配置
*
* @param resourcePath
* @throws ConfigException
*/
private void loadProperties(String resourcePath) throws ConfigException {
props = new Properties();
FileInputStream fis;
try {
fis = new FileInputStream(new File(resourcePath));
} catch (FileNotFoundException e) {
throw new ConfigException("配置文件不存在");
}
InputStreamReader reader;
try {
reader = new InputStreamReader(fis, "UTF-8");
props.load(reader);
} catch (Exception e) {
throw new ConfigException("加载配置文件失败");
}
}
/**
* 获取公钥路径
*
* @return
*/
public String getPublicKeyPath() {
return getPropertiesOrDefault("publicKeyPath", "");
}
/**
* 获取私钥路径
*
* @return
*/
public String getPrivateKeyPath() {
return getPropertiesOrDefault("privateKeyPath", "");
}
/**
* 获取properties的值,默认值""
*
* @param name
* @return
*/
public String getProperties(String name) {
return getPropertiesOrDefault(name, "");
}
/**
* 获取properties的值
*
* @param name
* @param defaultValue 默认值
* @return
*/
public String getPropertiesOrDefault(String name, String defaultValue) {
return props.getProperty(name, defaultValue);
}
}
|
package com.radius.sodalityUser.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import javax.json.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.radius.sodalityUser.common.Commonfunction;
import com.radius.sodalityUser.model.Notice;
import com.radius.sodalityUser.model.User;
import com.radius.sodalityUser.model.UserType.noticeType;
import com.radius.sodalityUser.repository.NoticeRepository;
import com.radius.sodalityUser.repository.UserRepositoryImpl;
import com.radius.sodalityUser.response.NoticeResponseJson;
import com.radius.sodalityUser.response.NoticeResponseList;
import com.radius.sodalityUser.response.SocietyJson;
import io.micrometer.core.instrument.util.StringUtils;
@Service
public class NoticeServiceImpl implements NoticeService {
@Autowired
Commonfunction fun;
@Autowired
NoticeRepository noticeRepo;
@Autowired
UserRepositoryImpl userRepo;
@Override
public Notice addNotice(MultipartFile[] uploadfiles, JsonObject requestBody) {
// TODO Auto-generated method stub
Notice notice = new Notice();
if (requestBody.containsKey("title")) {
notice.setTitle(requestBody.getString("title"));
}
if (requestBody.containsKey("description")) {
notice.setDescription(requestBody.getString("description"));
}
if (requestBody.containsKey("noticeTo")) {
notice.setNoticeTo(requestBody.getString("noticeTo"));
}
Date d = new Date();
notice.setCreatedDate(d);
notice.setUpdatedDate(d);
notice.setUuid(fun.uuIDSend());
notice.setType(noticeType.notice);
notice.setParrentAccount(userRepo.findById(Long.parseLong(requestBody.getJsonNumber("id").toString())).get());
String ImagesListfileName = Arrays.stream(uploadfiles).map(x -> {
return x.getOriginalFilename();
}).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
ArrayList<String> listimage = new ArrayList<String>();
ArrayList setData = null;
if (StringUtils.isEmpty(ImagesListfileName)) {
} else {
try {
listimage = fun.saveUploadedFiles(Arrays.asList(uploadfiles));
setData = (listimage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notice.setImage(setData);
noticeRepo.save(notice);
return notice;
}
@Override
public Notice updateNotice(MultipartFile[] uploadfiles, JsonObject requestBody) {
// TODO Auto-generated method stub
String path = "/images/";
Notice notice = new Notice();
notice = noticeRepo.findById(Long.parseLong(requestBody.getJsonNumber("noticeId").toString())).get();
Date d = new Date();
notice.setUpdatedDate(d);
if (requestBody.containsKey("title")) {
notice.setTitle(requestBody.getString("title"));
}
if (requestBody.containsKey("description")) {
notice.setDescription(requestBody.getString("description"));
}
if (requestBody.containsKey("noticeTo")) {
notice.setNoticeTo(requestBody.getString("noticeTo"));
}
String ImagesListfileName = Arrays.stream(uploadfiles).map(x -> {
return x.getOriginalFilename();
}).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
ArrayList<String> listimage = new ArrayList<String>();
if (StringUtils.isEmpty(ImagesListfileName)) {
} else {
try {
listimage = fun.saveUploadedFiles(Arrays.asList(uploadfiles));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (requestBody.containsKey("images")) {
for (int i = 0; i < requestBody.getJsonArray("images").size(); i++) {
System.out.println(path + requestBody.getJsonArray("images").getString(i));
String Newpath = path + requestBody.getJsonArray("images").getString(i);
System.out.println(Newpath);
listimage.add(Newpath);
}
}
notice.setImage(listimage);
noticeRepo.save(notice);
return notice;
}
@Override
public NoticeResponseList getAllNotice(JsonObject requestBody) {
// TODO Auto-generated method stub
String type = "";
if (requestBody.containsKey("type")) {
type = requestBody.getString("type");
} else {
type = "";
}
ArrayList<Notice> NoticeList;
NoticeResponseList jsonResponse = new NoticeResponseList();
if (type.isEmpty()) {
NoticeList = noticeRepo.getAllNotice(requestBody.getString("parentUUid"));
} else {
NoticeList = noticeRepo.getAllNotice(requestBody.getString("parentUUid"));
}
ArrayList<NoticeResponseJson> list = new ArrayList();
jsonResponse.setStatus(false);
for (int counter = 0; counter < NoticeList.size(); counter++) {
NoticeResponseJson json = new NoticeResponseJson();
json.setTitle(NoticeList.get(counter).getTitle());
json.setType(NoticeList.get(counter).getType());
json.setCreatedDate(NoticeList.get(counter).getCreatedDate());
json.setDescription(NoticeList.get(counter).getDescription());
json.setUpdatedDate(NoticeList.get(counter).getUpdatedDate());
json.setUuid(NoticeList.get(counter).getUuid());
list.add(json);
jsonResponse.setStatus(true);
}
jsonResponse.setData(list);
return jsonResponse;
}
@Override
public Notice getNotice(String uuid) {
// TODO Auto-generated method stub
return noticeRepo.getNoticeDetail(uuid);
}
@Override
public NoticeResponseList getAllNotification(JsonObject returnJsonObject) {
// TODO Auto-generated method stub
ArrayList<Notice> NoticeList;
NoticeResponseList jsonResponse = new NoticeResponseList();
NoticeList = noticeRepo.getAllNotification(returnJsonObject.getString("parentUUid"));
ArrayList<NoticeResponseJson> list = new ArrayList<NoticeResponseJson>();
jsonResponse.setStatus(false);
for (int counter = 0; counter < NoticeList.size(); counter++) {
NoticeResponseJson json = new NoticeResponseJson();
json.setTitle(NoticeList.get(counter).getTitle());
json.setType(NoticeList.get(counter).getType());
json.setCreatedDate(NoticeList.get(counter).getCreatedDate());
json.setDescription(NoticeList.get(counter).getDescription());
json.setUpdatedDate(NoticeList.get(counter).getUpdatedDate());
json.setUuid(NoticeList.get(counter).getUuid());
json.setType(NoticeList.get(counter).getType());
json.setImagelist(NoticeList.get(counter).getImage());
json.setUserImage(NoticeList.get(counter).getParrentAccount().getSocietyDetail().getSocietyLogo());
json.setUserName(NoticeList.get(counter).getParrentAccount().getSocietyDetail().getSocietyDisplayName());
json.setNoticeTo(NoticeList.get(counter).getNoticeTo());
if (NoticeList.get(counter).getDisccusionBy() != null) {
json.setDiscussBy(NoticeList.get(counter).getDisccusionBy().getUuid());
json.setUserImage(NoticeList.get(counter).getDisccusionBy().getResidentDetail().getProfileImage());
json.setUserName(NoticeList.get(counter).getDisccusionBy().getResidentDetail().getFirstName());
}
list.add(json);
jsonResponse.setStatus(true);
}
jsonResponse.setData(list);
return jsonResponse;
}
@Override
public Notice addDisccusion(MultipartFile[] uploadfiles, JsonObject requestBody) {
// TODO Auto-generated method stub
Notice notice = new Notice();
if (requestBody.containsKey("title")) {
notice.setTitle(requestBody.getString("title"));
}
if (requestBody.containsKey("description")) {
notice.setDescription(requestBody.getString("description"));
}
if (requestBody.containsKey("noticeTo")) {
notice.setNoticeTo(requestBody.getString("noticeTo"));
}
Date d = new Date();
notice.setCreatedDate(d);
notice.setUpdatedDate(d);
notice.setUuid(fun.uuIDSend());
notice.setType(noticeType.discussion);
notice.setParrentAccount(userRepo.getParentUuid(requestBody.getString("uuid")));
notice.setDisccusionBy(userRepo.getUser(requestBody.getString("uuid")));
String ImagesListfileName = Arrays.stream(uploadfiles).map(x -> {
return x.getOriginalFilename();
}).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
ArrayList<String> listimage = new ArrayList<String>();
ArrayList setData = null;
if (StringUtils.isEmpty(ImagesListfileName)) {
} else {
try {
listimage = fun.saveUploadedFiles(Arrays.asList(uploadfiles));
setData = (listimage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notice.setImage(setData);
noticeRepo.save(notice);
return notice;
}
@Override
public Notice updateDisccusion(MultipartFile[] uploadfiles, JsonObject requestBody) {
// TODO Auto-generated method stub
String path = "/images/";
Notice notice = null;
notice = noticeRepo.findById(Long.parseLong(requestBody.getJsonNumber("noticeId").toString())).get();
Date d = new Date();
notice.setUpdatedDate(d);
if (requestBody.containsKey("title")) {
notice.setTitle(requestBody.getString("title"));
}
if (requestBody.containsKey("description")) {
notice.setDescription(requestBody.getString("description"));
}
if (requestBody.containsKey("noticeTo")) {
notice.setNoticeTo(requestBody.getString("noticeTo"));
}
String ImagesListfileName = Arrays.stream(uploadfiles).map(x -> {
return x.getOriginalFilename();
}).filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
ArrayList<String> listimage = new ArrayList<String>();
if (StringUtils.isEmpty(ImagesListfileName)) {
} else {
try {
listimage = fun.saveUploadedFiles(Arrays.asList(uploadfiles));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (requestBody.containsKey("images")) {
for (int i = 0; i < requestBody.getJsonArray("images").size(); i++) {
System.out.println(path + requestBody.getJsonArray("images").getString(i));
String Newpath = path + requestBody.getJsonArray("images").getString(i);
System.out.println(Newpath);
listimage.add(Newpath);
}
}
notice.setImage(listimage);
noticeRepo.save(notice);
return notice;
}
@Override
public NoticeResponseList getAllDisccusion(JsonObject requestBody) {
// TODO Auto-generated method stub
String type = "";
if (requestBody.containsKey("type")) {
type = requestBody.getString("type");
} else {
type = "";
}
ArrayList<Notice> NoticeList;
NoticeResponseList jsonResponse = new NoticeResponseList();
if (type.isEmpty()) {
NoticeList = noticeRepo.getAllDisccusion(requestBody.getString("parentUUid"));
} else {
NoticeList = noticeRepo.getAllDisccusion(requestBody.getString("parentUUid"));
}
ArrayList<NoticeResponseJson> list = new ArrayList();
jsonResponse.setStatus(false);
for (int counter = 0; counter < NoticeList.size(); counter++) {
NoticeResponseJson json = new NoticeResponseJson();
json.setTitle(NoticeList.get(counter).getTitle());
json.setType(NoticeList.get(counter).getType());
json.setCreatedDate(NoticeList.get(counter).getCreatedDate());
json.setDescription(NoticeList.get(counter).getDescription());
json.setUpdatedDate(NoticeList.get(counter).getUpdatedDate());
json.setUuid(NoticeList.get(counter).getUuid());
list.add(json);
jsonResponse.setStatus(true);
}
jsonResponse.setData(list);
return jsonResponse;
}
@Override
public Notice getDisccusionDetail(String uuid) {
// TODO Auto-generated method stub
return noticeRepo.getNoticeDetail(uuid);
}
}
|
package kodlama.io.hrms.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import kodlama.io.hrms.business.abstracts.CoverLetterService;
import kodlama.io.hrms.core.utilities.results.DataResult;
import kodlama.io.hrms.core.utilities.results.Result;
import kodlama.io.hrms.entities.concretes.CoverLetter;
@RestController
@RequestMapping("/api/coverletters")
@CrossOrigin
public class CoverLetteController {
private CoverLetterService coverLetterService;
@Autowired
public CoverLetteController(CoverLetterService coverLetterService) {
super();
this.coverLetterService = coverLetterService;
}
@PostMapping("/add")
public Result add(@RequestBody CoverLetter coverLetter) {
return this.coverLetterService.add(coverLetter);
}
@PostMapping("/update")
public Result update(@RequestBody CoverLetter coverLetter) {
return this.coverLetterService.update(coverLetter);
}
@PostMapping("/delete")
public Result delete(@RequestParam("id") int id) {
return this.coverLetterService.delete(id);
}
@GetMapping("/getbyid")
public DataResult<CoverLetter> getById(@RequestParam("id") int id) {
return this.coverLetterService.getById(id);
}
@GetMapping("/getall")
public DataResult<List<CoverLetter>> getAll() {
return this.coverLetterService.getAll();
}
}
|
package com.max.harrax;
import static org.lwjgl.glfw.GLFW.GLFW_PRESS;
import static org.lwjgl.glfw.GLFW.GLFW_RELEASE;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints;
import static org.lwjgl.glfw.GLFW.glfwDestroyWindow;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.glfw.GLFW.glfwPollEvents;
import static org.lwjgl.glfw.GLFW.glfwSetCursorPosCallback;
import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback;
import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback;
import static org.lwjgl.glfw.GLFW.glfwSetMouseButtonCallback;
import static org.lwjgl.glfw.GLFW.glfwSetWindowCloseCallback;
import static org.lwjgl.glfw.GLFW.glfwSetWindowSizeCallback;
import static org.lwjgl.glfw.GLFW.glfwSwapBuffers;
import static org.lwjgl.glfw.GLFW.glfwTerminate;
import static org.lwjgl.opengl.GL11.GL_RENDERER;
import static org.lwjgl.opengl.GL11.GL_VENDOR;
import static org.lwjgl.opengl.GL11.GL_VERSION;
import static org.lwjgl.opengl.GL11.glGetString;
import com.max.harrax.events.Event;
import com.max.harrax.events.KeyCode;
import com.max.harrax.events.KeyPressedEvent;
import com.max.harrax.events.KeyReleasedEvent;
import com.max.harrax.events.MouseButtonPressedEvent;
import com.max.harrax.events.MouseButtonReleasedEvent;
import com.max.harrax.events.MouseMovedEvent;
import com.max.harrax.events.WindowCloseEvent;
import com.max.harrax.events.WindowResizeEvent;
import org.lwjgl.glfw.GLFWCursorPosCallback;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWMouseButtonCallback;
import org.lwjgl.glfw.GLFWWindowCloseCallback;
import org.lwjgl.glfw.GLFWWindowSizeCallback;
import org.lwjgl.opengl.GL;
public class Window {
private String title;
private int width, height;
private final long window;
GLFWErrorCallback errorCallback;
GLFWWindowCloseCallback windowCloseCallback;
GLFWWindowSizeCallback windowSizeCallback;
GLFWKeyCallback keyCallback;
GLFWMouseButtonCallback mouseButtonCallback;
GLFWCursorPosCallback cursorPosCallback;
public Window(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;
if (!glfwInit())
throw new IllegalStateException("Unable to initialize GLFW!");
glfwSetErrorCallback(errorCallback = GLFWErrorCallback.createPrint(System.err));
glfwDefaultWindowHints();
window = glfwCreateWindow(width, height, title, 0, 0);
glfwMakeContextCurrent(window);
GL.createCapabilities();
String vendor = glGetString(GL_VENDOR);
String renderer = glGetString(GL_RENDERER);
String version = glGetString(GL_VERSION);
System.out.printf("[Vendor]: %s\n", vendor);
System.out.printf("[Renderer]: %s\n", renderer);
System.out.printf("[Version]: %s\n", version);
glfwSetWindowCloseCallback(window, windowCloseCallback = GLFWWindowCloseCallback.create((window) -> {
Event event = new WindowCloseEvent();
Application.get().onEvent(event);
}));
glfwSetKeyCallback(window, keyCallback = GLFWKeyCallback.create((window, key, scancode, action, mods) -> {
switch (action) {
case GLFW_PRESS:
for (KeyCode kc : KeyCode.values()) {
if (kc.code == key)
Application.get().onEvent(new KeyPressedEvent(kc));
}
break;
case GLFW_RELEASE:
for (KeyCode kc : KeyCode.values()) {
if (kc.code == key)
Application.get().onEvent(new KeyReleasedEvent(kc));
}
break;
}
}));
glfwSetMouseButtonCallback(window,
mouseButtonCallback = GLFWMouseButtonCallback.create((window, button, action, mods) -> {
Event event;
switch (action) {
case GLFW_PRESS:
event = new MouseButtonPressedEvent(button);
Application.get().onEvent(event);
break;
case GLFW_RELEASE:
event = new MouseButtonReleasedEvent(button);
Application.get().onEvent(event);
break;
}
}));
glfwSetCursorPosCallback(window, cursorPosCallback = GLFWCursorPosCallback.create((window, xpos, ypos) -> {
Event event = new MouseMovedEvent((float) xpos, (float) ypos);
Application.get().onEvent(event);
}));
glfwSetWindowSizeCallback(window, windowSizeCallback = GLFWWindowSizeCallback.create((window, w, h) -> {
Event event = new WindowResizeEvent(w, h);
Application.get().onEvent(event);
}));
}
public void onUpdate() {
glfwPollEvents();
glfwSwapBuffers(window);
}
public void dispose() {
errorCallback.free();
windowCloseCallback.free();
keyCallback.free();
mouseButtonCallback.free();
cursorPosCallback.free();
glfwDestroyWindow(window);
glfwTerminate();
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
|
package com.example.mauricio.simpleDagger2WithMockito;
import android.databinding.ObservableField;
/**
* Created by mauricio on 8/30/16.
*/
public class MainViewModel {
public ObservableField<String> text = new ObservableField<>();
}
|
public class AddBinary {
public String addBinary(String a, String b) {
int aPos = a.length() - 1, bPos = b.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (aPos >= 0 && bPos >= 0) {
int aL = a.charAt(aPos) - '0';
int bL = b.charAt(bPos) - '0';
int bitSum = aL + bL + carry;
if (bitSum > 1) {
bitSum -= 2;
carry = 1;
} else {
carry = 0;
}
aPos--;
bPos--;
sb.append(bitSum);
}
while (aPos >= 0) {
int aL = a.charAt(aPos) - '0';
int bitSum = aL + carry;
if (bitSum > 1) {
bitSum -= 2;
carry = 1;
} else {
carry = 0;
}
aPos--;
sb.append(bitSum);
}
while (bPos >= 0) {
int bL = b.charAt(bPos) - '0';
int bitSum = bL + carry;
if (bitSum > 1) {
bitSum -= 2;
carry = 1;
} else {
carry = 0;
}
bPos--;
sb.append(bitSum);
}
if (carry == 1) {
StringBuilder sb1 = new StringBuilder();
sb1.append(1);
sb1.append(new StringBuilder(sb.toString()).reverse().toString());
return sb1.toString();
}
return new StringBuilder(sb.toString()).reverse().toString();
}
}
class AddBinaryTest {
public static void main(String[] args) {
System.out.println(new AddBinary().addBinary("101", "100"));
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.validation.beanvalidation;
import java.lang.reflect.Method;
import org.hibernate.validator.constraints.URL;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.MergedAnnotations;
/**
* Smoke tests specific to the combination of {@link MergedAnnotations}
* and Bean Validation constraint annotations.
*
* @author Sam Brannen
* @since 6.0
*/
class BeanValidationMergedAnnotationsTests {
@Disabled("This test should only be run manually to inspect log messages")
@Test
@URL
void constraintAnnotationOnMethod() throws Exception {
// If the issue raised in gh-29206 had not been addressed, we would see
// a log message similar to the following.
// 19:07:33.848 [main] WARN o.s.c.a.AnnotationTypeMapping - Support for
// convention-based annotation attribute overrides is deprecated and will
// be removed in Spring Framework 6.1. Please annotate the following attributes
// in @org.hibernate.validator.constraints.URL with appropriate @AliasFor
// declarations: [regexp, payload, flags, groups, message]
Method method = getClass().getDeclaredMethod("constraintAnnotationOnMethod");
MergedAnnotations mergedAnnotations = MergedAnnotations.from(method);
mergedAnnotations.get(URL.class);
}
}
|
package com.myvodafone.android.business.managers;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Html;
import android.text.SpannableString;
import android.util.Pair;
import com.myvodafone.android.R;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.service.Action_bundle;
import com.myvodafone.android.model.service.Bundle_item;
import com.myvodafone.android.model.service.EligibleBundles;
import com.myvodafone.android.model.view.BundlePurchaseCategories;
import com.myvodafone.android.model.view.PostPayBundlePurchaseCategories;
import com.myvodafone.android.model.view.PrePayBundlePurchaseCategories;
import com.myvodafone.android.model.view.VFModelBundleItemPurchase;
import com.myvodafone.android.model.view.VFModelBundleItemsPurchase;
import com.myvodafone.android.service.DataHandler;
import com.myvodafone.android.utils.GlobalData;
import com.myvodafone.android.utils.StaticTools;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.List;
/**
* Created by kakaso on 3/21/2016.
*/
public class PrePayBundlePurchaseManager {
public static String ERROR_EMPTY = "ERROR_EMPTY";
public interface PrePayBundlePurchaseListener {
void onSuccessBundleList();
void onErrorBundleList(String message);
void onGenericErrorBundleList();
}
public interface BundlePurchaseActionListener{
void onSuccessBundleAction(String action,String message);
void onErrorBundleAction(String message);
void onGenericErrorBundleAction();
}
public static void getEligiblePrepayBundles(Context context, VFAccount account, WeakReference<PrePayBundlePurchaseListener> listener){
new EligibleBundlesAsync(context, account, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static class EligibleBundlesAsync extends AsyncTask<Void,Void,Void>{
EligibleBundles response;
Context context;
WeakReference<PrePayBundlePurchaseListener> callback;
VFAccount account;
public EligibleBundlesAsync(Context context, VFAccount account, WeakReference<PrePayBundlePurchaseListener> listener){
this.context = context;
this.callback = listener;
this.account = account;
}
@Override
protected Void doInBackground(Void... params) {
String msisdn = account.getSelectedAccountNumber();
if(StaticTools.isBizAdmin(account)){
msisdn = MemoryCacheManager.getSelectedBizMsisdn();
}
String cos = (StaticTools.getAccountMsisdn(MemoryCacheManager.getSelectedAccount()).equals(msisdn)?
(MemoryCacheManager.getSelectedAccount().getCos() + "|" + GlobalData.APP_VERSION) : "|"+ GlobalData.APP_VERSION);
response = DataHandler.wb_elligibleBundles(account.getUsername(), account.getPassword(), msisdn, cos, context);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(StaticTools.isValidCallback(callback)){
if(response!=null) {
if(!response.getError().equals("0") && response.getErrordesc().length()>2){
if (StaticTools.isValidCallback(callback)) {
callback.get().onErrorBundleList(response.getErrordesc());
}
}
else if(response.getError().equals("0")){
if(response.getEligibleBundles()!=null) {
if(response.getEligibleBundles().size() == 0){
if (StaticTools.isValidCallback(callback)) {
callback.get().onErrorBundleList(ERROR_EMPTY);
}
}
else {
MemoryCacheManager.setBundlePurchaseItems(response.getEligibleBundles());
if (StaticTools.isValidCallback(callback)) {
callback.get().onSuccessBundleList();
}
}
}
else {
if (StaticTools.isValidCallback(callback)) {
callback.get().onGenericErrorBundleList();
}
}
}
}
else{
if (StaticTools.isValidCallback(callback)) {
callback.get().onGenericErrorBundleList();
}
}
}
}
}
public static ArrayList<String> getCategories(Context context){
ArrayList<Pair<String,String>> categories = new ArrayList<>();
for(Bundle_item item:MemoryCacheManager.getBundlePurchaseItems()) {
String[] result = getCategoryName(context, item.getNew_Category().toLowerCase());
categories.add(new Pair<>(result[1],result[0]));
}
ArrayList<String> result = new ArrayList<>();
Collections.sort(categories, new Comparator<Pair<String, String>>() {
@Override
public int compare(Pair<String, String> lhs, Pair<String, String> rhs) {
return Integer.parseInt(lhs.first) - Integer.parseInt(rhs.first);
}
});
for(Pair<String,String> pair:categories){
if(!result.contains(pair.second))
result.add(pair.second);
}
return result;
}
public static String[] getCategoryName(Context context,String cat){
switch (cat){
case BundlePurchaseCategories.UNDER24:
return new String[]{context.getString(R.string.bundles_under24_category),"0"};
case BundlePurchaseCategories.STUDENT24:
return new String[]{context.getString(R.string.bundles_student24_category),"1"};
case BundlePurchaseCategories.STUDENT:
return new String[]{context.getString(R.string.bundles_student_category),"2"};
case PrePayBundlePurchaseCategories.DATA:
return new String[]{context.getString(R.string.bundles_internet_category),"3"};
case PostPayBundlePurchaseCategories.DATA:
return new String[]{context.getString(R.string.bundles_internet_category),"4"};
case BundlePurchaseCategories.VOICE:
return new String[]{context.getString(R.string.bundles_voice_category), "5"};
case BundlePurchaseCategories.SMS:
return new String[]{context.getString(R.string.bundles_sms_category),"6"};
case BundlePurchaseCategories.COMBO:
return new String[]{context.getString(R.string.bundles_combo_category),"7"};
case BundlePurchaseCategories.INTERNATIONAL:
return new String[]{context.getString(R.string.bundles_international_category),"8"};
case BundlePurchaseCategories.DEFAULT:
return new String[]{context.getString(R.string.bundles_internet_category), "9"};
default:
return new String[]{context.getString(R.string.bundles_internet_category),"10"};
}
}
public static String getCategory(Context c, String category, boolean postPay){
String selectedCategory = BundlePurchaseCategories.DEFAULT;
if (category.equalsIgnoreCase(c.getString(R.string.bundles_student_category))){
selectedCategory = BundlePurchaseCategories.STUDENT;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_combo_category))) {
selectedCategory = BundlePurchaseCategories.COMBO;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_internet_category))) {
selectedCategory = postPay? PostPayBundlePurchaseCategories.DATA: PrePayBundlePurchaseCategories.DATA;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_international_category))) {
selectedCategory = BundlePurchaseCategories.INTERNATIONAL;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_sms_category))) {
selectedCategory = BundlePurchaseCategories.SMS;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_voice_category))) {
selectedCategory = BundlePurchaseCategories.VOICE;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_under24_category))) {
selectedCategory = BundlePurchaseCategories.UNDER24;
}
else if(category.equalsIgnoreCase(c.getString(R.string.bundles_student24_category))) {
selectedCategory = BundlePurchaseCategories.STUDENT24;
}
return selectedCategory;
}
public static List<Bundle_item> getBundleItemsOfCategory(String category){
List<Bundle_item> categoryBundles = new ArrayList<>();
for(Bundle_item item:MemoryCacheManager.getBundlePurchaseItems()){
if(item.getNew_Category().equalsIgnoreCase(category) && StaticTools.isNullOrEmpty(item.getActivation_Action())){
categoryBundles.add(item);
}
}
return categoryBundles;
}
public static VFModelBundleItemsPurchase getBundleListModel(String category){
List<Bundle_item> categoryBundles = getBundleItemsOfCategory(category);
VFModelBundleItemsPurchase model = new VFModelBundleItemsPurchase();
model.setBundleItemsList(buildBundleItems(categoryBundles));
return model;
}
private static ArrayList<VFModelBundleItemPurchase> buildBundleItems( List<Bundle_item> categoryBundles){
ArrayList<VFModelBundleItemPurchase> result = new ArrayList<>();
List<Bundle_item> onceoffBundles = new ArrayList<>();
List<Bundle_item> recurringBundles = new ArrayList<>();
for(Bundle_item item:categoryBundles){
if(!item.getBundleType().equals("recurring")){
onceoffBundles.add(item);
}
else{
recurringBundles.add(item);
}
}
for(Bundle_item item:onceoffBundles){
VFModelBundleItemPurchase model = buildBundleItem(item);
if(Boolean.parseBoolean(item.getHas_recurring()) && !StaticTools.isNullOrEmpty(item.getRecurring_code())){
for(int i=0;i<recurringBundles.size();i++){
if(item.getRecurring_code().equals(recurringBundles.get(i).getCode())){
VFModelBundleItemPurchase recModel = buildBundleItem(recurringBundles.get(i));
model.setRecurringBundle(recModel);
recurringBundles.remove(i);
break;
}
}
}
result.add(model);
}
for(Bundle_item item:recurringBundles){
VFModelBundleItemPurchase model = buildBundleItem(item);
result.add(model);
}
return result;
}
private static VFModelBundleItemPurchase buildBundleItem(Bundle_item item){
VFModelBundleItemPurchase model = new VFModelBundleItemPurchase();
model.setCode(item.getCode());
model.setBundleHeader(item.getShortBundleName());
model.setShortDescription(item.getShort_desc());
model.setTeaserText(item.getTeaser());
model.setDateStatus(getDateStatus(item));
//model.setDeactivationMessage("");
model.setActivationMessage(item.getConf_msg_upon_deact().replace("&", "&"));
model.setIsNextBill(item.getIsNextBill()!=null && Boolean.parseBoolean(item.getIsNextBill()));
model.setDeactivationCommand(item.getDeactivation_Command());
String price = item.getPrice();
String[] split = null;
if(price.contains("/"))
split = price.split("/");
price = (split!=null && split.length>0)?split[0]:price;
model.setPrice(price);
model.setLongDecription(item.getLong_desc());
model.setBundleDuration(split!=null && split.length>1? split[1]:"");
if(item.getBundleType().equals("recurring")){
model.setBundleType(VFModelBundleItemPurchase.BundleType.Recurring);
}
else if(item.getBundleType().equals("on-off")){
model.setBundleType(VFModelBundleItemPurchase.BundleType.OnOff);
}
else {
model.setBundleType(VFModelBundleItemPurchase.BundleType.OnceOff);
}
model.setIsActive(item.getIsactive().equals("1"));
if(item.getWillExpire().equals("renew") || item.getWillExpire().equals("expire")){
model.setDate(item.getExpirationDate());
}
if(!StaticTools.isNullOrEmpty(item.getExpirationDate())){
try {
if(item.getExpirationDate().equals("-") || item.getExpirationDate().equalsIgnoreCase("infinity")){
model.setExpireDate(null);
}
else {
model.setExpireDate(StaticTools.tryParseDate(item.getExpirationDate(), "yyyyMMdd", 0));
}
} catch (Exception e) {
model.setExpireDate(null);
StaticTools.Log(e);
}
}
model.setActionStatus(VFModelBundleItemPurchase.ActionStatus.Activate);
if(model.getBundleType()== VFModelBundleItemPurchase.BundleType.Recurring && model.isActive())
{
if(item.getDeactivation().equalsIgnoreCase("yes")) {
model.setActionStatus(VFModelBundleItemPurchase.ActionStatus.Deactivate);
}
else {
model.setActionStatus(VFModelBundleItemPurchase.ActionStatus.Disabled);
}
}
else if(model.getBundleType() == VFModelBundleItemPurchase.BundleType.OnOff && model.isActive())
{
if(item.getDeactivation().equalsIgnoreCase("yes")) {
model.setActionStatus(VFModelBundleItemPurchase.ActionStatus.Deactivate);
}
else {
model.setActionStatus(VFModelBundleItemPurchase.ActionStatus.Disabled);
}
}
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
model.setModDate(sdf.parse(item.getModDate()));
}
catch (Exception e){
StaticTools.Log(e);
model.setModDate(GregorianCalendar.getInstance().getTime());
}
return model;
}
public static int getCategoryIcon(String category){
switch (category){
case PrePayBundlePurchaseCategories.DEFAULT:
return R.drawable.bundle_cat_inter;
case PrePayBundlePurchaseCategories.VOICE:
return R.drawable.bundle_cat_voice;
case PrePayBundlePurchaseCategories.COMBO:
return R.drawable.bundle_cat_combo;
case PrePayBundlePurchaseCategories.INTERNATIONAL:
return R.drawable.bundle_cat_inter;
case PrePayBundlePurchaseCategories.DATA:
return R.drawable.bundle_cat_data;
case PostPayBundlePurchaseCategories.DATA:
return R.drawable.bundle_cat_data;
case PrePayBundlePurchaseCategories.SMS:
return R.drawable.bundle_cat_sms;
case PrePayBundlePurchaseCategories.STUDENT:
return R.drawable.bundle_cat_student;
case BundlePurchaseCategories.UNDER24:
return R.drawable.bundle_cat_under24;
case BundlePurchaseCategories.STUDENT24:
return R.drawable.bundle_cat_student;
default:
return R.drawable.bundle_cat_data;
}
}
public static void bundleAction(Context context, Bundle_item bundleItem, String actionType, WeakReference<BundlePurchaseActionListener> listener){
new BundleActionAsync(context, bundleItem, actionType, listener).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static class BundleActionAsync extends AsyncTask<String, Void, String> {
Action_bundle temptr;
Bundle_item bundleItem;
String actionType;
Context context;
WeakReference<BundlePurchaseActionListener> callback;
public BundleActionAsync(Context context, Bundle_item bundleItem, String actionType, WeakReference<BundlePurchaseActionListener> listener){
this.bundleItem = bundleItem;
this.context = context;
this.actionType = actionType;
this.callback = listener;
}
protected String doInBackground(String... urls) {
try {
temptr = DataHandler.wb_activateBundle(MemoryCacheManager.getSelectedAccount().getUsername(), MemoryCacheManager.getSelectedAccount().getPassword(),
MemoryCacheManager.getSelectedAccount().getSelectedAccountNumber(),
bundleItem.getCode(), actionType,
bundleItem.getActivation(),
bundleItem.getProvisioning(), context);
} catch (NullPointerException e) {
StaticTools.Log(e.getMessage());
temptr = null;
}
return "";
}
protected void onPostExecute(String result) {
if (temptr == null) {
if (StaticTools.isValidCallback(callback)) {
callback.get().onGenericErrorBundleAction();
}
} else {
if (temptr.getError().equals("0")) {
if (StaticTools.isValidCallback(callback)) {
callback.get().onSuccessBundleAction(actionType, temptr.getErrordesc());
}
} else {
if (StaticTools.isValidCallback(callback)) {
callback.get().onErrorBundleAction(temptr.getErrordesc().replace("&", "&"));
}
}
}
}
}
public static SpannableString getBundleHeader(Context context, String name, String price){
String bundleStr = context.getString(R.string.bundle_item_name);
if(price.toLowerCase().contains(context.getString(R.string.free))){
bundleStr = context.getString(R.string.bundle_item_name).replace(context.getString(R.string.with),"");
}
return new SpannableString(Html.fromHtml(bundleStr.replace("__BNAME",name).replace("__BPRICE", price)));
}
public static SpannableString getBundleDetailsHeader(Context context, String name, String price, String duration, String msisdn){
String bundleStr = context.getString(R.string.bundle_item_name_noline);
if(price.toLowerCase().contains(context.getString(R.string.free))){
bundleStr = context.getString(R.string.bundle_item_name_noline).replace(context.getString(R.string.with),"");
}
bundleStr = bundleStr.replace("__BNAME", name).replace("__BPRICE",
price + ((duration != null && duration.length() > 1) ? "/" + duration : ""))
.replace("__MS", msisdn);
return new SpannableString(Html.fromHtml(bundleStr));
}
public static VFModelBundleItemPurchase.DateStatus getDateStatus(Bundle_item item) {
if (item.getIsactive().equals("1")) {
if (item.getActivation().toLowerCase().equals("recurring")) {
if (item.getWillExpire().toLowerCase().equals("renew")) {
return VFModelBundleItemPurchase.DateStatus.RenewDate;
} else if (item.getWillExpire().toLowerCase().equals("expire")) {
return VFModelBundleItemPurchase.DateStatus.ExpireDate;
}
} else {
if (item.getWillExpire().toLowerCase().equals("expire")) {
return VFModelBundleItemPurchase.DateStatus.ExpireDate;
}
}
}
return VFModelBundleItemPurchase.DateStatus.None;
}
}
|
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import java.io.IOException;
public class TestClass {
//unit test - testing http connection
@Test
public void testCon() throws IOException, java.text.ParseException, ParseException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
System.out.println(o);
}
@Test
public void testCuisine() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray numEntries = app.getByCuisineAndNeighbourhood(o, "Asian","Manhattan");
assertEquals(2, numEntries.size());
}
@Test
public void testReview() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray numEntries = app.getByReviewRating(o, "Queens", 2);
assertEquals(6, numEntries.size());
}
@Test
public void testOpeningDay() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray numEntries = app.getByOpeningHours(o, "Tuesday");
//assertEquals(9, numEntries);
}
@Test
public void testDohmh() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray numEntries = (app.getByDohmh(o, "Brooklyn"));
assertEquals(3, numEntries.size());
}
@Test
public void testReviewBVA() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
app.getByReviewRating(o, "Queens", 1);
}
@Test
public void testWrongArea() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray j = app.getByCuisineAndNeighbourhood(o, "Asian", "Brooklyn");
assertEquals(0,j.size());
}
@Test
public void testNearestHotel() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
app.getNearHotel(o,"Manhattan");
}
@Test
public void integrationTestCuisine() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray american = (JSONArray) app.getByCuisineAndNeighbourhood(o,"American","Manhattan");
JSONArray americanTues = (JSONArray) app.getByOpeningHours(american,"Tuesday"); //will return two JSON Objects
assertEquals(2,americanTues.size());
}
@Test
public void integrationTestRatingCuisine() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray pizza = app.getByCuisineAndNeighbourhood(o,"Pizza","Brooklyn");
JSONArray goodPizza = app.getByReviewRating(pizza,"Brooklyn",4);
assertEquals(6, goodPizza.size()); //number of reviews 4+
}
//edge test for min and max for rating scores
@Test
public void testEdgeRating() throws java.text.ParseException, ParseException, IOException {
App app = new App();
JSONArray o = (JSONArray) app.getData();
JSONArray numEntriesZero = app.getByReviewRating(o, "Brooklyn", 0);
JSONArray numEntriesFive = app.getByReviewRating(o, "Brooklyn", 5);
assertNotEquals(numEntriesFive.size(), numEntriesZero.size());
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.console;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
/**
* Holds static references to the GridBagConstraints and the GridBagLayout.
* These should always be used when adding components.
*
* @see GridBagConstraints
* @see GridBagLayout
*
* @author Robert Jan van der Waals
*/
public final class Layout {
private static final GridBagConstraints gbc = new GridBagConstraints();
private static final GridBagLayout gbl = new GridBagLayout();
public static GridBagLayout getGBL() {
return gbl;
}
/**
* Sets the Gridbag Constraints on the saved instance
*/
public static GridBagConstraints getGBC ( int x,
int y,
int width,
int height,
double xWeight,
double yWeigth,
int gbcAnchor,
int gbcStretch,
Insets insets,
int xPad,
int yPad) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = xWeight;
gbc.weighty = yWeigth;
gbc.anchor = gbcAnchor;
gbc.fill = gbcStretch;
gbc.insets = insets;
gbc.ipadx = xPad;
gbc.ipady = yPad;
return gbc;
}
}
|
package dmitriy.telepnev.testFixtures;
import dmitriy.telepnev.AbstractFixture;
import dmitriy.telepnev.testFixtureDto.TestFixture2DTO;
public class TestFixture2 extends AbstractFixture<TestFixture2DTO> {
public TestFixture2() {
super();
filePath = "fixtures/test/fixture1.yml";
tableName = "table2";
}
}
|
/**
* @author Denise van Baalen (s4708237)
* @author Anna Gansen (s4753755)
*/
package nl.ru.ai.exercise6;
import java.util.Stack;
public class Convert
{
public static void main(String[] args)
{
/*
* Test for tail recursion
*/
xsy(3);
System.out.println();
/*
* Test for left recursion
*/
reverse("ykraps");
System.out.println();
/*
* Test for middle recursion
*/
downUp(5);
System.out.println();
}
/** Prints a number of 'x's equal to the input integer, then prints a y.
* @param i
*/
private static void xsyOriginal(int i)
{
assert i>0: "Integer must be greater than zero.";
if(i==0)
System.out.print("y");
else
{
System.out.print("x");
xsyOriginal(i-1);
}
}
/** Prints a number of 'x's equal to the input integer, then prints a y.
* @param i
*/
private static void xsy(int i)
{
assert i>0: "Integer must be greater than zero.";
while(i!=0)
{
System.out.print("x");
i=i-1;
}
System.out.print("y");
}
/** Prints the reverse of the input string.
* @param s
*/
private static void reverseOriginal(String s)
{
assert s!=null:"String must be declared.";
if(s.length()==0)
return;
else
{
reverseOriginal(s.substring(1));
System.out.print(s.charAt(0));
}
}
/** Prints the reverse of the input string.
* @param s
*/
private static void reverse(String s)
{
assert s!=null:"String must be declared.";
Stack<String> stack = new Stack<String>();
while(s.length()!=0)
{
stack.push(s);
s=s.substring(1);
System.out.println(s);
}
while(!stack.isEmpty())
{
s=stack.pop();
System.out.print(s.charAt(0));
}
}
/** Prints an integer and all positive integers before it (no zero), prints an exclamation mark, and then prints all integers
* from 1 up to and including the input integer (i).
* @param i
*/
private static void downUpOriginal(int i)
{
assert i>0: "Integer must be greater than zero.";
if(i==0)
System.out.print("!");
else
{
System.out.print(i);
downUpOriginal(i-1);
System.out.print(i);
}
}
/** Prints an integer and all positive integers before it (no zero), prints an exclamation mark, and then prints all integers
* from 1 up to and including the input integer (i).
* @param i
*/
private static void downUp(int i)
{
assert i>0: "Integer must be greater than zero.";
Stack<Integer> stack=new Stack<Integer>();
while(i!=0)
{
System.out.print(i);
stack.push(i);
i=i-1;
}
System.out.print("!");
while(!stack.isEmpty())
{
i=stack.pop();
System.out.print(i);
}
}
}
|
package com.SearchHouse.pojo;
import java.util.Set;
public class BedRoom {
private Integer bedroomIdFk;//卧室主键
private String bedroomName;//都有、主卧、次卧、隔断
public BedRoom(){
}
public Integer getBedroomIdFk() {
return bedroomIdFk;
}
public void setBedroomIdFk(Integer bedroomIdFk) {
this.bedroomIdFk = bedroomIdFk;
}
public String getBedroomName() {
return bedroomName;
}
public void setBedroomName(String bedroomName) {
this.bedroomName = bedroomName;
}
@Override
public String toString() {
return "BedRoom [bedroomIdFk=" + bedroomIdFk + ", bedroomName=" + bedroomName + "]";
}
public BedRoom(Integer bedroomIdFk, String bedroomName) {
super();
this.bedroomIdFk = bedroomIdFk;
this.bedroomName = bedroomName;
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.core.web.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.el.VariableResolver;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.objects.Picture;
import net.datacrow.core.objects.ValidationException;
import net.datacrow.core.resources.DcResources;
import net.datacrow.core.web.model.DcWebImage;
import net.datacrow.core.web.model.DcWebObject;
import net.datacrow.core.web.model.DcWebObjects;
import net.datacrow.util.DcImageIcon;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.apache.myfaces.custom.navmenu.NavigationMenuItem;
public class ItemImage extends DcBean {
private UploadedFile uploadedFile;
@Override
public String back() {
return "details";
}
@Override
public String current() {
return "itemimage";
}
@Override
public List<NavigationMenuItem> getMenuItems() {
List<NavigationMenuItem> menu = new ArrayList<NavigationMenuItem>();
menu.add(getMenuItem(DcResources.getText("lblBack"), "#{itemImage.back}", null));
addLogoffMenuItem(menu);
return menu;
}
@Override
public String getActionListener() {
return "#{itemImage.actionListener}";
}
public String open() {
if (!isLoggedIn())
return redirect();
FacesContext fc = FacesContext.getCurrentInstance();
VariableResolver vr = fc.getApplication().getVariableResolver();
DcWebObject wo = (DcWebObject) vr.resolveVariable(fc, "webObject");
Map map = fc.getExternalContext().getRequestParameterMap();
int fieldIdx = Integer.valueOf((String) map.get("fieldIdx"));
Picture picture = (Picture) wo.getDcObject().getValue(fieldIdx);
DcWebImage wi = (DcWebImage) vr.resolveVariable(fc, "image");
wi.setFieldIdx(fieldIdx);
wi.setModuleIdx(wo.getModule());
if (picture != null) {
wi.setPicture(picture);
} else {
wi.setPicture(null);
}
return "itemimage";
}
public boolean isAllowUpload() {
FacesContext fc = FacesContext.getCurrentInstance();
VariableResolver vr = fc.getApplication().getVariableResolver();
DcWebImage wi = (DcWebImage) vr.resolveVariable(fc, "image");
DcWebObject wo = (DcWebObject) vr.resolveVariable(fc, "webObject");
return getUser().isEditingAllowed(DcModules.get(wo.getModule()).getField(wi.getFieldIdx()));
}
public UploadedFile getUpFile() {
return uploadedFile;
}
public void setUpFile(UploadedFile upFile) {
uploadedFile = upFile;
}
@SuppressWarnings("unchecked")
public String upload() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
VariableResolver vr = fc.getApplication().getVariableResolver();
DcWebImage wi = (DcWebImage) vr.resolveVariable(fc, "image");
byte[] b = uploadedFile.getBytes();
DcWebObject wo = (DcWebObject) vr.resolveVariable(fc, "webObject");
DcObject dco = wo.getDcObject();
dco.setValue(wi.getFieldIdx(), new DcImageIcon(b));
try {
dco.saveUpdate(false);
wi.setPicture((Picture) dco.getValue(wi.getFieldIdx()));
wo.load();
DcWebObjects objects = (DcWebObjects) vr.resolveVariable(fc, "webObjects");
objects.update(wo);
} catch (ValidationException ve) {
ve.printStackTrace();
}
fc.getExternalContext().getApplicationMap().put("fileupload_bytes", uploadedFile.getBytes());
fc.getExternalContext().getApplicationMap().put("fileupload_type", uploadedFile.getContentType());
fc.getExternalContext().getApplicationMap().put("fileupload_name", uploadedFile.getName());
return current();
}
public boolean isUploaded() {
FacesContext facesContext = FacesContext.getCurrentInstance();
return facesContext.getExternalContext().getApplicationMap().get("fileupload_bytes")!= null;
}
}
|
package com.epam.university.spring.dao;
import com.epam.university.spring.domain.UserAccount;
public interface UserAccountDao {
UserAccount create(UserAccount account);
void update(UserAccount account);
UserAccount getAccountByUserId(Long userId);
}
|
package AbstractFactory.MobileApplication;
import AbstractFactory.IDeveloper;
import AbstractFactory.IProjectManager;
import AbstractFactory.IProjectTeamFactory;
import AbstractFactory.ITester;
public class MobileTeamFactory implements IProjectTeamFactory {
@Override
public IDeveloper getDeveloper() {
return new KotlinDeveloper();
}
@Override
public ITester getTester() {
return new QATester();
}
@Override
public IProjectManager getProjectManager() {
return new MobileAppPM();
}
}
|
package com.ingoskr.eminen.enelmoment.dialogs;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ingoskr.eminen.enelmoment.R;
import com.ingoskr.eminen.enelmoment.ui.activitys.Login;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.zip.Inflater;
/**
* Fragmento con un diálogo personalizado
*/
public class RegistroDialog extends DialogFragment {
private static final String TAG = RegistroDialog.class.getSimpleName();
EditText use, corr, con, repCon;
Button Register;
boolean mostrar=false;
RequestQueue requestQueue;
private static final String URL = "http://108.59.1.32/~oscarito/enelmomento/Insertar.php";
StringRequest request;
AlertDialog.Builder builder;
LinearLayout custoToast;
ImageView imagenToast;
TextView mensajeToast;
public RegistroDialog() {
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createRegDialogo();
}
/**
* Crea un diálogo con personalizado para comportarse
* como formulario de login
*
* @return Diálogo
*/
public AlertDialog createRegDialogo() {
builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.registrarse, null);
builder.setView(v);
requestQueue = Volley.newRequestQueue(getContext().getApplicationContext());
use = (EditText) v.findViewById(R.id.nomUs);
corr = (EditText) v.findViewById(R.id.correoUs);
con = (EditText) v.findViewById(R.id.passUs);
repCon = (EditText) v.findViewById(R.id.passUsRep);
requestQueue = Volley.newRequestQueue(getContext().getApplicationContext());
Register = (Button) v.findViewById(R.id.btnRegistrarse);
Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (use.getText().toString().isEmpty() && corr.getText().toString().isEmpty() && con.getText().toString().isEmpty() && repCon.getText().toString().isEmpty()) {
Snackbar.make(view, "Todos los campos son requeridos", Snackbar.LENGTH_SHORT).setAction("Listo", null).show();
} else if (use.getText().toString().isEmpty() || corr.getText().toString().isEmpty() || con.getText().toString().isEmpty() || repCon.getText().toString().isEmpty()) {
Snackbar.make(view, "Todos los campos son requeridos", Snackbar.LENGTH_SHORT).setAction("Listo", null).show();
} else {
if (validarNombre(use.getText().toString()) == false) {
use.setError("Nombre invalido");
use.requestFocus();
}
if (esCorreo(corr.getText().toString()) && esPassValida(con.getText().toString())) {
if (con.getText().toString().equals(repCon.getText().toString()) == false) {
Snackbar.make(view, "Las contraseñas no coinciden", Snackbar.LENGTH_LONG).setAction("Listo", null).show();
repCon.requestFocus();
repCon.setError("Las contraseñas no coinciden");
} else {
registrarse();
}
} else if (esCorreo(corr.getText().toString()) == true && esPassValida(con.getText().toString()) == false) {
con.setError("La contraseña debe ser mayor a 4 caracteres");
con.requestFocus();
} else if (esCorreo(corr.getText().toString()) == false && esPassValida(con.getText().toString()) == true) {
corr.setError("Debes agregar un correo valido (@)");
corr.requestFocus();
}
if (esPassValida(con.getText().toString())==false) {
con.setError("La contraseña debe ser mayor a 4 caracteres");
repCon.setError("Nombre invalido");
con.requestFocus();
}
}
}
});
return builder.create();
}
private void registrarse() {
final Toast toast = new Toast(getContext());
final View toast_layout = getActivity().getLayoutInflater().inflate(R.layout.toast_informacion, (ViewGroup) getActivity().findViewById(R.id.toastCustom));
custoToast = (LinearLayout) toast_layout.findViewById(R.id.toastCustom);
imagenToast=(ImageView) toast_layout.findViewById(R.id.imagenToast);
mensajeToast=(TextView) toast_layout.findViewById(R.id.mensajeToast);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
imagenToast.setImageDrawable(getResources().getDrawable(R.drawable.completo));
custoToast.setBackgroundColor(getResources().getColor(R.color.toast_correcto));
mensajeToast.setText("Tus datos han sido guardados correctamente");
toast.setGravity(Gravity.CENTER,0,-150);
toast.setView(toast_layout);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
createRegDialogo().dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
imagenToast.setImageDrawable(getResources().getDrawable(R.drawable.atencion));
custoToast.setBackgroundColor(getResources().getColor(R.color.toast_alerta));
mensajeToast.setText("A ocurrido un error inesperado por favor intentelo mas tarde");
toast.setGravity(Gravity.CENTER,0,-150);
toast.setView(toast_layout);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
createRegDialogo().dismiss();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("usuario", use.getText().toString());
hashMap.put("contra", con.getText().toString());
hashMap.put("email", corr.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
private boolean esCorreo(String correo) {
return correo.contains("@");
}
private boolean esPassValida(String s) {
return s.length() > 4;
}
public void login(View view) {
startActivity(new Intent(getContext().getApplicationContext(), Login.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
private boolean validarNombre(String nombre) {
Pattern patron = Pattern.compile("^[a-zA-Z ]+$");
return patron.matcher(nombre).matches() || nombre.length() > 30;
}
public boolean accionMostrar() {
return mostrar;
}
}
|
package mb.tianxundai.com.toptoken.mall.shop.balance;
import mb.tianxundai.com.toptoken.bean.BalanceBean;
import mb.tianxundai.com.toptoken.mall.base.IBaseView;
public interface IBalanceView extends IBaseView {
void getBalanceSuccess(BalanceBean.Balance balance);
void failure(String message);
}
|
package com.github.iam20.coap;
import com.github.iam20.coap.core.CoapServerApplication;
import com.github.iam20.coap.core.CoapServerService;
public class DimmingControlApplication {
public static void main(String[] args) {
CoapServerService.makeManagerThread().start();
CoapServerApplication.run();
}
}
|
package tcss450.uw.edu.huskylist;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import tcss450.uw.edu.huskylist.model.ItemContent;
/**
* Created by vsmirnov on 6/3/16.
*/
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
/** This variable is used to hold the list of BookContent. */
private final List<ItemContent> mValues;
/** This variable is used to hold the fragment interaction listener */
private final ItemListFragment.OnItemListFragmentInteractionListener mListener;
/**
* This is the BookRecyclerViewAdapter constructor.
*
* @param items is the given list of BookContent.
* @param listener is the given fragment interaction listener.
*/
public MyItemRecyclerViewAdapter(List<ItemContent> items, ItemListFragment.OnItemListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
/**
* This method is used to create the view holder.
*
* @param parent is the given view group parent.
* @param viewType is the view type.
* @return is the inflated view.
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
/**
* This method binds the view holder.
*
* @param holder is the given view holder.
* @param position is the given position.
*/
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getItemTitle());
holder.mContentView.setText(mValues.get(position).getItemPrice());
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.OnItemListFragmentInteractionListener(holder.mItem);
}
}
});
}
/**
* This method returns the item count.
*
* @return is the item count.
*/
@Override
public int getItemCount() {
return mValues.size();
}
/**
* The ViewHolder class is used to represent a book.
*
* @author Shelema Bekele
* @author Vladimir Smirnov
* @version 1.0
*/
public class ViewHolder extends RecyclerView.ViewHolder {
/** This variable holds the view. */
public final View mView;
/** This variable holds TextView that holds the ID. */
public final TextView mIdView;
/** This variable holds TextView that holds the content. */
public final TextView mContentView;
/** This variable holds the item. */
public ItemContent mItem;
/**
* This is the ViewHolder constructor.
*
* @param view is the given view.
*/
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
/**
* This method is used to represent the book as a String.
*
* @return is the String.
*/
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
|
package com.elo7.umatic;
public class Track {
private String name;
private TrackRequest request;
private TrackResponse response;
public TrackRequest getRequest() {
return request;
}
public void setRequest(final TrackRequest request) {
this.request = request;
}
public TrackResponse getResponse() {
return response;
}
public void setResponse(final TrackResponse response) {
this.response = response;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package ru.steagle.service;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.KeyStore;
import ru.steagle.protocol.HTTPClientFactory;
import ru.steagle.utils.MySSLSocketFactory;
import ru.steagle.utils.Utils;
public class ServiceTask {
private String regServer;
public ServiceTask(String regServer) {
this.regServer = regServer;
}
protected String execute(String postBody) {
String responseString = null;
try {
HttpPost httpPost = new HttpPost(regServer);
StringEntity stringEntity = new StringEntity(postBody, HTTP.UTF_8);
stringEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type","application/xml; charset=utf-8");
httpPost.setEntity(stringEntity);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 443));
ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(httpPost.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(ccm, httpPost.getParams());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
} catch (Throwable e) {
Utils.writeLogMessage("Exception: " + e.getMessage() + "\n", false);
}
if (responseString == null)
responseString = "";
return responseString;
}
}
|
package kr.co.shop.batch.sample.job;
import java.util.List;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import kr.co.shop.batch.sample.model.master.SampleBatchData;
import kr.co.shop.batch.sample.vo.xml.generator.ControllerPkg;
import kr.co.shop.batch.sample.vo.xml.generator.DaoPkg;
import kr.co.shop.batch.sample.vo.xml.generator.GeneratorConfiguration;
import kr.co.shop.batch.sample.vo.xml.generator.GlobalPkg;
import kr.co.shop.batch.sample.vo.xml.generator.ServicePkg;
import kr.co.shop.common.util.UtilsDate;
import kr.co.shop.common.util.UtilsText;
import kr.co.shop.constant.MappersSample;
import kr.co.shop.support.BatchReaderAndWriter;
import lombok.extern.slf4j.Slf4j;
/***
* XML파일을 읽어와서 DB에 처리하는 방법이다.
*
* 1. 디스크 드라이브에 있는 XML파일을 읽어온다.
* 1.1 Spring batch에서 xml parsing은 JAXB2를 사용한다.
* 1.2 매핑할 VO 클래스를 만든 후에 JAXB2어노테이션을 이용하여 구조를 잡는다.
* 1.2.1 어노테이션은 나열되는 항목들을 이용하여 설정 한다.@XmlRootElement,@XmlAccessorType, @XmlElementWrapper,@XmlElementRefs,@XmlElements
* 1.3 XML 파일 경로 및 VO에 매핑할 클래스명을 newXmlItemReader에 설정하여 호출 한다.
* 2. XML에서 읽어온 데이터를 ItemProcessor를 통하여 가공 한다.
* 2.1 DB에서 읽어온 데이터 아이템을 process(T item) 메소드에 한건 씩 넘겨준다. 만약 최상위 root element기준이 아닌 반복되는 하위 element를 지정하면 여러번 호출 된다.
* 2.2 특정 컬럼 값이 조건에 일치 할 경우 객체 반환, 일치하지 않을 경우 null로 리턴하여 skip한다.
* 2.3 리턴에 호출 된 객체는 writer에 한번에 넘겨 준다.
* 3. 가공된 데이터를 DB에 저장한다.
* 3.1 newMyBatisBatchItemWriter 에 호출 할 mybatis mapperId를 설정한다.
*
* @author zerocooldog 장진철
*
*/
@Slf4j
@Configuration
public class SampleXMLToDBConfiguration extends BatchReaderAndWriter {
public static final String JOB_NAME = "sampleXMLToDBJob";
public static final String STEP_NAME_SAMPLE_BATCH_DATA = UtilsText.concat(JOB_NAME,"-","sampleXMLToDBJobStep");
public static final int CHUNK_SIZE = 1000;
@Bean
public Job sampleXMLToDBJob() {
return getJobBuilderFactory(JOB_NAME)
.start(sampleXMLToDBJobStep())
.build();
}
@Bean
@JobScope
public Step sampleXMLToDBJobStep(){
ItemProcessor<GeneratorConfiguration, SampleBatchData> processor = new ItemProcessor<GeneratorConfiguration,SampleBatchData> () {
@Override
public SampleBatchData process(GeneratorConfiguration item) throws Exception {
log.debug("properties length : {}",item.getProperties());
log.debug("properties contorllerPkg : {}",item.getGlobal());
SampleBatchData sampleBatchData = new SampleBatchData();
sampleBatchData.setSeq(Integer.parseInt(UtilsDate.today("hhmmsssss")));
List<GlobalPkg> global = item.getGlobal();
for (GlobalPkg globalPkg : global) {
log.debug("isControllerPkg :{} ", ( globalPkg instanceof ControllerPkg ));
log.debug("isServicePkg :{} ", ( globalPkg instanceof ServicePkg ));
log.debug("isDaoPkg :{} ", ( globalPkg instanceof DaoPkg ));
if( globalPkg instanceof ControllerPkg ) {
sampleBatchData.setData1(globalPkg.getTarget());
}else if( globalPkg instanceof ServicePkg ) {
sampleBatchData.setData2(globalPkg.getTarget());
}else if( globalPkg instanceof DaoPkg ) {
sampleBatchData.setData3(globalPkg.getTarget());
}
}
// log.debug("properties servicePkg : {}",item.getServicepkg());
// log.debug("properties daoPkg : {}",item.getDaopkg());
// List<Property> properties = item.getProperties();
// for (Property property : properties) {
// log.debug("porperty key attribute : {}",item.getKey());
// log.debug("porperty value : {}", item.getValue());
// }
return sampleBatchData;
}
};
String writerMapper = MappersSample.SAMPLE_BATCH_DATA_DAO_INSERT;
String xmlPath = "D:\\project\\abc\\workspace\\common\\generator\\generator.xml";
return getStepBuilderFactory(STEP_NAME_SAMPLE_BATCH_DATA)
.<GeneratorConfiguration,SampleBatchData>chunk(CHUNK_SIZE)
.reader(newXmlItemReader(xmlPath,"configuration",GeneratorConfiguration.class))
.processor(processor)
.writer(newMyBatisBatchItemWriter(writerMapper))
.build();
}
} |
package com.grandsea.ticketvendingapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.grandsea.ticketvendingapplication.R;
import com.grandsea.ticketvendingapplication.adapter.ShiftAdapter;
import com.grandsea.ticketvendingapplication.base.BaseActivity;
import com.grandsea.ticketvendingapplication.constant.IntentKey;
import com.grandsea.ticketvendingapplication.constant.UrlConstant;
import com.grandsea.ticketvendingapplication.model.bean.OrderInfo;
import com.grandsea.ticketvendingapplication.model.bean.PostShiftParams;
import com.grandsea.ticketvendingapplication.model.bean.Shift;
import com.grandsea.ticketvendingapplication.model.common.GsonObject;
import com.grandsea.ticketvendingapplication.util.BasicUtil;
import com.grandsea.ticketvendingapplication.util.DateUtil;
import com.grandsea.ticketvendingapplication.util.DialogManager;
import com.grandsea.ticketvendingapplication.view.CustomButton;
import com.grandsea.ticketvendingapplication.view.DateView;
import com.grandsea.ticketvendingapplication.view.ImageTextView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
import okhttp3.MediaType;
import static com.grandsea.ticketvendingapplication.adapter.GsonAdapter.gson;
/**
* 班次
*/
public class ShiftActivity extends BaseActivity implements View.OnClickListener {
private static final int DEFAULT_PAGE_SIZE = 15;
private static final int PAGE_MIN = 1;
private PostShiftParams mPostShiftParams;
private RecyclerView recyclerView;
private int pageid =PAGE_MIN;
private List<Shift> shiftDataList = new ArrayList<>();
private CustomButton btBack,btLast,btNext;
private int currentPage =1;
private ImageTextView itvStationStart,itvStationEnd;
private DateView dateView;
private String ticketDate;
private TextView tvNoShift;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shift);
itvStationStart =(ImageTextView) findViewById(R.id.ash_stationStart);
itvStationEnd =(ImageTextView) findViewById(R.id.ash_stationEnd);
dateView =(DateView) findViewById(R.id.ash_dateView);
dateView.setDateChangeListener(new DateView.DateChangeListener() {
@Override
public void add(int day) {
long timeSpan = day*DateView.DAY_SECEND;
currentPage=PAGE_MIN;//重置为第一页
getShiftList(currentPage, timeSpan);
}
@Override
public void minus(int day) {
long timeSpan = day*DateView.DAY_SECEND;
currentPage=PAGE_MIN;//重置为第一页
getShiftList(currentPage, timeSpan);
}
});
//处理上下按钮功能
btBack = (CustomButton) findViewById(R.id.ash_btBack);
btNext =(CustomButton) findViewById(R.id.ash_btNext);
btLast =(CustomButton) findViewById(R.id.ash_btLast);
btBack.setOnClickListener(this);
btNext.setOnClickListener(this);
btLast.setOnClickListener(this);
recyclerView =(RecyclerView) findViewById(R.id.ash_RecyclerView);
tvNoShift =(TextView) findViewById(R.id.ash_tipsNoShift);
tvNoShift.setVisibility(View.GONE);
tvSpannableImg(tvNoShift,"很抱歉,你查询的站点今天没有合适的班次\n你可以点击日期右边的@查询明天的班次,\n或者点击右下角的“返回按钮选择其他站点”","@");
recyclerView.setLayoutManager(new LinearLayoutManager(this));
initData();
}
private void initData() {
//处理前面传递过来的对象 -->
Intent intent = getIntent();
mPostShiftParams = (PostShiftParams)intent.getSerializableExtra(IntentKey.SHIFT_OBJ);
String getOnStation = mPostShiftParams.getGetOnStation();
String takeOffStation = mPostShiftParams.getTakeOffStation();
itvStationStart.getTvLeft().setText(getOnStation+"");
itvStationEnd.getTvLeft().setText(takeOffStation+"");
getShiftList(currentPage,0);
}
@Override
public void onClick(View v) {
if (v == btBack) {
finish();
} else if (v == btLast) {
// toast("btLast");
if (null == recyclerView)
return;
if (currentPage > PAGE_MIN) {
currentPage--;
getShiftList(currentPage,dateView.getTimeSpan());
} else {
DialogManager.dialogPageTurn(ShiftActivity.this, "已经是第一页",null);
}
} else if (v == btNext) {
if (null == recyclerView)
return;
if(shiftDataList.size() < DEFAULT_PAGE_SIZE){
DialogManager.dialogPageTurn(ShiftActivity.this, "已经是最后一页",null);
}else{
currentPage ++;
getShiftList(currentPage,dateView.getTimeSpan());
}
}
}
private void getShiftList(int pageid,long timeSpan) {
Date date = new Date(System.currentTimeMillis() + timeSpan);
ticketDate = DateUtil.formatYYYYMMDD(date);
mPostShiftParams.setDepartDate(ticketDate);
Map<String,Object> paramMap = new HashMap();
paramMap.put("type",1);
paramMap.put("pageid",pageid);
paramMap.put("params", mPostShiftParams);
paramMap.put("orderType",1); //1:按时间升序排序,2:按时间降序排序
String requestContent =new Gson().toJson(BasicUtil.buildPostData(this,paramMap)) ;
logI(requestContent);
OkHttpUtils
.postString()
.url(UrlConstant.SHIFT_LIST)
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.content(requestContent)
.build()
.execute(new StringCallback(){
@Override
public void onError(Call call, Exception e, int i) {
toast("网络异常,请重新刷新");
e.printStackTrace();
}
@Override
public void onResponse(String s, int i) {
GsonObject dataGson = new GsonObject(gson.fromJson(s, JsonObject.class)); //对数据转换成json后进行对象封装
final List<Shift> shiftList = dataGson.getAsList(gson,"shifts",Shift.class);
shiftDataList = shiftList;
if(shiftList ==null || shiftList.size()==0){
//toast("没有班次了");
tvNoShift.setVisibility(View.VISIBLE);
//return;
}else {
tvNoShift.setVisibility(View.GONE);
}
ShiftAdapter adapter = new ShiftAdapter(shiftList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ShiftAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
if (shiftList.get(position).getTicketNum()<1) {
toast("请选择有余票的车次");
return;
}
Intent intent = new Intent(ShiftActivity.this,SelectTicketsActivity.class);//PassengerActivity
Shift shift = shiftList.get(position);
String shiftStr = gson.toJson(shift);
OrderInfo orderInfo = gson.fromJson(shiftStr,OrderInfo.class);
orderInfo.setShiftId(shift.getId());
orderInfo.setTicketDate(ticketDate); // 选中班次的日期 --DateUtil.formatYYYYMMDD(new Date())
int departCityId = mPostShiftParams.getDepartCityId();
String departCity = mPostShiftParams.getDepartCity();
int destCityId = mPostShiftParams.getDestCityId();
String destCity = mPostShiftParams.getDestCity();
//TODO 要修改。。以下 4 项
orderInfo.setDepartCityId(departCityId);//出发城市id --DefaultConfig.DEPART_CITY_ID
orderInfo.setDepartCity(departCity);//出发城市 --"珠海"
orderInfo.setDestCityId(destCityId);//终点城市id
orderInfo.setDestCity(destCity);//终点城市
intent.putExtra(IntentKey.EXTRA_SHIFT_TO_PASSENGER_OBJ,orderInfo);
intent.putExtra(IntentKey.TICKET_DATE,dateView.getTvDate().getText().toString().trim());
startActivity(intent);
}
});
}
});
}
}
|
package com.cs.rest.status;
import javax.xml.bind.annotation.XmlElement;
/**
* @author Omid Alaepour.
*/
public class ValidationResponseMessage extends ResponseMessage {
private static final long serialVersionUID = 1L;
@XmlElement
private final boolean valid;
public ValidationResponseMessage(final boolean valid) {
super(valid ? StatusCode.DOES_NOT_EXIST : StatusCode.EXISTS, "");
this.valid = valid;
}
}
|
package com.ctt.constant;
/**
*
*/
public class Constants {
public static final String MIXKEY = "hhf";
/** 暂留,不使用 **/
public static final String SUCCESS_CODE = "200";
public static final String SUCCESS_MSG = "请求成功";
/**
* session中存放用户信息的key值
*/
public static final String SESSION_USER_INFO = "userInfo";
public static final String SESSION_USER_PERMISSION = "userPermission";
}
|
package jp.ac.kyushu_u.csce.modeltool.vdmslEditor;
import org.eclipse.osgi.util.NLS;
public class Messages extends NLS {
private static final String BUNDLE_NAME = "jp.ac.kyushu_u.csce.modeltool.vdmslEditor.messages"; //$NON-NLS-1$
public static String AbstractVdmslSearchHandler_0;
public static String AbstractVdmslSearchHandler_1;
public static String AbstractVdmslSearchHandler_2;
public static String VdmslDictionarySearchHandler_0;
public static String VdmslDictionarySearchHandler_1;
public static String VdmslDictionarySearchHandler_2;
public static String VdmslModel_0;
public static String VdmslModel_1;
public static String VdmslModel_2;
public static String VdmslModel_3;
public static String VdmslModel_4;
public static String VdmslModel_5;
public static String VdmslSearchHandler_0;
public static String VdmslSearchHandler_1;
public static String VdmslSearchHandler_2;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
|
public class github {
public static void main(String[]args) {
System.out.println("monster");
}
}
|
package com.target.interview.poc.commentmoderator.mapper;
import com.target.interview.poc.commentmoderator.constants.DataBaseConstats;
import com.target.interview.poc.commentmoderator.data.CommentValidationResponse;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
@Component
public class BlackListMapper implements RowMapper<NoiseDaoTO> {
@Nullable
@Override
public NoiseDaoTO mapRow(ResultSet resultSet, int i) throws SQLException {
NoiseDaoTO commentValidationResponse = new NoiseDaoTO();
commentValidationResponse.setName(StringUtils.trimAllWhitespace(resultSet.getString(DataBaseConstats.NOISE_NAME)));
commentValidationResponse.setType(StringUtils.trimAllWhitespace(resultSet.getString(DataBaseConstats.NOISE_TYPE)));
return commentValidationResponse;
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.StudentCourseaccessrole;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class StudentCourseaccessroleRecord extends UpdatableRecordImpl<StudentCourseaccessroleRecord> implements Record5<Integer, String, String, String, Integer> {
private static final long serialVersionUID = 1122861301;
/**
* Setter for <code>bitnami_edx.student_courseaccessrole.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.student_courseaccessrole.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.student_courseaccessrole.org</code>.
*/
public void setOrg(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.student_courseaccessrole.org</code>.
*/
public String getOrg() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.student_courseaccessrole.course_id</code>.
*/
public void setCourseId(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.student_courseaccessrole.course_id</code>.
*/
public String getCourseId() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.student_courseaccessrole.role</code>.
*/
public void setRole(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.student_courseaccessrole.role</code>.
*/
public String getRole() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.student_courseaccessrole.user_id</code>.
*/
public void setUserId(Integer value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.student_courseaccessrole.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(4);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record5 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, String, String, String, Integer> fieldsRow() {
return (Row5) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, String, String, String, Integer> valuesRow() {
return (Row5) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return StudentCourseaccessrole.STUDENT_COURSEACCESSROLE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return StudentCourseaccessrole.STUDENT_COURSEACCESSROLE.ORG;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return StudentCourseaccessrole.STUDENT_COURSEACCESSROLE.COURSE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return StudentCourseaccessrole.STUDENT_COURSEACCESSROLE.ROLE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field5() {
return StudentCourseaccessrole.STUDENT_COURSEACCESSROLE.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getOrg();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getCourseId();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getRole();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value5() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord value2(String value) {
setOrg(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord value3(String value) {
setCourseId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord value4(String value) {
setRole(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord value5(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentCourseaccessroleRecord values(Integer value1, String value2, String value3, String value4, Integer value5) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached StudentCourseaccessroleRecord
*/
public StudentCourseaccessroleRecord() {
super(StudentCourseaccessrole.STUDENT_COURSEACCESSROLE);
}
/**
* Create a detached, initialised StudentCourseaccessroleRecord
*/
public StudentCourseaccessroleRecord(Integer id, String org, String courseId, String role, Integer userId) {
super(StudentCourseaccessrole.STUDENT_COURSEACCESSROLE);
set(0, id);
set(1, org);
set(2, courseId);
set(3, role);
set(4, userId);
}
}
|
/*
* 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 crawlers.utils;
import org.neo4j.ogm.config.Configuration;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
/**
*
* @author zua
*/
public class Neo4jSessionFactoryForCrawlers {
private static Neo4jSessionFactoryForCrawlers factory;
private final SessionFactory sessionFactory;
private Neo4jSessionFactoryForCrawlers() {
// We pass it as the first argument to a SessionFactory instance
Configuration configuration = new Configuration();
configuration.driverConfiguration().setURI(System.getenv("GRAPHENEDB_URL"));
configuration.autoIndexConfiguration().setAutoIndex("assert");
sessionFactory = new SessionFactory(configuration, "db");
}
public static Neo4jSessionFactoryForCrawlers getInstance() {
if (factory == null) {
factory = new Neo4jSessionFactoryForCrawlers();
}
return factory;
}
public Session getNeo4jSession() {
return sessionFactory.openSession();
}
}
|
package Dao.dao;
import Dao.model.SecondDirectory;
public interface SecondDirectoryMapper {
void deleteByPrimaryKey(Integer sdid);
void insert(SecondDirectory record);
void insertSelective(SecondDirectory record);
SecondDirectory selectByPrimaryKey(Integer sdid);
void updateByPrimaryKeySelective(SecondDirectory record);
void updateByPrimaryKey(SecondDirectory record);
} |
package com.git.cloud.dic.dao;
import java.util.List;
import java.util.Map;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.common.support.Pagination;
import com.git.cloud.common.support.PaginationParam;
import com.git.cloud.dic.model.po.DicTypePo;
import com.git.cloud.dic.model.po.DicPo;
public interface IDicDao extends ICommonDAO{
/**wmy
* 修改字典类型时,数据字典表中的名称也相应进行更改
* @param map
* @throws RollbackableBizException
*/
public void updateDicTypeCode(DicTypePo dicTypePo)throws RollbackableBizException;
/**
* 查询字典类型列表
* @Title: findDicTypePage
* @Description: TODO
* @field: @param paginationParam
* @field: @return
* @field: @throws RollbackableBizException
* @return Pagination<DicTypePo>
* @throws
*/
public Pagination<DicTypePo> findDicTypePage(PaginationParam paginationParam) throws RollbackableBizException;
/**
* 保存字典类型
* @Title: saveDicType
* @Description: TODO
* @field: @param dicTypePo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void saveDicType(DicTypePo dicTypePo) throws RollbackableBizException;
/**
* 更新字典类型
* @Title: updateDicType
* @Description: TODO
* @field: @param dicTypePo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void updateDicType(DicTypePo dicTypePo) throws RollbackableBizException;
/**
* 删除字典类型
* @Title: deleteDicType
* @Description: TODO
* @field: @param id
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void deleteDicType(String id) throws RollbackableBizException;
/**
* 根据字典类型ID判断该字典类型下有无字典
* @Title: haveDic
* @Description: TODO
* @field: @param dicTypeCode
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public boolean haveDic(String dicTypeCode) throws RollbackableBizException;
/**
* 判断字典类型名称是否存在
* @Title: dicTypeNameExist
* @Description: TODO
* @field: @param dicTyepName
* @field: @return
* @field: @throws RollbackableBizException
* @return boolean
* @throws
*/
public boolean dicTypeNameExist(String dicTyepName,String dicTypeCode) throws RollbackableBizException;
/**
* 根据dicTypeCode 查询字典类型
* @Title: findDicTypeByCode
* @Description: TODO
* @field: @param dicTypeCode
* @field: @return
* @field: @throws RollbackableBizException
* @return List
* @throws
*/
public DicTypePo findDicTypeByCode(String dicTypeCode) throws RollbackableBizException;
/**
* 查询字典列表
* @Title: findDicPage
* @Description: TODO
* @field: @param paginationParam
* @field: @return
* @field: @throws RollbackableBizException
* @return Pagination<DicPo>
* @throws
*/
public Pagination<DicPo> findDicPage(PaginationParam paginationParam) throws RollbackableBizException;
/**
* 保存字典
* @Title: saveDic
* @Description: TODO
* @field: @param dicPo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void saveDic(DicPo dicPo) throws RollbackableBizException;
/**
* 更新字典
* @Title: updateDic
* @Description: TODO
* @field: @param dicPo
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void updateDic(DicPo dicPo) throws RollbackableBizException;
/**
* 删除字典
* @Title: deleteDic
* @Description: TODO
* @field: @param id
* @field: @throws RollbackableBizException
* @return void
* @throws
*/
public void deleteDic(String id) throws RollbackableBizException;
/**
* 判断字典名称是否存在
* @Title: dicNameExist
* @Description: TODO
* @field: @param dicTyepName
* @field: @return
* @field: @throws RollbackableBizException
* @return boolean
* @throws
*/
public boolean dicNameExist(String dicName,String dicCode,String dicTypeCode) throws RollbackableBizException;
/**
* 根据dicCode 查询字典
* @Title: findDicByCode
* @Description: TODO
* @field: @param dicCode
* @field: @return
* @field: @throws RollbackableBizException
* @return List
* @throws
*/
public DicPo findDicById(String dicId) throws RollbackableBizException;
/**
* wmy,验证字典名称不能重复
* @param name
* @return
* @throws RollbackableBizException
*/
public DicTypePo validateDicTypeName(String name)throws RollbackableBizException;
public String findDicNameByDicCode(String dicCode)throws RollbackableBizException;
} |
package com.foodkal.app.build.configure;
/**
* Created by Tamil on 9/22/2017.
*/
public class BuildConfigure {
/* Dev Mode*/
public static String BASE_URL = "http://demo.newstartup.in/";
public static String CLIENT_SECRET = "vH1Fn3f3tjbn8eWonP30ygbhmpF4pmv1s8WQX0RJ";
public static String CLIENT_ID = "2";
//Pubnub for Chat
public static String PUBNUB_PUBLISH_KEY = "pub-c-2e80d162-68ec-4005-b6ca-5b416c9b2b8a";
public static String PUBNUB_SUBSCRIBE_KEY = "sub-c-68fb6f54-bb01-11e7-bcea-b64ad28a6f98";
public static String PUBNUB_CHANNEL_NAME = "21";
//Stripe for card payment
public static String STRIPE_PK = "pk_test_39kly6aEfUEfvMpRnN6BnxLb";
}
|
package com.example.interview.bankCallSystem.impl_3;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class MainTest {
public static void main(String[] args) {
final ExecutorService threadPool = Executors.newCachedThreadPool();
// 每个队伍 最多有10人 //之所以要生成一个Producer,是因为这里不能加static,否则无法调用基类的底层方法(很多不是static的,而你又不能改!!!)
final ArrayBlockingQueue<Consumer> normals = new ArrayBlockingQueue<>(10);
final ArrayBlockingQueue<Consumer> vips = new ArrayBlockingQueue<>(10);
final ArrayBlockingQueue<Consumer> quicks = new ArrayBlockingQueue<>(10);
//step1: init客户
final Producer producer = new Producer();
producer.setNormals(normals);
producer.setQuicks(quicks);
producer.setVips(vips);
//向不同type的客户队列中添加init客户
threadPool.execute(() -> producer.produce()); //子线程生成客户,等待取用,模拟比例: VIP客户 :快速客户 :普通客户 = 1 :3 :6
//step2: //初始化 1~6号窗口
final WindowList Windows = new WindowList();
//step3: 调度器: 融合 window + 客户,构成业务办理
final Dispatcher dispatcher=new Dispatcher();
//(获取空闲的window,让当前的customer办理业务,当前[type1的队列]没人就到[type2的队列]找人,以此类推...)
threadPool.execute(() -> dispatcher.doQuick(threadPool, Windows, vips, normals, quicks));
threadPool.execute(() -> dispatcher.doVIP(threadPool, Windows, vips, normals, quicks));
threadPool.execute(() -> dispatcher.doNomal(threadPool, Windows, vips, normals, quicks));
//step4: 任务通道已打通完成,做以总结:
threadPool.execute(() -> {
try {
while (true) {
// http://blog.csdn.net/yingzishizhe/article/details/8769907
int threadCount = ((ThreadPoolExecutor) threadPool).getActiveCount();
System.out.println("现在活跃的线程数量为: " + threadCount);//当前工作的线程:5(五个.execute()执行线程的方法)
System.out.println("现在排队的人数为:" + (vips.size() + normals.size() + quicks.size()));
Thread.sleep(3000);
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
|
package com.meizu.scriptkeeper.constant;
import android.os.Environment;
import java.io.File;
/**
* Author: jinghao
* Date: 2015-01-06
*/
public class Constants {
public static final String SYSTEM_RUN_UIAUTOMATOR_A4 = "/system/bin/sh /data/data/com.meizu.scriptkeeper/files/uitest/a4/uiautomator ";
public static final String SYSTEM_RUN_UIAUTOMATOR_A5 = "/system/bin/sh /data/data/com.meizu.scriptkeeper/files/uitest/a5/uiautomator ";
public static final String SYSTEM_RUN_MONKEY_A4 = "/system/bin/sh /data/data/com.meizu.scriptkeeper/files/uitest/a4/monkey ";
public static final String SYSTEM_RUN_MONKEY_A5 = "/system/bin/sh /data/data/com.meizu.scriptkeeper/files/uitest/a5/monkey ";
public static final String SYSTEM_BIN_PATH = "/system/bin/";
public static final String SD_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator;
public static final String TEST_RESULT = SD_PATH + "TestResult" + File.separator;
public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getPath() + "/Download/";
public static final String DATA_PATH = Environment.getDataDirectory().getPath();
public static final String DATA_LOCAL_TMP_PATH = "/data/local/tmp/";
public static final String DALVIK_CACHE_PATH = "/data/local/tmp/dalvik-cache";
public static final String RUN_UIAUTOMATOR = "uiautomator runtest ";
public static final String RESULT_ZIP_PATH = TEST_RESULT + "result.zip";
public static final String PERFORMANCE_TABLE = "performance";
public static final String APPLICATION_PID = "APPLICATION_PID";
public static final String U_RESULT_TABLE = "u_result";
}
|
package com.youthlin.demo.mvc.dao;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import java.util.Properties;
/**
* @author : youthlin.chen @ 2019-06-06 20:17
*/
@Slf4j
@Intercepts(@Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }))
public class StatementInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
log.info("target:{}, method:{}, arg:{}", invocation.getTarget(), invocation.getMethod(), invocation.getArgs());
return invocation.proceed();
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
@Override
public void setProperties(Properties properties) {
log.info("setProperties:{}", properties);
}
}
|
package com.wencheng.web.controller.manager;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wencheng.dao.impl.NewsDaoImpl;
import com.wencheng.domain.News;
import com.wencheng.utils.WebUtils;
public class NewsAction extends HttpServlet {
/**
* Constructor of the object.
*/
public NewsAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
NewsDaoImpl dao = new NewsDaoImpl();
News bean = new News();
WebUtils.getBean(bean, request);
String id = request.getParameter("managerid");
String id1 = request.getParameter("schoolid");
if(id == null || WebUtils.isSubmit(request)){
response.sendRedirect(request.getContextPath()+"/manager/createnews?errormessage="+URLEncoder.encode("创建失败","utf-8"));
return;
}
if(dao.create(bean, Integer.parseInt(id),id1)){
response.sendRedirect(request.getContextPath()+"/manager/mynews");
return;
}else{
response.sendRedirect(request.getContextPath()+"/manager/createnews?errormessage="+URLEncoder.encode("创建失败","utf-8"));
return;
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//doGet
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
|
package com.fanfte.netty.im.server.handler;
import com.fanfte.netty.im.packet.request.LoginRequestPacket;
import com.fanfte.netty.im.message.Packet;
import com.fanfte.netty.im.message.codec.PacketCodec;
import com.fanfte.netty.im.packet.request.MessageRequestPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Created by tianen on 2018/9/16
*
* @author fanfte
* @date 2018/9/16
**/
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf requestByteBuf = (ByteBuf) msg;
Packet packet = PacketCodec.getInstance().decode(requestByteBuf);
if(packet instanceof LoginRequestPacket) {
} else if(packet instanceof MessageRequestPacket) {
}
}
}
|
package net.tanpeng.arithmetic.offers;
import java.util.ArrayDeque;
import java.util.ArrayList;
/**
* 剑指Offer第65题:滑动窗口的最大值
* <p>
* 题目描述:
* <p>
* 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
* 例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
* 那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
* 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
* {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1},
* {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
* <p>
* 考点:队列
*/
public class T65 {
/**
* 使用双端队列进行取巧操作,具体思路见《剑指Offer》第292页
*
* @param num
* @param size
* @return
*/
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList result = new ArrayList();
if (size < 1 || num.length < size)
return result;
// 双端队列
ArrayDeque<Integer> deque = new ArrayDeque();
//先判断 0 - size
for (int i = 0; i < size; i++) {
while (!deque.isEmpty() && num[i] >= num[deque.peekLast()])
deque.pollLast();
deque.offerLast(i);
}
for (int i = size; i < num.length; i++) {
result.add(num[deque.peekFirst()]);
while (!deque.isEmpty() && num[i] >= num[deque.peekLast()])
deque.pollLast();
if (!deque.isEmpty() && deque.peekFirst() <= i - size)
deque.pollFirst();
deque.offerLast(i);
}
result.add(num[deque.peekFirst()]);
return result;
}
/**
* 时间复杂度特别高的方法
*
* @param num
* @param size
* @return
*/
public ArrayList<Integer> maxInWindows2(int[] num, int size) {
ArrayList result = new ArrayList();
if (size < 1)
return result;
int maxItem;
for (int i = 0; i < num.length - size + 1; i++) {
maxItem = num[i];
for (int j = i + 1; j < i + size; j++) {
if (num[j] > maxItem)
maxItem = num[j];
}
result.add(maxItem);
}
return result;
}
}
|
package com.kg;
import com.kg.fft.FFT;
import com.kg.python.SpotifyDLTest;
import com.kg.synth.*;
import com.kg.wub.AudioObject;
import com.kg.wub.system.CentralCommand;
import com.myronmarston.music.Instrument;
import eu.hansolo.fx.regulators.GradientLookup;
import eu.hansolo.fx.regulators.Regulator;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.*;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.paint.Stop;
import javafx.scene.text.Font;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.ShortMessage;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import static com.kg.python.SpotifyDLTest.STEMS.*;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_ACCENT;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_CUTOFF;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_DECAY;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_ENVMOD;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_RESONANCE;
import static com.kg.synth.BasslineSynthesizer.MSG_CC_TUNE;
public class TheHorde extends Application {
public static SpotifyDLTest.STEMS stem = STEM0;
private Canvas sequencerCanvas;
private Canvas visualizerCanvas;
private Canvas trackerCanvas;
private int selectedSequencer = 0;
public static Output output;
private int canvasYHeight;
private int canvasYoffset;
private GradientLookup gradientLookup;
private static double main_vol;
private static final double SCALE_FACTOR = 0.80;
private boolean drawSequencerPosition = true;
ArrayList<SequencerData>[] sd = new ArrayList[16];
public static Regulator bpm;
// FFT fft = new FFT(Output.BUFFER_SIZE, (float) Output.SAMPLE_RATE);
@Override
public void start(Stage primaryStage) throws Exception {
Stop[] stops = {
new Stop(0, Color.rgb(0, 0, 255, 1)),
new Stop(0.2, Color.rgb(0, 127, 255, 1)),
new Stop(0.4, Color.rgb(0, 255, 0, 1)),
new Stop(0.6, Color.rgb(255, 255, 0, 1)),
new Stop(0.8, Color.rgb(255, 127, 0, 1)),
new Stop(.99, Color.rgb(255, 0, 0, 1)),
new Stop(1.2, Color.rgb(255, 0, 255, 1))
};
gradientLookup = new GradientLookup(stops);
output = new Output(this);
Parent root = null;
FXMLLoader loader = new FXMLLoader(new File("data/gui.fxml").toURL());
try {
root = loader.load();
} catch (FileNotFoundException e) {
URL url = this.getClass().getClassLoader().getResource("gui.fxml");
loader = new FXMLLoader(url);
root = loader.load();
}
Map<String, Object> fxmlNamespace = loader.getNamespace();
BorderPane bp = new BorderPane(root);
bp.setBorder(new Border(new BorderStroke(Color.RED,
BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));
// Scene scene = new Scene(root);
Scene scene = new Scene(new Group(bp), 1400, 680);
bp.setPrefWidth(scene.getWidth() * 1 / SCALE_FACTOR);
scene.widthProperty().addListener(observable -> {
bp.setPrefWidth(scene.getWidth() * 1 / SCALE_FACTOR);
});
bp.setPrefHeight(scene.getHeight() * 1 / SCALE_FACTOR);
scene.heightProperty().addListener(observable -> {
bp.setPrefHeight(scene.getHeight() * 1 / SCALE_FACTOR);
});
primaryStage.setTitle("The Horde");
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent t) {
output.dispose();
Platform.exit();
System.exit(0);
}
});
System.out.println("acid audio system starting");
ToggleGroup toggleGroup = (ToggleGroup) fxmlNamespace.get("selectsequencer");
toggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@Override
public void changed(ObservableValue<? extends Toggle> ov, Toggle t, Toggle t1) {
RadioButton chk = (RadioButton) t1.getToggleGroup().getSelectedToggle(); // Cast object to radio button
// System.out.println("Selected Radio Button - "+chk.getText());
selectedSequencer = Integer.parseInt(chk.getId().replace("select-channel-", "")) - 1;
drawSequencer();
}
});
for (Sequencer s : output.getSequencers()) {
// s.setBpm(120d);
s.randomizeSequence();
}
// output.setVolume(1d);
output.start();
System.out.println("acid audio system started");
//vol knob
final Regulator vol = (Regulator) scene.lookup("#midi-vol");
vol.setTargetValue(50);
vol.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("main vol:\t" + newValue);
main_vol = newValue.doubleValue() / 127d;
// for (Sequencer seq : output.getSequencers()) {
// main_vol =seq.getVolume()*newValue.doubleValue() / 127d;
// System.out.println("val="+val);
// seq.setVolume(val);
// }
}
});
final Button wub = (Button) scene.lookup("#wub");
wub.setOnAction(new EventHandler<>() {
@Override
public void handle(ActionEvent event) {
new Thread(new Runnable() {
@Override
public void run() {
// Song song = SongManager.getRandom();
// System.out.println("bpm:" + output.getSequencers()[selectedSequencer].getBpm() + "\t" + song.analysis.getTempo());
// Song song1 = AudioUtils.timeStretch(song, output.getSequencers()[selectedSequencer].getBpm());
// new AudioObject(song1, null);
AudioObject.factory();
}
}).start();
}
});
//midi start
final Button midiStart = (Button) scene.lookup("#midi-start");
midiStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("midistart clicked");
Sequencer seq = output.getSequencers()[0];
if (seq instanceof MidiSequencer) {
MidiDevice md = ((MidiSequencer) seq).midiDeviceReceiver;
if (md != null) {
try {
// md.getReceiver().send(new ShortMessage(ShortMessage.STOP, ((MidiSequencer) seq).channel, 0), -1);
md.getReceiver().send(new ShortMessage(ShortMessage.START, ((MidiSequencer) seq).channel, 0), -1);
// md.getReceiver().send(new ShortMessage(ShortMessage.PROGRAM_CHANGE, selectedSequencer, (int) (Math.random() * 127), 0), -1);
} catch (MidiUnavailableException e) {
e.printStackTrace();
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
}
}
for (Sequencer seq1 : output.getSequencers()) {
seq1.reset();
}
output.resume();
}
});
midiStart.fire();
//midi stop
final Button midiStop = (Button) scene.lookup("#midi-stop");
midiStop.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("midistop clicked");
Sequencer seq = output.getSequencers()[0];
if (seq instanceof MidiSequencer) {
MidiDevice md = ((MidiSequencer) seq).midiDeviceReceiver;
if (md != null) {
try {
md.getReceiver().send(new ShortMessage(ShortMessage.STOP, ((MidiSequencer) seq).channel, 0), -1);
// md.getReceiver().send(new ShortMessage(ShortMessage.PROGRAM_CHANGE, selectedSequencer, (int) (Math.random() * 127), 0), -1);
} catch (MidiUnavailableException e) {
e.printStackTrace();
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
}
}
output.pause();
}
});
//program change
final Button progDown = (Button) scene.lookup("#midi-prog-change-down");
progDown.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Sequencer seq = output.getSequencers()[selectedSequencer];
if (seq instanceof MidiSequencer) {
MidiDevice md = ((MidiSequencer) seq).midiDeviceReceiver;
if (md != null) {
try {
int pp = 0;
int d = (int) (Math.random() * 127f);
System.out.println("selected=" + selectedSequencer);
// md.getReceiver().send(new ShortMessage(ShortMessage.CONTROL_CHANGE, selectedSequencer, 0, pp>>7), -1);
// md.getReceiver().send(new ShortMessage(ShortMessage.CONTROL_CHANGE, selectedSequencer, 32, pp & 0x7f), -1);
md.getReceiver().send(new ShortMessage(ShortMessage.PROGRAM_CHANGE, selectedSequencer, d, 0), -1);
System.out.println("prog down clicked");
} catch (MidiUnavailableException e) {
e.printStackTrace();
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
}
}
}
});
final Button progUp = (Button) scene.lookup("#midi-prog-change-up");
progUp.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Sequencer seq = output.getSequencers()[selectedSequencer];
if (seq instanceof MidiSequencer) {
MidiDevice md = ((MidiSequencer) seq).midiDeviceReceiver;
if (md != null) {
try {
int pp = 0;
int d = (int) (Math.random() * 127f);
System.out.println("selected=" + selectedSequencer);
// md.getReceiver().send(new ShortMessage(ShortMessage.CONTROL_CHANGE, selectedSequencer, 0, pp>>7), -1);
// md.getReceiver().send(new ShortMessage(ShortMessage.CONTROL_CHANGE, selectedSequencer, 32, pp & 0x7f), -1);
md.getReceiver().send(new ShortMessage(ShortMessage.PROGRAM_CHANGE, selectedSequencer, d, 0), -1);
System.out.println("prog up clicked");
} catch (MidiUnavailableException e) {
e.printStackTrace();
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
}
}
}
});
//transpose
final Button transposeUp = (Button) scene.lookup("#transpose-up");
transposeUp.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("transpose up clicked");
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
for (int i = 0; i < bassline.note.length; i++) {
bassline.note[i]++;
}
output.getSequencers()[selectedSequencer].pitch_offset++;
}
});
final Button transposeDown = (Button) scene.lookup("#transpose-down");
transposeDown.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("transpose down clicked");
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
for (int i = 0; i < bassline.note.length; i++) {
bassline.note[i]--;
}
output.getSequencers()[selectedSequencer].pitch_offset--;
}
});
final Button transposeLeft = (Button) scene.lookup("#transpose-left");
transposeLeft.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("transpose left clicked");
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
for (int i = 0; i < bassline.note.length; i++) {
bassline.note[i % bassline.note.length] = bassline.note[(i + 1) % bassline.note.length];
bassline.pause[i % bassline.note.length] = bassline.pause[(i + 1) % bassline.note.length];
bassline.accent[i % bassline.note.length] = bassline.accent[(i + 1) % bassline.note.length];
bassline.slide[i % bassline.note.length] = bassline.slide[(i + 1) % bassline.note.length];
}
}
});
final Button transposeRight = (Button) scene.lookup("#transpose-right");
transposeRight.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("transpose right clicked");
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
for (int i = bassline.note.length - 1; i >= 0; i--) {
bassline.note[i % bassline.note.length] = bassline.note[(bassline.note.length + i - 1) % bassline.note.length];
bassline.pause[i % bassline.note.length] = bassline.pause[(bassline.note.length + i - 1) % bassline.note.length];
bassline.accent[i % bassline.note.length] = bassline.accent[(bassline.note.length + i - 1) % bassline.note.length];
bassline.slide[i % bassline.note.length] = bassline.slide[(bassline.note.length + i - 1) % bassline.note.length];
}
}
});
final Button trackSave = (Button) scene.lookup("#track-save");
trackSave.setOnAction(new EventHandler<ActionEvent>() {
int width = 72;
int height = 48;
int margin = 2;
@Override
public void handle(ActionEvent event) {
drawSequencerPosition = false;
drawSequencer();
System.out.println("track save clicked");
SnapshotParameters sp = new SnapshotParameters();
sequencerCanvas.snapshot(new Callback<SnapshotResult, Void>() {
@Override
public Void call(SnapshotResult param) {
drawSequencerPosition = true;
if (sd[selectedSequencer] == null) {
sd[selectedSequencer] = new ArrayList<SequencerData>();
}
GraphicsContext gc = trackerCanvas.getGraphicsContext2D();
gc.drawImage(param.getImage(), (width + margin) * (sd[selectedSequencer].size()) + margin / 2, (height + margin) * (selectedSequencer) + margin / 2 + 20, width, height);
sd[selectedSequencer].add(new SequencerData(param.getImage(), output.getSequencers()[selectedSequencer]));
System.out.println("got image!");
// JDialog dialog = new JDialog();
//// dialog.setUndecorated(true);
// dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// JLabel label = new JLabel(new ImageIcon(image));
// dialog.add(label);
// dialog.pack();
// dialog.setVisible(true);
return null;
}
}, sp, null);
}
});
//bpm knob
bpm = (Regulator) scene.lookup("#midi-bpm");
bpm.setTargetValue(Sequencer.bpm);
bpm.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
newValue = Math.floor(newValue.floatValue() * 10f) / 10f;
System.out.println("bpm:\t" + newValue);
for (Sequencer seq : output.getSequencers()) {
seq.setBpm(newValue.doubleValue());
}
}
});
//pan knobs
for (int i = 0; i < 16; i++) {
final Regulator pan = (Regulator) scene.lookup("#midi-pan-" + (i + 1));
final Regulator delay = (Regulator) scene.lookup("#midi-delay-" + (i + 1));
final Regulator reverb = (Regulator) scene.lookup("#midi-reverb-" + (i + 1));
final int finalI = i;
pan.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("pan:" + finalI + "\t" + newValue);
output.pan[finalI] = newValue.floatValue();
}
});
delay.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("delay:" + finalI + "\t" + newValue);
// output.reverb[finalI].
}
});
reverb.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("reverb:" + finalI + "\t" + newValue);
// output.pan[finalI]=newValue.floatValue();
}
});
}
//synth1 knobs
for (int i = 0; i < 6; i++) {
final Regulator regulator1 = (Regulator) scene.lookup("#synth1-knob-" + (i + 1));
// regulator1.se
final Regulator regulator2 = (Regulator) scene.lookup("#synth2-knob-" + (i + 1));
final int finalI = i;
regulator1.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("synth1:" + finalI + "\t" + newValue);
switch (finalI) {
case 0:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_TUNE, newValue.intValue());
break;
case 1:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_CUTOFF, newValue.intValue());
break;
case 2:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_RESONANCE, newValue.intValue());
break;
case 3:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_ENVMOD, newValue.intValue());
break;
case 4:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_DECAY, newValue.intValue());
break;
case 5:
((BasslineSynthesizer) output.synthesizers[3]).controlChange(MSG_CC_ACCENT, newValue.intValue());
break;
}
}
});
regulator2.targetValueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("synth2:" + finalI + "\t" + newValue);
switch (finalI) {
case 0:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_TUNE, newValue.intValue());
break;
case 1:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_CUTOFF, newValue.intValue());
break;
case 2:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_RESONANCE, newValue.intValue());
break;
case 3:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_ENVMOD, newValue.intValue());
break;
case 4:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_DECAY, newValue.intValue());
break;
case 5:
((BasslineSynthesizer) output.synthesizers[2]).controlChange(MSG_CC_ACCENT, newValue.intValue());
break;
}
}
});
}
for (int i = 0; i < Output.PARTS; i++) {
final Slider slider = (Slider) scene.lookup("#midi-sl-" + (i + 1));
final ToggleButton onButton = (ToggleButton) scene.lookup("#midi-bt-" + (i + 1));
final Button shuffleButton = (Button) scene.lookup("#midi-shuffle-" + (i + 1));
final int finalI = i;
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
if (onButton.isSelected()) {
output.getSequencers()[finalI].setVolume(new_val.doubleValue() / 127d);
}
}
});
slider.setValue(63);
GridPane.setFillHeight(slider, true);
// GridPane.setHalignment(slider, HPos.CENTER);
// onButton.setText(" ");
onButton.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
output.getSequencers()[finalI].setVolume(slider.getValue() / 127d);
onButton.setStyle("-fx-background-color: #99ff99");
} else {
output.getSequencers()[finalI].setVolume(0);
onButton.setStyle("-fx-background-color: #dddddd");
}
}
});
onButton.setStyle("-fx-background-color: #dddddd");
onButton.setSelected(true);
GridPane.setFillWidth(onButton, true);
GridPane.setFillHeight(onButton, true);
GridPane.setHalignment(onButton, HPos.CENTER);
GridPane.setValignment(onButton, VPos.CENTER);
shuffleButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
output.getSequencers()[finalI].randomizeSequence();
output.getSequencers()[finalI].randomizeRhythm();
System.out.println("shuffle clicked:" + (finalI + 1));
}
});
shuffleButton.setFont(new Font(shuffleButton.getFont().getName(), 12));
shuffleButton.setText("\u21BB");
GridPane.setFillWidth(shuffleButton, true);
GridPane.setFillHeight(shuffleButton, true);
GridPane.setHalignment(shuffleButton, HPos.CENTER);
GridPane.setValignment(shuffleButton, VPos.CENTER);
onButton.setSelected(false);
}
ArrayList<String> arr = new ArrayList<String>();
ObservableList<String> observableList = FXCollections.observableList(arr);
// observableList.add("MIDI Out");
observableList.addAll(Instrument.AVAILABLE_INSTRUMENTS);
for (int i = 0; i < Output.PARTS - 4; i++) {
final ChoiceBox cb = (ChoiceBox) scene.lookup("#midi-instrument-" + (i + 1));
if (i == 9 || ((output.getSequencers()[i] instanceof MidiSequencer && ((MidiSequencer) output.getSequencers()[i]).midiDeviceReceiver != null))) {
cb.setVisible(false);
continue;
}
cb.setItems(observableList);
if (output.getSequencers()[i] instanceof InstrumentSequencer) {
cb.getSelectionModel().select(((InstrumentSequencer) output.getSequencers()[i]).getInstrument());
}
cb.setMinWidth(150d);
GridPane.setHalignment(cb, HPos.CENTER);
GridPane.setValignment(cb, VPos.CENTER);
final int finalI = i;
cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
((InstrumentSequencer) output.getSequencers()[finalI]).instrument = (String) cb.getItems().get(newValue.intValue());
((InstrumentSequencer) output.getSequencers()[finalI]).setChannel();
System.out.println("changing to instrument:" + cb.getSelectionModel().getSelectedItem().toString() + "\t" + "on channel:" + ((InstrumentSequencer) output.getSequencers()[finalI]).channel);
}
});
}
sequencerCanvas = (Canvas) scene.lookup("#sequencer");
visualizerCanvas = (Canvas) scene.lookup("#vis");
trackerCanvas = (Canvas) scene.lookup("#tracker");
sequencerCanvas.setOnMousePressed(new EventHandler<MouseEvent>() {
private int state;
@Override
public void handle(MouseEvent e) {
if (!sequencerCanvas.contains(e.getX(), e.getY())) {
return;
}
int x = (int) (e.getX() / (sequencerCanvas.getWidth() / 16));
int y = (int) ((sequencerCanvas.getHeight() - e.getY()) / (sequencerCanvas.getHeight() / canvasYHeight) - canvasYoffset);
if (CentralCommand.setMidiHov != null && CentralCommand.setMidiAu != null) {
String midiString = "midi-" + String.format("%02d", selectedSequencer) + "-" + String.format("%03d", y);
CentralCommand.setMidiAu.midiMap.put(midiString, CentralCommand.setMidiHov);
System.out.println(midiString);
CentralCommand.setMidiAu = null;
CentralCommand.setMidiHov = null;
}
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
if (bassline != null) {
if (e.getButton() == MouseButton.PRIMARY) {
bassline.note[x] = (byte) y;
bassline.pause[x] = false;
} else if (e.getButton() == MouseButton.SECONDARY) {
// bassline.note[x] = (byte) y;
state++;
switch (state % 6) {
case 0:
bassline.pause[x] = false;
bassline.accent[x] = false;
bassline.slide[x] = false;
break;
case 1:
bassline.pause[x] = false;
bassline.accent[x] = true;
bassline.slide[x] = false;
break;
case 2:
bassline.pause[x] = true;
bassline.accent[x] = false;
bassline.slide[x] = false;
break;
case 3:
bassline.pause[x] = false;
bassline.accent[x] = false;
bassline.slide[x] = true;
break;
case 4:
bassline.pause[x] = false;
bassline.accent[x] = true;
bassline.slide[x] = true;
break;
case 5:
bassline.pause[x] = true;
bassline.accent[x] = false;
bassline.slide[x] = false;
}
}
} else {
int[][] rhythm = output.getSequencers()[selectedSequencer].getRhythm();
rhythm[y][x] = (rhythm[y][x] + 1) % 3;
}
}
});
sequencerCanvas.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
if (!sequencerCanvas.contains(e.getX(), e.getY()) || e.getButton() != MouseButton.PRIMARY) {
return;
}
int x = (int) (e.getX() / (sequencerCanvas.getWidth() / 16d));
int y = (int) ((sequencerCanvas.getHeight() - e.getY()) / (sequencerCanvas.getHeight() / canvasYHeight) - canvasYoffset);
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
if (bassline != null) {
bassline.note[x] = (byte) y;
System.out.println("note:" + y);
bassline.pause[x] = false;
} else {
}
}
});
trackerCanvas.setOnMousePressed(new EventHandler<MouseEvent>() {
private int state;
int width = 72;
int height = 48;
int margin = 2;
//(x-margin/2)/(width+margin)=(xloc)
//(y-margin/2+20)/(height+margin)=(yloc)
@Override
public void handle(MouseEvent e) {
if (!trackerCanvas.contains(e.getX(), e.getY())) {
return;
}
int xLoc = (int) ((e.getX() - (margin / 2)) / (width + margin));
int yLoc = (int) ((e.getY() - (margin / 2 + 20)) / (height + margin));
System.out.println("Clicked on tracker canvas " + xLoc + "\t" + yLoc);
if (sd[yLoc] != null) {
if (xLoc < sd[yLoc].size() && sd[yLoc].get(xLoc) != null) {
output.getSequencers()[selectedSequencer].setSequence(sd[yLoc].get(xLoc));
}
}
}
});
trackerCanvas.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
if (!trackerCanvas.contains(e.getX(), e.getY()) || e.getButton() != MouseButton.PRIMARY) {
return;
}
System.out.println("dragged on tracker canvas");
}
});
drawSequencer();
primaryStage.setScene(scene);
primaryStage.show();
Scale scale = new Scale(SCALE_FACTOR, SCALE_FACTOR);
scale.setPivotX(0);
scale.setPivotY(0);
bp.getTransforms().setAll(scale);
}
public void drawTracker() {
Platform.runLater(new Runnable() {
@Override
public void run() {
//draw tracker here
}
});
}
boolean seqLock = false;
public void drawSequencer() {
if (seqLock) {
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
seqLock = true;
BasslinePattern bassline = output.getSequencers()[selectedSequencer].getBassline();
if (sequencerCanvas == null) return;
int step = output.getSequencers()[selectedSequencer].step;
double width = sequencerCanvas.getWidth();
double height = sequencerCanvas.getHeight();
double widthDist = width / 16d;
if (output.getSequencers()[selectedSequencer] instanceof RhythmSequencer) {
canvasYoffset = 0;
canvasYHeight = 7;
} else {
canvasYHeight = 96;
canvasYoffset = 23;
}
double heightDist = height / canvasYHeight;
GraphicsContext gc = sequencerCanvas.getGraphicsContext2D();
Color gl = gradientLookup.getColorAt(selectedSequencer / 16d).darker().darker().darker();
gc.setFill(gl.darker());
gc.fillRect(0, 0, sequencerCanvas.getWidth(), sequencerCanvas.getHeight());
gc.setStroke(gl);
gc.setLineWidth(2);
for (int i = 0; i < 17; i++) {
if (i % 4 == 0) {
gc.setStroke(gl.brighter());
} else {
gc.setStroke(gl);
}
gc.strokeLine(i * widthDist, 0, i * widthDist, height);
}
gc.setStroke(gl);
gc.setLineWidth(1);
for (int i = 0; i < canvasYHeight + 1; i++) {
if (i % 12 == 0) {
gc.setStroke(gl.brighter());
} else {
gc.setStroke(gl);
}
gc.strokeLine(0, i * heightDist, width, i * heightDist);
}
if (drawSequencerPosition) {
gc.setStroke(Color.WHITE);
gc.strokeLine(step * widthDist, 0, step * widthDist, height);
// gc.setStroke(Color.BLACK);
// gc.setLineWidth(1);
// gc.strokeLine(0, sequencerCanvas.getHeight() - output.getSequencers()[selectedSequencer].pitch_offset * heightDist, width, sequencerCanvas.getHeight() - output.getSequencers()[selectedSequencer].pitch_offset * heightDist);
}
gc.setLineWidth(2);
if (bassline != null) {
for (int i = 0; i < 16; i++) {
int note = bassline.getNote(i);
int pitch = bassline.note[i] + canvasYoffset;
if (!bassline.pause[i]) {
gc.setFill(new Color(.0d, 1d, .0d, 1d));
gc.setStroke(new Color(.0d, 1d, .0d, 1d));
gc.setLineWidth(3);
int vel = (bassline.accent[i] ? 127 : 80);
if (!bassline.accent[i]) {
gc.setStroke(new Color(.0d, 1d, .0d, 1d));
gc.setFill(new Color(.0d, 1d, .0d, 1d));
} else {
gc.setStroke(new Color(1d, .7d, 0d, 1d));
gc.setFill(new Color(1d, .7d, .0d, 1d));
}
gc.fillRoundRect(i * widthDist, height - pitch * heightDist, widthDist, heightDist, 10, 10);
gc.strokeRoundRect(i * widthDist, height - pitch * heightDist, widthDist, heightDist, 10, 10);
// gc.strokeRoundRect(i * widthDist, height - pitch * heightDist, widthDist, heightDist, 10, 10);
}
}
for (int i = 0; i < 16; i++) {
if (bassline.slide[i]) {
int pitch = bassline.note[i] + canvasYoffset;
int nextpitch = bassline.note[(i + 1) % 16] + canvasYoffset;
gc.setLineWidth(5);
gc.setStroke(new Color(1d, 1d, .0d, 1d));
gc.strokeLine(((i + 1) % 16) * widthDist, height - (pitch * heightDist) + heightDist / 2, ((i + 1) % 16) * widthDist, height - (nextpitch * heightDist) + heightDist / 2);
}
}
} else {
int[][] rhythm = output.getSequencers()[selectedSequencer].getRhythm();
for (int j = 0; j < rhythm.length; j++) {
for (int i = 0; i < rhythm[j].length; i++) {
if (rhythm[j][i] > 0) {
// if (!bassline.accent[i]) {
// gc.setStroke(new Color(.0d, 1d, .0d, 1d));
// gc.setFill(new Color(.0d, 1d, .0d, 1d));
// } else {
if (rhythm[j][i] == 1) {
gc.setStroke(new Color(1d, 1d, 0d, 1d));
gc.setFill(new Color(1d, 1d, .0d, 1d));
}
if (rhythm[j][i] == 2) {
gc.setStroke(new Color(1d, .7d, 0d, 1d));
gc.setFill(new Color(1d, .7d, .0d, 1d));
}
// }
gc.fillRoundRect(i * widthDist, height - (j + 1) * heightDist, widthDist, heightDist, 10, 10);
gc.strokeRoundRect(i * widthDist, height - (j + 1) * heightDist, widthDist, heightDist, 10, 10);
}
}
}
}
seqLock = false;
}
});
// gc.setLineWidth(5);
// gc.strokeLine(40, 10, 10, 40);
// gc.fillOval(10, 60, 30, 30);
// gc.strokeOval(60, 60, 30, 30);
// gc.fillRoundRect(110, 60, 30, 30, 10, 10);
// gc.strokeRoundRect(160, 60, 30, 30, 10, 10);
// gc.fillArc(10, 110, 30, 30, 45, 240, ArcType.OPEN);
// gc.fillArc(60, 110, 30, 30, 45, 240, ArcType.CHORD);
// gc.fillArc(110, 110, 30, 30, 45, 240, ArcType.ROUND);
// gc.strokeArc(10, 160, 30, 30, 45, 240, ArcType.OPEN);
// gc.strokeArc(60, 160, 30, 30, 45, 240, ArcType.CHORD);
// gc.strokeArc(110, 160, 30, 30, 45, 240, ArcType.ROUND);
// gc.fillPolygon(new double[]{10, 40, 10, 40},
// new double[]{210, 210, 240, 240}, 4);
// gc.strokePolygon(new double[]{60, 90, 60, 90},
// new double[]{210, 210, 240, 240}, 4);
// gc.strokePolyline(new double[]{110, 140, 110, 140},
// new double[]{210, 210, 240, 240}, 4);
}
public static void main(String args[]) {
System.out.println("horde started");
if (args.length == 1) {
String[] temp = args[0].split(" ");
if (temp.length > 1) {
args = temp;
}
}
System.out.println("args=" + Arrays.toString(args));
String wub = null;
double tempo = 0;
top:
for (String arg : args) {
switch (arg) {
default:
break;
case "STEM0":
TheHorde.stem = STEM0;
System.out.println("STEM0");
continue top;
case "STEM2":
TheHorde.stem = STEM2;
System.out.println("STEM2");
continue top;
case "STEM4":
TheHorde.stem = STEM4;
System.out.println("STEM4");
continue top;
case "STEM5":
TheHorde.stem = STEM5;
System.out.println("STEM5");
continue top;
}
try {
Sequencer.bpm = Integer.parseInt(arg);
System.out.println("set tempo to:" + Sequencer.bpm);
tempo = Sequencer.bpm;
} catch (NumberFormatException e) {
wub = arg;
}
}
Sequencer.bpm = 120;
if (wub != null) {
Sequencer.bpm = tempo;
String finalWub = wub;
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
CentralCommand.ccn.nodes.size();
TheHorde.output.mixingAudioInputStream.getFormat();
break;
} catch (Exception e) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
AudioObject.factory(finalWub);
}
}).start();
}
launch(args);
}
//double max=Double.MIN_VALUE;
//double min=Double.MAX_VALUE;
private double[] lastBytes = new double[256];
private double[] accel = new double[256];
boolean visLock = false;
float[] fftf = new float[256];
public void drawVisualizer(final byte[] buffer5) {
if (visLock) {
return;
}
Platform.runLater(new Runnable() {
@Override
public void run() {
visLock = true;
if (visualizerCanvas != null) {
double width = visualizerCanvas.getWidth();
double height = visualizerCanvas.getHeight();
fftf = calculateFFT(buffer5, 256);
GraphicsContext gc = visualizerCanvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(0, 0, width, height);
gc.setStroke(new Color(1d, 1d, 1d, 1d));
double dw = width / 256d;
gc.setLineWidth(dw + .03f);
for (int i = 0; i < 256; i++) {
double perc = (double) i / width;
int l = (int) (perc * fftf.length);
double mag = fftf[l];
Color co = gradientLookup.getColorAt(Math.min(1, mag / 2));
// Color co1=new Color(co.getRed(),co.getGreen(),co.getBlue(),1d);
Color lastco = gradientLookup.getColorAt(Math.min(1, lastBytes[l] / 2));
// gc.setStroke(Color.WHITE);
gc.setStroke(lastco);
// gc.strokeLine(i * dw-dw/2, height - lastBytes[l] / 3 * height, i * dw + dw/2, height - lastBytes[l] / 3 * height);
gc.strokeLine(i * dw, 1 + height - lastBytes[l] / 3 * height, i * dw, height - lastBytes[l] / 3 * height);
if (mag > lastBytes[l]) {
lastBytes[l] = mag;
accel[l] = 0;
} else {
lastBytes[l] -= accel[l];
accel[l] += .001d;
}
// lastBytes[l] /= 100d;
gc.setStroke(co);
gc.strokeLine(i * dw, height, i * dw, height - mag / 3 * height);
}
visLock = false;
}
}
});
}
FFT fft = new FFT(Output.BUFFER_SIZE / 2, (float) Output.SAMPLE_RATE);
public float[] calculateFFT(byte[] signal, int width) {
//fft.window(new GaussWindow());
fft.linAverages(width);
// fft.logAverages(44100/640,256/8);
final int mNumberOfFFTPoints = signal.length / 2;
// double temp;
float[] buf = new float[mNumberOfFFTPoints];
// Complex[] y;
// Complex[] complexSignal = new Complex[mNumberOfFFTPoints];
// double[] absSignal = new double[mNumberOfFFTPoints / 2];
//
for (int i = 0; i < mNumberOfFFTPoints; i++) {
buf[i] = (float) ((signal[2 * i] & 0xFF) | (signal[2 * i + 1] << 8)) / 32768.0F;
}
//
fft.forward(buf);
float[] ret = new float[width];
for (int i = 0; i < width; i++) {
ret[i] = Math.min(fft.getAvg(i), 3f);
}
return ret;
// y = FFT6.fft(complexSignal);
//
// for (int i = 0; i < (mNumberOfFFTPoints / 2); i++) {
// absSignal[i] = Math.sqrt(Math.pow(y[i].re(), 2) + Math.pow(y[i].im(), 2));
// }
//
// return absSignal;
}
} |
package history;
/**
* Class <code>HistoryObject</code> is only used by the History class
* as a way to store the reset points with the objects.
*
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
*/
class HistoryObject {
private Object obj;
private boolean reset;
public HistoryObject(Object obj, boolean resetPoint) {
this.obj = obj;
this.reset = resetPoint;
}
public Object getObject() {
return obj;
}
public boolean isResetPoint() {
return reset;
}
}
|
package ru.plotnikov.factory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FactoryManager {
public static UserDaoFactory getFactory() {
try (InputStream input = FactoryManager.class.getClassLoader().getResourceAsStream("config.properties")) {
Properties properties = new Properties();
if (input==null) {
throw new IOException("Sorry, unable to find config.properties");
}
properties.load(input);
if (properties.getProperty("factory").equals("Hibernate"))
return new UserHibernateDaoFactory();
if (properties.getProperty("factory").equals("Jdbc"))
return new UserJdbcDaoFactory();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package com.tomaszdebski.decerto.controller;
import com.tomaszdebski.decerto.dto.QuoteDto;
import com.tomaszdebski.decerto.exception.QuoteNotFoundException;
import com.tomaszdebski.decerto.service.QuoteService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.LinkedMultiValueMap;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
public class QuoteControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private QuoteService quoteService;
@Test
public void getAllQuotes() throws Exception
{
QuoteDto quoteDto = QuoteDto.builder()
.withId(1L)
.withAuthorFirstName("firstName1")
.withAuthorLastName("LastName1")
.withContent("content1").build();
QuoteDto quoteDto2 = QuoteDto.builder()
.withId(2L)
.withAuthorFirstName("firstName2")
.withAuthorLastName("LastName2")
.withContent("content2").build();
List<QuoteDto> quotes = Arrays.asList(quoteDto, quoteDto2);
when(quoteService.getAllQuote(1,10)).thenReturn(quotes);
LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add("pageNo", "1");
requestParams.add("pageSize", "10");
mockMvc.perform( MockMvcRequestBuilders
.get("/quotes")
.params(requestParams)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.*", hasSize(2)))
.andExpect(MockMvcResultMatchers.jsonPath("$.[*].authorFirstName").isNotEmpty())
.andExpect(MockMvcResultMatchers.jsonPath("$.[*].authorLastName").isNotEmpty());
}
@Test
public void checkOneQuote() throws Exception{
QuoteDto quoteDto = QuoteDto.builder()
.withId(1L)
.withAuthorFirstName("authorFirstName")
.withAuthorLastName("authorLastName")
.withContent("content").build();
when(quoteService.getQuote(1L)).thenReturn(quoteDto);
mockMvc.perform(MockMvcRequestBuilders.
get("/quotes/1")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.authorFirstName").value("authorFirstName"))
.andExpect(jsonPath("$.authorLastName").value("authorLastName"))
.andExpect(jsonPath("$.content").value("content"));
}
@Test
public void checkOneQuoteThrowException() throws Exception{
when(quoteService.getQuote(1L)).thenThrow(new QuoteNotFoundException(1L));
mockMvc.perform(MockMvcRequestBuilders.
get("/quotes/1")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(result -> assertTrue(result.getResolvedException() instanceof QuoteNotFoundException));
}
}
|
package dataset;
public enum Datasets {
JORDANIAN(1);
private Datasets(int id) {
this.datasetId = id;
}
public int datasetId;
}
|
package com.alevohin.demo.acceptence;
import com.alevohin.demo.CalculatorResult;
import com.alevohin.demo.DemoApplication;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import io.dropwizard.testing.junit.DropwizardAppRule;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.JerseyClientBuilder;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class SubtractTest {
@ClassRule
public static final DropwizardAppRule RULE = new DropwizardAppRule(DemoApplication.class);
@Test
@UseDataProvider("dataProviderSubtract2")
public void subtract2(String a, String b, String expected) {
Client client = new JerseyClientBuilder().build();
final String url = String.format(
"http://localhost:%d/subtract/%s/%s",
RULE.getLocalPort(), a, b
);
final Response response = client.target(url).request().get();
assertThat(response.getStatus()).isEqualTo(200);
CalculatorResult calculatorResult = response.readEntity(CalculatorResult.class);
assertThat(calculatorResult.getValue()).isEqualTo(expected);
}
@DataProvider
public static Object[][] dataProviderSubtract2() {
return new Object[][]{
{"0", "0", "0"},
{"1", "2", "-1"},
{"1.3", "2.4", "-1.1"},
{"2", "1", "1"},
{"1", "-1", "2"},
{"1.5", "1.5", "0"},
{"-1.5", "-1.41", "-0.09"},
{"1E-1", "1E-1", "0"},
};
}
@Test
@UseDataProvider("dataProviderSubtract3")
public void subtract3(String a, String b, String c, String expected) {
Client client = new JerseyClientBuilder().build();
final String url = String.format(
"http://localhost:%d/subtract/%s/%s/%s",
RULE.getLocalPort(), a, b, c
);
final Response response = client.target(url).request().get();
assertThat(response.getStatus()).isEqualTo(200);
CalculatorResult calculatorResult = response.readEntity(CalculatorResult.class);
assertThat(calculatorResult.getValue()).isEqualTo(expected);
}
@DataProvider
public static Object[][] dataProviderSubtract3() {
return new Object[][]{
{"0", "0", "0", "0"},
{"1", "2", "3", "-4"},
{"-1.3", "2.4", "3.7", "-7.4"},
{"3", "2", "1", "0"},
{"1", "1", "0", "0"},
{"1.5", "1.5", "0", "0"},
{"1.5", "0", "1.5", "0"},
{"1.5", "1.41", "+1.21", "-1.12"},
};
}
@Test
@UseDataProvider("dataProviderSubtractError")
public void subtractError(String params, int code) {
Client client = new JerseyClientBuilder().build();
final String url = String.format(
"http://localhost:%d/subtract%s",
RULE.getLocalPort(), params
);
final Response response = client.target(url).request().get();
assertThat(response.getStatus()).isEqualTo(code);
}
@DataProvider
public static Object[][] dataProviderSubtractError() {
return new Object[][]{
{"/1/a", 400},
{"/a/2", 400},
{"/1/2/a", 400},
{"/1.11.1/2", 400}
};
}
}
|
package com.test.base;
/**
* @author YLine
*
* 2019年5月7日 上午9:42:52
*/
public interface Solution
{
public boolean findTarget(TreeNode root, int k);
}
|
package sandBox1;
/**
* Created by hansoljeong on 2015. 11. 6..
*/
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class sandBoxRunner {
private List<Name> name;
private sandBoxConfig theHibernateUtility;
public sandBoxRunner(){
theHibernateUtility = new sandBoxConfig();
}
public static void main(String[] args){
sandBoxRunner addressExample = new sandBoxRunner();
addressExample.addNewUsers();
addressExample.showAllUsers();
addressExample.modifyUser();
//addressExample.addRoomNumbers();
addressExample.addPhoneNumber();
}
/*
* show how to add records to the database
*/
private void addNewUsers() {
//get physical connection with a database. Lightweight and designed to be instantiated each time an interaction
// is needed with the database.
Session session = theHibernateUtility.getCurrentSession();
/*
* all database interactions in Hibernate are required to be inside a transaction.
* Begin a unit of work and return the associated Transaction object.
*/
Transaction transaction = session.beginTransaction();
/*
* create some User instances.
*/
Name hansol = new Name();
Name wontak = new Name();
try{
hansol.setRname("Hansol");
hansol.setRoomNum(2301);
wontak.setRname("Wontak");
wontak.setRoomNum(303);
/* Many ways of nasty-path
* jade.setUname(null); // Null is invalid value to put.
* jade.setPword(null);
*
* //
* jade.setUname(String.valueOf());
* jade.setPword();
*/
}catch(Exception e){
e.printStackTrace();
}
/*
* save each instance as a record in the database
*/
try {
session.save(hansol);
session.save(wontak);
}catch(Exception e){
e.printStackTrace();
}
//If setUname is null, an assertion failure occurs.
transaction.commit(); //commit() forces database to be saved permanently
/*
* prove that the User instances were added to the database and that
* the instances were each updated with a database generated id.
*/
System.out.println("aUser generated ID is: " + hansol.getId());
}
/*
* show how to get a collection of type List containing all of the records in the app_user table
*/
private void showAllUsers() {
Session session = theHibernateUtility.getCurrentSession();
Transaction transaction = session.beginTransaction();
/*
* execute a HQL query against the database. HQL is NOT SQL. It is object based.
*/
Query allUsersQuery = session.createQuery("select n from Name as n order by n.id");
/*
* get a list of User instances based on what was found in the database tables.
*/
name = allUsersQuery.list(); //Three users
System.out.println("num users: " + name.size());
/*
* iterate over each User instance returned by the query and found in the list.
*/
Iterator<Name> iter = name.iterator();;
while(iter.hasNext()) {
Name element = iter.next();
System.out.println(element.toString());
System.out.println("num of phone numbers: "+element.getPhoneNumbers().size());
}
transaction.commit();
}
/*
* show how to modify a database record
*/
private void modifyUser() {
Session session = theHibernateUtility.getCurrentSession();
Transaction transaction = session.beginTransaction();
Name hansol;
try {
/*
* get a single User instance from the database.
*/
//The name here has to be matched to setName on the main. Otherwise, it will shows the error NullPointerException
Query singleUserQuery = session.createQuery("select n from Name as n where n.rname='Hansol'");
hansol = (Name) singleUserQuery.uniqueResult();
/*s
* change the user name for the Java instance
*/
hansol.setRname("Hansol Jeong");
/*
* call the session merge method for the User instance in question. This tells the database that the instance is ready to be permanently stored.
* Merge method causes the existing row in the database table to be updated rather than creating a new one.
*/
session.merge(hansol);
//session.save(jade) cannot be used on here, because it does not store entities in a completed session. BUt it notifies the database to do a provisional save.
/*
* call the transaction commit method. This tells the database that the changes are ready to be permanently stored.
*/
}catch(Exception e){
e.printStackTrace();
}
transaction.commit();
/*
* permanently store the changes into the database tables.
*/
showAllUsers();
}
private void addPhoneNumber(){
Session session = theHibernateUtility.getCurrentSession();
Transaction transaction = session.beginTransaction();
Query hansolQuery = session.createQuery("select n from Name as n where n.rname='Hansol Jeong'");
Name hansolName = (Name) hansolQuery.uniqueResult();
Query wontakQuery = session.createQuery("select n from Name as n where n.rname='Wontak'");
Name wontakName = (Name) wontakQuery.uniqueResult();
Contact addPhoneNumber = new Contact();
addPhoneNumber.setPhone("(801)989-2444");
Contact wontaksNumber = new Contact();
wontaksNumber.setPhone("(801)989-2444");
Set<Contact> addPhoneNumbers = hansolName.getPhoneNumbers();
addPhoneNumbers.add(addPhoneNumber);
Set<Contact> wontaksPhoneNumbers = wontakName.getPhoneNumbers();
wontaksPhoneNumbers.add(wontaksNumber);
session.save(addPhoneNumber);
session.save(wontaksNumber);
session.merge(hansolName);
session.merge(wontakName);
transaction.commit();
showAllUsers();
}
}
|
package com.needii.dashboard.model;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.util.Date;
/**
* The persistent class for the admin_privileges database table.
*
*/
@Entity
@Table(name="admin_privileges")
@NamedQuery(name="AdminPrivilege.findAll", query="SELECT a FROM AdminPrivilege a")
public class AdminPrivilege implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_at")
@CreationTimestamp
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="updated_at")
@UpdateTimestamp
private Date updatedAt;
//bi-directional many-to-one association to Privilege
// @ManyToOne
// @JoinColumn(name="privileges_id")
// private Privilege privilege;
@Column(name="privileges_id")
private int privilegeId;
//bi-directional many-to-one association to Admin
@ManyToOne
private Admin admin;
public AdminPrivilege() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Admin getAdmin() {
return this.admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public int getPrivilegeId() {
return privilegeId;
}
public void setPrivilegeId(int privilegeId) {
this.privilegeId = privilegeId;
}
} |
package org.wuxinshui.boosters.designPatterns.simpleFacthory.moreMethods;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by FujiRen on 2016/10/30.
*/
public class SendFactoryTest {
@Test
public void produceEmail() throws Exception {
SendFactory factory = new SendFactory();
Sender sender = factory.produceEmail();
sender.send();
}
@Test
public void produceSms() throws Exception {
SendFactory factory = new SendFactory();
Sender sender = factory.produceSms();
sender.send();
}
} |
public class Clerk implements Runnable {
public int ID;
// public static long time = System.currentTimeMillis(); // Maybe sync the time
public static int totalCustomersHelpedClerk;
Clerk(int ID) {
this.ID = ID;
}
@Override
public void run() {
msg("is waiting to help customers");
while (Main.customerThreads[0] == null) {
} // busy wait until at least one customer arrives.
Main.availClerks.add(this);
while (totalCustomersHelpedClerk != Main.totalCustomers) { // keep trying to help until someone has helped every customer
giveSlip();
}
try {
Thread.sleep(400000); // when we have helped all the customers, wait for closing time.
msg("is waiting for the store to close...");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
msg("is leaving because it was notified about closing time");
}
}
public void msg(String m) {
System.out.println("[" + (System.currentTimeMillis() - Main.time) + "] " + "Clerk-" + ID + ": " + m);
}
public void giveSlip() {
try {
// add to the queue
Main.waitForSlip.remove(0).setSlip(); // help the customers in a FCFS order ( one at a time )
totalCustomersHelpedClerk++;
Main.availClerks.add(this);
} catch (Exception e) {
// add to the queue
return;
// If there are no customers in line, we need to go back to busy waiting. so
// just return
}
}
} |
package pers.fpj.util;
import java.io.Serializable;
/**
*
* Created by fpj on 2017/11/15 14:28.
*/
public class ResultUtils<T> implements Serializable {
/**
* 业务状态码
*/
private int code;
/**
* 数据
*/
private T data;
/**
* 结果描述
*/
private String msg;
public ResultUtils() {
}
private ResultUtils(int code, T data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
public static DataBuilder ok() {
return new DataBuilder<>(State.OK.code());
}
public static DataBuilder created() {
return new DataBuilder<>(State.CREATED.code());
}
public static ResultUtils notFound() {
return new SimpleBuilder<>()
.setCode(State.NOT_FOUND.code())
.setData(null)
.setMsg(State.NOT_FOUND.phrase())
.build();
}
public static MsgBuilder clientError(int code) {
return new MsgBuilder<>(code);
}
public static MsgBuilder serverError(int code) {
return new MsgBuilder<>(code);
}
public static class MsgBuilder<T> extends Builder<T> {
public MsgBuilder(int code) {
this.code = code;
}
public ResultUtils<T> msg(String msg) {
return new SimpleBuilder<T>()
.setCode(this.code)
.setData(null)
.setMsg(msg)
.build();
}
}
public static class DataBuilder<T> extends Builder<T> {
public DataBuilder(int code) {
this.code = code;
}
public ResultUtils<T> data(T data) {
return new SimpleBuilder<T>()
.setCode(this.code)
.setData(data)
.setMsg(null)
.build();
}
}
public static class SimpleBuilder<T> extends Builder<T> {
public SimpleBuilder<T> setCode(int code) {
super.code = code;
return this;
}
public SimpleBuilder<T> setData(T data) {
super.data = data;
return this;
}
public SimpleBuilder<T> setMsg(String msg) {
super.msg = msg;
return this;
}
public ResultUtils<T> build() {
return new ResultUtils<T>(code, data, msg);
}
}
private static abstract class Builder<T> {
int code;
T data;
String msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public enum State {
OK(200, "执行成功"),
CREATED(201, "创建成功"),
CLIENT_ERROR(400, "请求失败"),
NOT_FOUND(404, "资源不存在"),
SERVER_ERROR(500, "处理失败");
/**
* 状态码
*/
private final int code;
/**
* 短语
*/
private final String phrase;
State(int code, String phrase) {
this.code = code;
this.phrase = phrase;
}
public int code() {
return this.code;
}
public String phrase() {
return this.phrase;
}
}
}
|
package action;
import java.util.Map;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware{
protected Map<String,Object> requestMap;
protected Map<String,Object> sessionMap;
protected Map<String,Object> contextMap;
public void setRequest(Map<String, Object> request) {
this.requestMap=request;
}
public void setSession(Map<String, Object> session) {
this.sessionMap=session;
}
public void setApplication(Map<String, Object> application) {
this.contextMap=application;
}
}
|
package com.cdkj.fastdfs.pool;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.csource.common.MyException;
/**
* @description: 文件服务器连接池
*/
public class FastdfsPool extends Pool<FastdfsClient> {
public FastdfsPool(GenericObjectPoolConfig poolConfig, String confPath, Integer objMaxActive) throws FileNotFoundException, IOException, MyException {
super(poolConfig, new FastdfsPooledObjectFactory(confPath, objMaxActive));
}
public FastdfsPool(GenericObjectPoolConfig poolConfig, Integer objMaxActive) throws IOException, MyException {
super(poolConfig, new FastdfsPooledObjectFactory(objMaxActive));
}
@Override
public void returnBrokenResource(final FastdfsClient resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
@Override
public void returnResource(final FastdfsClient resource) {
if (resource != null) {
returnResourceObject(resource);
}
}
}
|
/**
* <copyright>
* </copyright>
*
*
*/
package ssl.resource.ssl.ui;
/**
* A class used to initialize default preference values.
*/
public class SslPreferenceInitializer extends org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer {
private final static ssl.resource.ssl.ui.SslAntlrTokenHelper tokenHelper = new ssl.resource.ssl.ui.SslAntlrTokenHelper();
public void initializeDefaultPreferences() {
initializeDefaultSyntaxHighlighting();
initializeDefaultBrackets();
org.eclipse.jface.preference.IPreferenceStore store = ssl.resource.ssl.ui.SslUIPlugin.getDefault().getPreferenceStore();
// Set default value for matching brackets
store.setDefault(ssl.resource.ssl.ui.SslPreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, "192,192,192");
store.setDefault(ssl.resource.ssl.ui.SslPreferenceConstants.EDITOR_MATCHING_BRACKETS_CHECKBOX, true);
}
private void initializeDefaultBrackets() {
org.eclipse.jface.preference.IPreferenceStore store = ssl.resource.ssl.ui.SslUIPlugin.getDefault().getPreferenceStore();
initializeDefaultBrackets(store, new ssl.resource.ssl.mopp.SslMetaInformation());
}
public void initializeDefaultSyntaxHighlighting() {
org.eclipse.jface.preference.IPreferenceStore store = ssl.resource.ssl.ui.SslUIPlugin.getDefault().getPreferenceStore();
initializeDefaultSyntaxHighlighting(store, new ssl.resource.ssl.mopp.SslMetaInformation());
}
private void initializeDefaultBrackets(org.eclipse.jface.preference.IPreferenceStore store, ssl.resource.ssl.ISslMetaInformation metaInformation) {
String languageId = metaInformation.getSyntaxName();
// set default brackets for ITextResource bracket set
ssl.resource.ssl.ui.SslBracketSet bracketSet = new ssl.resource.ssl.ui.SslBracketSet(null, null);
final java.util.Collection<ssl.resource.ssl.ISslBracketPair> bracketPairs = metaInformation.getBracketPairs();
if (bracketPairs != null) {
for (ssl.resource.ssl.ISslBracketPair bracketPair : bracketPairs) {
bracketSet.addBracketPair(bracketPair.getOpeningBracket(), bracketPair.getClosingBracket(), bracketPair.isClosingEnabledInside());
}
}
store.setDefault(languageId + ssl.resource.ssl.ui.SslPreferenceConstants.EDITOR_BRACKETS_SUFFIX, bracketSet.getBracketString());
}
private void initializeDefaultSyntaxHighlighting(org.eclipse.jface.preference.IPreferenceStore store, ssl.resource.ssl.ISslMetaInformation metaInformation) {
String languageId = metaInformation.getSyntaxName();
String[] tokenNames = metaInformation.getTokenNames();
if (tokenNames == null) {
return;
}
for (int i = 0; i < tokenNames.length; i++) {
if (!tokenHelper.canBeUsedForSyntaxColoring(i)) {
continue;
}
String tokenName = tokenHelper.getTokenName(tokenNames, i);
if (tokenName == null) {
continue;
}
ssl.resource.ssl.ISslTokenStyle style = metaInformation.getDefaultTokenStyle(tokenName);
if (style != null) {
String color = getColorString(style.getColorAsRGB());
setProperties(store, languageId, tokenName, color, style.isBold(), true, style.isItalic(), style.isStrikethrough(), style.isUnderline());
} else {
setProperties(store, languageId, tokenName, "0,0,0", false, false, false, false, false);
}
}
}
private void setProperties(org.eclipse.jface.preference.IPreferenceStore store, String languageID, String tokenName, String color, boolean bold, boolean enable, boolean italic, boolean strikethrough, boolean underline) {
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.BOLD), bold);
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.COLOR), color);
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.ENABLE), enable);
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.ITALIC), italic);
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.STRIKETHROUGH), strikethrough);
store.setDefault(ssl.resource.ssl.ui.SslSyntaxColoringHelper.getPreferenceKey(languageID, tokenName, ssl.resource.ssl.ui.SslSyntaxColoringHelper.StyleProperty.UNDERLINE), underline);
}
private String getColorString(int[] colorAsRGB) {
if (colorAsRGB == null) {
return "0,0,0";
}
if (colorAsRGB.length != 3) {
return "0,0,0";
}
return colorAsRGB[0] + "," +colorAsRGB[1] + ","+ colorAsRGB[2];
}
}
|
package Commands;
import collection.Collection;
import java.io.Serializable;
/*
Краткая информация:
На сервер передается несколько пакетов:
1. Команда clear
*/
public class clearCommand implements Serializable {
private static final long serialVersionUID = 32L;
public void serverjob(Collection collection, sendCommand send) {
try {
collection.getVector().clear();
collection.fileSaving();
}catch (Exception e){
send.setMessage("Не удалось отчистить файл, проверьте, доступен/существует ли он");
}
}
}
//clear
//+ |
package com.example.homework1128v2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
import android.widget.Toast;
public class SecondActivity extends Activity {
private int count;
private int number = 1;
private int remainder;
private int groupCount;
private int memberCount;
private List<String> attendList = new ArrayList<String>();
private List<List<String>> groupList = new ArrayList<List<String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
ListView listView = (ListView) findViewById(R.id.listView1);
// 出席者情報
attendList = getIntent().getStringArrayListExtra("attendList");
// グループの人数
memberCount = getIntent().getIntExtra("menberCount", 0);
// グループ分けの誤差範囲
int range = getIntent().getIntExtra("range", -1);
// 分岐に使う変数
int checkCount = memberCount;
// リストの中身をシャッフルする。
Collections.shuffle(attendList);
// 出席者数をメンバー数で割った余り
remainder = attendList.size() % memberCount;
// グループの数
groupCount = attendList.size() / memberCount;
// グループ分け
try {
// 誤差範囲+1 or 余りなしの時の処理
if (range == 1 || remainder == 0) {
createGroup();
// 誤差範囲-1の時の処理
} else {
// メンバー数を-1してグループ数を+1する。
groupCount += 1;
memberCount -= 1;
createGroup();
}
} catch (RuntimeException e) {
// 出席者数が設定してあるグループ人数以下の時にグループ人数を変更(トースト表示用)
if (attendList.size() <= memberCount) {
memberCount = attendList.size();
// 誤差範囲+1 or try節でmemberCountを-1した時
} else if (range == 1 || memberCount != checkCount) {
// 設定条件に出来るだけ近づける為の分岐
memberCount = attendList.size() % memberCount > attendList
.size() % (memberCount + 1) ? memberCount
: memberCount + 1;
} else {
memberCount = attendList.size() % memberCount > attendList
.size() % (memberCount - 1) ? memberCount
: memberCount - 1;
}
// 設定条件でのグループ分けが出来ないので、通知する。
Toast.makeText(
SecondActivity.this,
"指定された条件でのグループ分けができませんでしたので\n" + memberCount
+ "人毎にグループ分けします。", Toast.LENGTH_SHORT).show();
// try節で代入した値で誤差が出ないように初期化
List<String> memberList = new ArrayList<String>();
groupList = new ArrayList<List<String>>();
count = 0;
// 各リストの0番目にはグループ名を入れる。
memberList.add("group" + number);
// 拡張for分で出席者数分ループさせる。
for (String name : attendList) {
count++;
memberList.add(name);
// グループ人数とcountが等しくなったらgroupListに追加して初期化。
if (count == memberCount) {
number++;
groupList.add(memberList);
memberList = new ArrayList<String>();
memberList.add("group" + number);
count = 0;
}
}
//memberListが保持している値がグループ名のみの時にListを削除
if (memberList.size() <= 1) {
memberList.clear();
} else {
// 端数分をgroupListに追加
groupList.add(memberList);
}
}
// カスタマイズしたadapterでlistViewと紐づける。
GroupAdapter adapter = new GroupAdapter(this, R.layout.list_item,
groupList);
listView.setAdapter(adapter);
}
// グループ分けメソッド
private void createGroup() {
for (int i = 0; i < groupCount; i++) {
List<String> memberList = new ArrayList<String>();
memberList.add("group" + (i + 1));
for (int j = 0; j < memberCount; j++) {
memberList.add(attendList.get(count));
count++;
}
groupList.add(memberList);
}
if (remainder != 0 && count != attendList.size()) {
int difference = count;
for (int i = 0; i < attendList.size() - difference; i++) {
groupList.get(i).add(attendList.get(count));
count++;
}
}
}
}
|
/*
* Created on 09/12/2008
*
*/
package com.citibank.ods.modules.client.er.functionality;
import com.citibank.ods.common.functionality.BaseFnc;
import com.citibank.ods.common.functionality.ODSHistoryDetailFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.modules.client.er.functionality.valueobject.ERHistoryDetailFncVO;
/**
* @author lfabiano
* @since 09/12/2008
*/
public class ERHistoryDetailFnc extends BaseERDetailFnc implements
ODSHistoryDetailFnc
{
/* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSHistoryDetailFnc#loadForConsult(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void loadForConsult(BaseFncVO fncVO_) {
}
} |
package com.apap.igd.service;
import java.util.List;
import com.apap.igd.model.JenisPenangananModel;
import com.apap.igd.model.KebutuhanObatModel;
import com.apap.igd.model.rest.ObatModel;
public interface KebutuhanObatService {
void addListKebutuhanObat(List<KebutuhanObatModel> listKebutuhanObat, JenisPenangananModel jenisPenanganan);
KebutuhanObatModel getKebutuhanObatById(long idKebutuhanObat);
KebutuhanObatModel getKebutuhanObatByJenisPenanganan(JenisPenangananModel jenisPenanganan);
String getNamaObat(long idKebutuhanObat);
List<ObatModel> getListObatModel(List<KebutuhanObatModel> listKebutuhanObat);
long totalHargaObat(JenisPenangananModel jenisPenanganan);
List<ObatModel> listObatTidakCukup(List<KebutuhanObatModel> listKebutuhanObat);
} |
package com.dxt2.listviewandgw;
import android.content.Context;
import android.provider.ContactsContract;
import com.dxt2.listviewandgw.bean.DataResult;
import com.dxt2.listviewandgw.bean.Product;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2018/4/19 0019.
*/
public class Parser {
public static List<Product> getCateProductList(Context context) {
//获取raw,通过文件六的方式,再通过引用的Gson解析
InputStream is = context.getResources().openRawResource(R.raw.food_json);
try {
byte[] buffer = new byte[is.available()];
is.read(buffer);
String json = new String(buffer, "utf-8");
DataResult dataResult = new Gson().fromJson(json, DataResult.class);
List<Product> products = new ArrayList<>();
//通过遍历,为了更好的操作,把产品类型和产品类型下的商品进行合并,
// 此处是为了adapter更好的去操作
//把每一个商品实体里都标注商品类型和类型编号
for (int i = 0; i < dataResult.getResults().size(); i++) {
for (int j = 0; j < dataResult.getResults().get(i).getFoodList().size(); j++) {
DataResult.ResultsBean.FoodListBean food = dataResult.getResults().get(i).getFoodList().get(j);
Product item = new Product();
item.setID(food.getID());
item.setTitle(dataResult.getResults().get(i).getTitle());
item.setFoodName(food.getFoodName());
item.setFoodPrice(food.getFoodPrice());
item.setSalesCount(food.getSalesCount());
item.setImageUrl(food.getImageUrl());
item.setSeleteId(i);
products.add(item);
}
}
return products;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package com.example.demo.controller;
import com.example.demo.BrowserImitator;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@Api(tags = {"API для пользователей"}, description = "Получении информации о пользователях")
@RequestMapping("/api/users")
public class UserController {
@Autowired
UserDao userDao;
@Autowired
BrowserImitator browserImitator;
@Value("${python.url}") String pythonUrl;
@GetMapping
@ApiOperation(value = "Запрос всех пользователей")
public List<User> getAllUsers() {
return userDao.findAll();
}
@PostMapping
@ApiOperation(value = "Добавление пользователя")
public void addUser(@RequestBody User user) {
// userDao.save(user);
userDao.findById(user.getId()).orElseGet(() -> userDao.save(user)); // вызывыем только если не нашли
}
@GetMapping("/{id}")
@ApiOperation(value = "Получение пользователя")
public User getUser(@PathVariable int id) {
return userDao.findById(id).orElse(null);
// return userDao.findUserById(id);
}
@PutMapping("/{id}")
@ApiOperation(value = "Изменение пользователя")
public void updateUser(@PathVariable int id, @RequestBody User user) {
userDao.save(user);
}
@GetMapping("/name/{name}")
@ApiOperation(value = "Поиск пользователей по имени")
public List<User> getUsersByName(@PathVariable String name) {
return userDao.findByName(name);
}
@GetMapping("/surname/{surname}")
@ApiOperation(value = "Поиск пользователей по фамилии")
public List<User> getUsersBySurname(@PathVariable String surname) {
return userDao.findBySurnameMy(surname);
}
@GetMapping("/request/{name}")
@ApiOperation(value = "Поиск пользователей по имени")
public User makePythonRequest(@PathVariable String name) {
return browserImitator.get(pythonUrl + name, User.class, userDao.findById(1).orElse(null)).orElse(new User());
}
}
|
package controlador;
import Juego.DragonAlgoBall;
import javafx.event.EventHandler;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import modelo.Posicion;
import vista.*;
import modelo.excepciones.CasilleroVacio;
import modelo.excepciones.PosicionInvalida;
import modelo.turnos.Turno;
public class SeleccionarPersonajeHandler implements EventHandler<MouseEvent> {
private Turno turno;
private CanvasTablero canvas;
private ContenedorPrincipal contenedor;
private DragonAlgoBall juego;
public SeleccionarPersonajeHandler(DragonAlgoBall juego, ContenedorPrincipal contenedor) {
this.juego = juego;
this.contenedor = contenedor;
this.canvas = this.contenedor.getTablero();
this.turno = this.juego.getTurnoActual();
}
@Override
public void handle(MouseEvent t) {
GraphicsContext context = canvas.getGraphicsContext2D();
context.setLineWidth(5);;
context.setStroke(Color.RED);
try {
int coorX = ((int)(t.getX()/ValoresGraficos.tamanioCasillero))+1;
int coorY = Math.abs(((int)(t.getY()/ValoresGraficos.tamanioCasillero))-10);
turno.seleccionarPersonaje(new Posicion(coorX,coorY));
canvas.dibujarTablero();
context.strokeRect(((int)(t.getX()/ValoresGraficos.tamanioCasillero))*ValoresGraficos.tamanioCasillero, ((int)(t.getY()/ValoresGraficos.tamanioCasillero))*ValoresGraficos.tamanioCasillero, ValoresGraficos.tamanioCasillero, ValoresGraficos.tamanioCasillero);
this.contenedor.actualizarBotones(turno);
Label etiqueta = new Label();
etiqueta.setText(turno.getPersonajeSeleccionado().getNombre() + " seleccinado");
etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14));
etiqueta.setTextFill(Color.WHITE);
this.contenedor.actualizarConsola(etiqueta);
}
catch (PosicionInvalida e) {
Label etiqueta = new Label();
etiqueta.setText("Seleccione una posicion de tu equipo");
etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14));
etiqueta.setTextFill(Color.WHITE);
this.contenedor.actualizarConsola(etiqueta);
}
catch(CasilleroVacio e){
Label etiqueta = new Label();
etiqueta.setText("Seleccione una posicion de tu equipo");
etiqueta.setFont(Font.font("courier new", FontWeight.SEMI_BOLD, 14));
etiqueta.setTextFill(Color.WHITE);
this.contenedor.actualizarConsola(etiqueta);
}
}
}
|
package com.orengesunshine.todowithapi.component;
import android.app.Activity;
import com.orengesunshine.todowithapi.CreateActivity;
import com.orengesunshine.todowithapi.LoginActivity;
import com.orengesunshine.todowithapi.RegisterActivity;
import com.orengesunshine.todowithapi.TaskListActivity;
import com.orengesunshine.todowithapi.modules.TaskActivityModule;
import com.orengesunshine.todowithapi.scope.ActivityScope;
import com.orengesunshine.todowithapi.service.TodoClient;
import dagger.Component;
@ActivityScope
@Component(modules = {TaskActivityModule.class},dependencies = AppComponent.class)
public interface ActivityComponent {
void injectActivity(RegisterActivity activity);
void injectLoginActivity(LoginActivity activity);
void injectCreateActivity(CreateActivity activity);
void injectTaskActivity(TaskListActivity activity);
// TodoClient getTodoClient();
}
|
package com.inobu.mquestioner;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.inobu.mquestionair.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
//import android.view.Menu;
//import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HalamanUtama extends Activity {
Button butInput, butViewData, butGPS;
TextView txcektime, txnama;
TextView txrandom;
int cNara = 0;
int cLahan = 0;
String txNara = "";
String txLahan = "";
//String namaUser = null;
final Context context = this;
UserFunctions userFunctions = new UserFunctions();
DbHelper db = new DbHelper(this);
Boolean isInternetPresent = false;
ConnectionDetector cd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.halaman_utama);
txnama = (TextView) findViewById(R.id.txUser);
txrandom = (TextView) findViewById(R.id.txRandom);
txrandom.setText(String.valueOf(db.getRandom(99999,00000)));
cd = new ConnectionDetector(getApplicationContext());
// Bundle extras = getIntent().getExtras();
// if (extras != null) {
// namaUser = getIntent().getExtras().getString("nama");
txnama.setText(db.getUser());
// }
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
getCurrentDate();
butInput = (Button) findViewById(R.id.btInputData);
butInput.setOnClickListener(inputdataClick);
butViewData = (Button) findViewById(R.id.btViewData);
txcektime = (TextView) findViewById(R.id.cektime);
butViewData.setOnClickListener(viewdataClick);
cekTime();
} else {
Intent login = new Intent(getApplicationContext(), login.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
finish();
}
}
Button.OnClickListener inputdataClick = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, set.mquestioner.SetDesa.class);
startActivity(intent);
}
};
Button.OnClickListener viewdataClick = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context,
list.mquestioner.ListNarasumber.class);
startActivity(intent);
}
};
void getCurrentDate() {
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
System.out.println(formattedDate);
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06
// 16:00:22
}
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(getApplicationContext(), setting.class);
startActivity(intent);
break;
case R.id.logout:
userFunctions.logoutUser(getApplicationContext());
Intent in = new Intent(getApplicationContext(), login.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
break;
}
return false;
}
public void cekTime() {
String currentDateTime = DateFormat.getDateTimeInstance().format(
new Date());
txcektime.setText(currentDateTime);
cNara = db.cekSentNarasumber();
if (cNara > 0) {
txNara = "Data narasumber belum upload";
}
cLahan = db.cekSentLahan();
if (cLahan > 0) {
txLahan = "Data lahan belum upload";
}
txcektime.setText(txNara + "\n" + txLahan);
}
}
|
package org.bellatrix.services;
import org.bellatrix.data.MemberAccounts;
public class LoadAccountsByIDResponse {
private MemberAccounts accounts;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public MemberAccounts getAccounts() {
return accounts;
}
public void setAccounts(MemberAccounts accounts) {
this.accounts = accounts;
}
}
|
package com.nsimat.lil.sbet.mybootingweb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MybootingWebApplicationTests {
@Test
void contextLoads() {
}
}
|
package com.kinsella.people.integration.data.repository;
import com.kinsella.people.data.entity.Address;
import com.kinsella.people.data.entity.Person;
import com.kinsella.people.data.repository.AddressRepository;
import com.kinsella.people.data.repository.PersonRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
public class AddressRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private AddressRepository addressRepository;
@Autowired
private PersonRepository personRepository;
@Test
public void testFindByIdReturnsAddressAndAssociatedPerson() {
Person testPerson = new Person(1,"Test", "Person");
entityManager.persist(testPerson);
entityManager.flush();
Address testAddress= new Address(1,testPerson,"Test", "Test", "Test", "Test");
entityManager.persist(testAddress);
entityManager.flush();
Optional<Address> testInDatabase = addressRepository.findById(testAddress.getAddressId());
assertThat(testInDatabase.isPresent()).isEqualTo(true);
assertThat(testInDatabase.get().getPerson().equals(testPerson));
}
@Test
public void testDeletingAddressDoesNotDeletePerson() {
Person testPerson = new Person(1,"Test", "Person");
entityManager.persist(testPerson);
entityManager.flush();
Address testAddress= new Address(1,testPerson,"Test", "Test", "Test", "Test");
entityManager.persist(testAddress);
entityManager.flush();
Optional<Person> testPersonInDatabase = personRepository.findById(testPerson.getPersonId());
Optional<Address> testAddressInDatabase = addressRepository.findById(testAddress.getAddressId());
assertThat(testPersonInDatabase.isPresent()).isEqualTo(true);
assertThat(testAddressInDatabase.isPresent()).isEqualTo(true);
addressRepository.delete(testAddress);
entityManager.flush();
Optional<Person> testPersonStillInDatabase = personRepository.findById(testPerson.getPersonId());
Optional<Address> testAddressNotInDatabase = addressRepository.findById(testAddress.getAddressId());
assertThat(testPersonStillInDatabase.isPresent()).isEqualTo(true);
assertThat(testAddressNotInDatabase.isPresent()).isEqualTo(false);
}
}
|
package by.orion.onlinertasks.presentation.profile.details.pages.information.mappers;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.List;
import by.orion.onlinertasks.R;
import by.orion.onlinertasks.common.GenericObjectMapper;
import by.orion.onlinertasks.data.models.regions.Region;
public class ProfileExecutorLocationToProfileDetailsInformationLocation implements GenericObjectMapper<List<Region>, String> {
@NonNull
private final Context context;
@NonNull
private final List<Integer> executorRegionList;
public ProfileExecutorLocationToProfileDetailsInformationLocation(@NonNull Context context, @NonNull List<Integer> executorRegionList) {
this.context = context;
this.executorRegionList = executorRegionList;
}
@NonNull
@Override
public String map(@NonNull List<Region> regions) {
if (regions.size() == executorRegionList.size()) {
return context.getString(R.string.msg_profile_details_information_work_all_location);
}
StringBuilder builder = new StringBuilder();
builder.append(context.getString(R.string.msg_profile_details_information_work_in));
for (Region region : regions) {
if (!hasRegion(region.id())) {
continue;
}
builder.append(" ")
.append(region.name())
.append(", ");
}
builder.delete(builder.length() - 2, builder.length());
return builder.toString();
}
private boolean hasRegion(@NonNull final Integer id) {
for (Integer regId : executorRegionList) {
if (regId.equals(id)) {
return true;
}
}
return false;
}
}
|
package com.example.projet_pm.presentation.controler;
import android.content.SharedPreferences;
import android.widget.Toast;
import com.example.projet_pm.Constants;
import com.example.projet_pm.Singletons;
import com.example.projet_pm.presentation.modele.Match;
import com.example.projet_pm.presentation.vue.MainActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainController {
private SharedPreferences sharedPreferences;
private Gson gson;
private MainActivity view;
public MainController(MainActivity mainActivity, Gson gson, SharedPreferences sharedPreferences) {
this.view = mainActivity;
this.gson = gson;
this.sharedPreferences = sharedPreferences;
}
public void onStart() {
ArrayList<Match> matchList = getDataFromCache();
if(matchList != null) {
view.showList(matchList);
} else {
makeApiCall();
}
}
private void makeApiCall() {
Call<ArrayList<Match>> call = Singletons.getMatchAPI().getMatch();
call.enqueue(new Callback<ArrayList<Match>>() {
@Override
public void onResponse(Call<ArrayList<Match>> call, Response<ArrayList<Match>> response) {
if(response.isSuccessful() && response.body() != null) {
ArrayList<Match> match = response.body();
saveList(match);
view.showList(match);
}
else {
view.showError();
}
}
@Override
public void onFailure(Call<ArrayList<Match>> call, Throwable t) {
view.showError();
}
});
}
private void saveList(ArrayList<Match> match) {
String jsonString = gson.toJson(match);
sharedPreferences
.edit()
.putString(Constants.KEY_MATCH_LIST, jsonString)
.apply();
Toast.makeText(view.getApplicationContext(), "List Saved", Toast.LENGTH_SHORT).show();
}
private ArrayList<Match> getDataFromCache() {
String jsonMatch = sharedPreferences.getString(Constants.KEY_MATCH_LIST, null);
if(jsonMatch == null) {
return null;
} else {
Type listType = new TypeToken<ArrayList<Match>>(){}.getType();
return gson.fromJson(jsonMatch, listType);
}
}
public void onItemClick(Match match) {
view.navigateToDetails(match);
}
public void onButtonAClick() {
}
public void onButtonBClick() {
}
}
|
package MethodsEncapsulation;
/**
* Created by RXC8414 on 5/22/2017.
*/
public class NestedConditionals {
private int month;
private boolean isLeapYear = true;
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
daysInTheMonth(month);
}
private void daysInTheMonth(int month){
String strMessage;
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month == 12){
strMessage = "This is a 31 days month.";
}
// This is the portion that we have a nested conditional
else if (month == 2){
if(isLeapYear) {
strMessage = " This is a 29 days month.";
}
else{
strMessage = " This is a 28 days month.";
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11){
strMessage = "This is a 30 days month.";
}
else{
strMessage = "This is an invalid month.";
}
System.out.println(strMessage);
}
}
|
package com.zhanwei.java.thread;
public class JoinTest {
private static volatile int i = 0;
public static void main(String[] args) {
Thread thread1 = new Thread(new testThread());
thread1.start();
try {
thread1.join();//下面执行代码的线程必须等待 thread1线程的加入,即等待thread1线程执行完run方法,才继续执行下面的代码
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
static class testThread implements Runnable{
public void run() {
for( i=0;i<10000;i++){};
}
}
}
|
package services;
import java.util.Collection;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import repositories.BannerRepository;
import domain.Administrator;
import domain.Banner;
@Service
@Transactional
public class BannerService {
// Managed repository -----------------------------------------------------
@Autowired
private BannerRepository bannerRepository;
// Supporting services ----------------------------------------------------
@Autowired
private AdministratorService administratorService;
// Constructors -----------------------------------------------------------
public BannerService() {
super();
}
// Simple CRUD methods ----------------------------------------------------
public Banner findOne(final int bannerId) {
Assert.isTrue(bannerId != 0);
Banner result;
result = this.bannerRepository.findOne(bannerId);
return result;
}
public Collection<Banner> findAll() {
Collection<Banner> result;
result = this.bannerRepository.findAll();
return result;
}
public Banner create() {
Banner result;
Administrator administrator;
administrator = this.administratorService.findByPrincipal();
Assert.notNull(administrator);
result = new Banner();
return result;
}
public Banner save(Banner banner) {
Assert.notNull(banner);
Administrator administrator;
administrator = this.administratorService.findByPrincipal();
Assert.notNull(administrator);
banner = this.bannerRepository.save(banner);
return banner;
}
public void delete(final Banner banner) {
Administrator administrator;
administrator = this.administratorService.findByPrincipal();
Assert.notNull(administrator);
this.bannerRepository.delete(banner);
}
// Other business methods -------------------------------------------------
public Banner findRandom() {
final Collection<Banner> collectionBanners;
Banner[] banners;
Banner result;
collectionBanners = this.findAll();
if (!collectionBanners.isEmpty()) {
Random randomGenerator;
randomGenerator = new Random();
banners = collectionBanners.toArray(new Banner[collectionBanners.size()]);
result = banners[randomGenerator.nextInt(collectionBanners.size())];
} else
result = null;
return result;
}
}
|
package com.junzhao.base.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.junzhao.shanfen.R;
/**
* Created by Administrator on 2017/9/11.
* 可以显示全部内容或者部分内容,有全部、收起的效果
*/
public class AllTextView extends LinearLayout implements View.OnClickListener {
TextView tv_content;
TextView tv_allContent;
TextView tv_all;
private int length;
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
tv_content.setOnClickListener(l);
tv_allContent.setOnClickListener(l);
super.setOnClickListener(l);
}
public AllTextView(Context context) {
super(context);
initView(null);
}
public AllTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView(attrs);
}
public AllTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(attrs);
}
private void initView(AttributeSet attr) {
setOrientation(LinearLayout.VERTICAL);
LayoutInflater.from(getContext()).inflate(R.layout.textview_all,this,true);
tv_content = findViewById(R.id.tv_content1);
tv_allContent = findViewById(R.id.tv_allContent1);
tv_all = findViewById(R.id.tv_all1);
tv_content.setMovementMethod(LinkMovementMethod.getInstance());
tv_allContent.setMovementMethod(LinkMovementMethod.getInstance());
tv_all.setMovementMethod(LinkMovementMethod.getInstance());
TypedArray array = getContext().obtainStyledAttributes(attr,R.styleable.AllTextView);
length = array.getInt(R.styleable.AllTextView_text_length,66);
float textSize = array.getDimension(R.styleable.AllTextView_textSize, 14);
int color = array.getColor(R.styleable.AllTextView_textColor, Color.parseColor("#393737"));
array.recycle();
setTextSize(textSize);
setTextColor(color);
tv_all.setOnClickListener(this);
}
public void setTextSize(float textSize) {
// tv_content.setTextSize(textSize);
// tv_allContent.setTextSize(textSize);
// tv_all.setTextSize(textSize);
}
public void setTextColor(int color) {
tv_allContent.setTextColor(color);
tv_content.setTextColor(color);
}
public void setText(String text){
if(TextUtils.isEmpty(text)){
setVisibility(GONE);
return;
}
tv_allContent.setText(text);
tv_all.setText("全部");
if(text.length() > length){
tv_all.setVisibility(VISIBLE);
tv_content.setText(text.substring(0,length));
tv_content.setVisibility(VISIBLE);
tv_allContent.setVisibility(GONE);
setVisibility(VISIBLE);
}else{
tv_all.setVisibility(GONE);
tv_content.setVisibility(VISIBLE);
tv_content.setText(text);
tv_allContent.setVisibility(GONE);
setVisibility(VISIBLE);
}
}
public void setText(SpannableStringBuilder text){
if(TextUtils.isEmpty(text)){
setVisibility(GONE);
return;
}
tv_allContent.setText(text);
tv_all.setText("全部");
if(text.length() > length){
tv_all.setVisibility(VISIBLE);
tv_content.setText(text.toString().substring(0,length));
tv_content.setVisibility(VISIBLE);
tv_allContent.setVisibility(GONE);
setVisibility(VISIBLE);
}else{
tv_all.setVisibility(GONE);
tv_content.setVisibility(VISIBLE);
tv_content.setText(text);
tv_allContent.setVisibility(GONE);
setVisibility(VISIBLE);
}
}
public void setTextLength(int length){
this.length = length;
}
public String getText(){
return tv_allContent.getText().toString();
}
public void onClick(View view){
String text = ((TextView) view).getText().toString().trim();
if(text.equals("全部")){
tv_allContent.setVisibility(VISIBLE);
tv_content.setVisibility(GONE);
((TextView) view).setText("收起");
}else{
tv_allContent.setVisibility(GONE);
tv_content.setVisibility(VISIBLE);
((TextView) view).setText("全部");
}
}
}
|
package cl.cafeines.web.menu.demo.DAO;
import cl.cafeines.web.menu.demo.model.Option;
import cl.cafeines.web.menu.demo.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface ProductDAO extends JpaRepository<Product, Integer> {
@Query("select P from Product P where P.idCategory=?1")
List<Product> getCategoryProducts(Integer idCategory);
@Query("select O from Option O where O.idProduct=?1")
List<Option> getProductOptions(Integer idProduct);
}
|
package com.metoo.foundation.service;
import java.util.List;
import java.util.Map;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.query.support.IQueryObject;
import com.metoo.foundation.domain.Point;
public interface IPointService {
public boolean save(Point point);
public Point getObjById(Long id);
public boolean update(Point point);
public boolean delete(Long id);
IPageList list(IQueryObject properties);
public List<Point> query(String query, Map params, int begin, int max);
}
|
package com.example.controller;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;
import java.util.Currency;
/**
* Created by bartek on 2017-03-07.
*/
@RestController
@RequestMapping("/web")
public class DemoApplicationController {
@RequestMapping("/hello")
public String helloWorld()
{
return "Hello World!";
}
@RequestMapping("/currency/{value}/{multiplier}")
public String calculateCurrency(@PathVariable String value,
@PathVariable String multiplier,
@RequestParam("from") String from,
@RequestParam("to") String to)
{
Long valueLong, multiplierLong;
try {
valueLong = Long.parseLong(value);
multiplierLong = Long.parseLong(multiplier);
Currency.getInstance(from);
Currency.getInstance(to);
} catch (IllegalArgumentException e)
{
throw new RuntimeException("Something went wrong :c");
}
return value + " " + from + " = " + valueLong*multiplierLong + " " + to;
}
}
|
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashSet;
public class Game extends JPanel implements Runnable, KeyListener, ActionListener {
public Thread thread;
private boolean running;
public Sprite ufo;
public Sprite badguyone;
//public Timer t=new Timer(30000,this);
public Timer t=new Timer(20000,this);
public Sprite badguytwo;
public Sprite playbackground;
public Sprite vrgoggles;
public Sprite heartone;
public Sprite hearttwo;
public Sprite heartthree;
public Sprite startscreenbackground;
public Sprite vrgogglesbig=new Sprite("/resources/vrgogglesbig.png",0,0);
public Sprite bigheartcodeday=new Sprite("/resources/bigheart_codeday.png",0,0);
private boolean codedayheart=false;
public Sprite codeday;
private HashSet<Character> keystrokes;
private int badguyvelocity=1;
private BackgroundSound bgsound =new BackgroundSound("/resources/backgroundmusic.wav");
private BackgroundSound playsound =new BackgroundSound("/resources/playmusoc.wav");
@Override
public void actionPerformed(ActionEvent e) {
codedayheart=true;
codeday=new Sprite("/resources/heart_codeday.png",(int)(Math.random()*(740-1+1)),20);
badguyvelocity++;
}
private enum GameState{
START,
PLAYING,
GAME_OVER,
CREDITS,
INSTRUCTIONS
}
GameState state=GameState.START;
private int score;
private FontSprite scorefont;
private int lives=3;
public Game(){
addKeyListener(this);
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
int mousex = (int) e.getX();
int mousey = (int) e.getY();
//g.fill3DRect(300,325,200,75,true);
if (state == GameState.START) {
if (mousex >= 300 && mousex <= 500) {
if (mousey >= 225 && mousey <= 300) {
state = GameState.PLAYING;
playsound.clip.setFramePosition(0);
}
}
if (mousex >= 300 && mousex <= 500) {
if (mousey >= 325 && mousey <= 400) {
//System.exit(0);
state = GameState.CREDITS;
}
}
if (mousex >= 300 && mousex <= 500) {
if (mousey >= 425 && mousey <= 500) {
System.exit(0);
}
}
//g.fill3DRect(700,475,75,75,true);
if (mousex >= 700 && mousex <= 775) {
if (mousey >= 475 && mousey <= 550) {
state=GameState.INSTRUCTIONS;
}
}
}
//g.fill3DRect(20,20,75,75,true);
if (state == GameState.CREDITS) {
if (mousex >= 20 && mousex <= 95) {
if (mousey >= 20 && mousey <= 95) {
state = GameState.START;
}
}
//g.fill3DRect(625,275,50,50,true);
//github.characterimage.paintIcon(this,g,630,280);
// g.drawString("Artist: Aareev Panda", 200,400);
// g.fill3DRect(625,375,50,50,true);
// youtubelogo.characterimage.paintIcon(this,g,630,380);
String os=System.getProperty("os.name").toLowerCase();
Runtime rt = Runtime.getRuntime();
if (mousex >= 625 && mousex <= 675) {
if (mousey >= 275 && mousey <= 325) {
String url = "https://github.com/ShubhamPatilsd";
if(os.indexOf("mac")>=0) {
try {
rt.exec("open " + url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}else if(os.indexOf("win")>=0){
try {
rt.exec("rundll32 url.dll,FileProtocolHandlers "+url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}else if(os.indexOf("nix")>=0 || os.indexOf("nux")>=0){
try {
rt.exec("xdg-open "+url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
if (mousex >= 625 && mousex <= 675) {
if (mousey >= 375 && mousey <= 425) {
String url = "https://www.youtube.com/c/ReevythePanda/featured";
if(os.indexOf("mac")>=0) {
try {
rt.exec("open " + url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}else if(os.indexOf("win")>=0){
try {
rt.exec("rundll32 url.dll,FileProtocolHandlers "+url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}else if(os.indexOf("nix")>=0 || os.indexOf("nux")>=0){
try {
rt.exec("xdg-open "+url);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
}
if (state == GameState.GAME_OVER) {
if (mousex >= 300 && mousex <= 500) {
if (mousey >= 425 && mousey <= 500) {
init();
state=GameState.START;
}
}
}
if(state==GameState.INSTRUCTIONS){
if (mousex >= 20 && mousex <= 95) {
if (mousey >= 20 && mousey <= 95) {
state = GameState.START;
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
setFocusable(true);
keystrokes=new HashSet<Character>();
startscreenbackground=new Sprite("/resources/startscreenbackground.png",0,0);
//playbackground=new Sprite("/resources/playbackground.gif",0,0);
playbackground=new Sprite("/resources/alternate_background.gif",0,0);
ufo=new Sprite("/resources/ufo.gif",400,440);
badguyone=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
badguytwo=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
vrgoggles=new Sprite("/resources/vrgoggles.png",(int)(Math.random()*(740-1+1)+1),20);
thread=new Thread(this);
running=true;
scorefont=new FontSprite("/resources/pixelated.ttf",20,40,36);
heartone=new Sprite("/resources/heart.png",720,15);
hearttwo=new Sprite("/resources/heart.png",680,15);
heartthree=new Sprite("/resources/heart.png",640,15);
codeday=new Sprite("/resources/heart_codeday.png",(int)(Math.random()*(740-1+1)),20);
thread.start();
}
@Override
public void run() {
while(running) {
float f1 = System.currentTimeMillis();
//new Sound().playSound("/resources/gameoversound.wav");
if(state==GameState.PLAYING){
if(lives==0){
playsound.volume=false;
playsound.play();
state=GameState.GAME_OVER;
new Sound().playSound("/resources/gameoversound.wav");
}
if(badguyvelocity>10){
badguyvelocity=10;
}
badguyone.y+=badguyvelocity;
badguytwo.y+=badguyvelocity;
vrgoggles.y++;
badguyone.updateHitBox();
badguytwo.updateHitBox();
vrgoggles.updateHitBox();
ufo.updateHitBox();
if (Sprite.collision(badguyone.hitbox, ufo.hitbox) || Sprite.collision(badguytwo.hitbox, ufo.hitbox)) {
lives--;
playsound.volume=false;
playsound.play();
new Sound().playSound("/resources/pop_3.wav");
playsound.volume=true;
playsound.play();
ufo = new Sprite("/resources/ufo.gif", ufo.y, ufo.y);
badguyone=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
badguytwo=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
}
if (Sprite.collision((vrgoggles.hitbox), ufo.hitbox)) {
score++;
playsound.volume=false;
playsound.play();
new Sound().playSound("/resources/selectcharacter.wav");
playsound.volume=true;
playsound.play();
vrgoggles = new Sprite("/resources/vrgoggles.png", (int) (Math.random() * (740 - 1 + 1) + 1), 20);
}
if (vrgoggles.y >= 440) {
vrgoggles = new Sprite("/resources/vrgoggles.png", (int) (Math.random() * (740 - 1 + 1) + 1), 20);
}
if (badguyone.y >= 440) {
badguyone=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
}
if (badguytwo.y >= 440) {
badguytwo=new Sprite("/resources/rocketbig.gif",(int)(Math.random()*(740-1+1)+1),20);
}
if(codedayheart) {
if(Sprite.collision((codeday.hitbox),ufo.hitbox)){
if(lives<3){
lives++;
new Sound().playSound("/resources/gaininghearts.wav");
codedayheart=false;
ufo=new Sprite("/resources/ufo.gif",ufo.x,ufo.y);
}
}
if (codeday.y >= 440) {
codedayheart=false;
}
codeday.y++;
codeday.updateHitBox();
}
if (!keystrokes.isEmpty()) {
for (char c : keystrokes) {
if (c == 'a') {
ufo.x -= 4;
}
if (c == 'd') {
ufo.x += 4;
}
}
}
if (ufo.x < -30) {
ufo.x = -30;
}
if (ufo.x > 750) {
ufo.x = 750;
}
}
repaint();
float f2=System.currentTimeMillis();
float deltaF=f2-f1;
try{
thread.sleep((1000/60)-(long)deltaF);
}catch(InterruptedException e){
state=GameState.PLAYING;
}
}
}
public void stop() throws InterruptedException {
running = false;
thread.join();
}
@Override
public void paintComponent(Graphics g){
if(state==GameState.START){
bgsound.volume=true;
playsound.volume=false;
playsound.play();
bgsound.play();
startscreenbackground.characterimage.paintIcon(this, g, startscreenbackground.x, startscreenbackground.y);
//Play Button
g.setColor(Color.white);
ufo.characterimage.paintIcon(this, g, 352,25);
g.setFont(new FontSprite("/resources/creditsfont.ttf",0,0,48).font);
g.drawString("Space Catch",185,150);
g.fill3DRect(300,225,200,75,true);
//Play Button Text
g.setFont(scorefont.font);
g.setColor(Color.black);
g.drawString("Play", 370, 270);
g.setColor(Color.white);
g.fill3DRect(300,325,200,75,true);
//Play Button Text
g.setFont(scorefont.font);
g.setColor(Color.black);
g.drawString("Credits", 350, 370);
//Quit
g.setColor(Color.white);
g.fill3DRect(300,425,200,75,true);
//Play Button Text
g.setFont(scorefont.font);
g.setColor(Color.black);
g.drawString("Quit", 370, 470);
g.setColor(Color.white);
g.fill3DRect(700,475,75,75,true);
g.setFont(new FontSprite("/resources/pixelated.ttf",0,0,20).font);
g.setColor(Color.black);
g.drawString("How To", 705, 500);
g.drawString("Play",720,540);
}
if(state==GameState.INSTRUCTIONS){
bgsound.volume=true;
playsound.volume=false;
playsound.play();
bgsound.play();
super.paintComponent(g);
startscreenbackground.characterimage.paintIcon(this, g, startscreenbackground.x, startscreenbackground.y);
g.setColor(Color.black);
g.fillRect(0,0,800,600);
g.setFont(new FontSprite("/resources/creditsfont.ttf",0,0,24).font);
g.setColor(Color.white);
g.drawString("You are a ",175,100);
ufo.characterimage.paintIcon(this,g,400,50);
g.setColor(Color.white);
new Sprite("/resources/rocket.gif",0,0).characterimage.paintIcon(this,g,175,150);
g.drawString("hurts you",250,175);
vrgogglesbig.characterimage.paintIcon(this,g,175,225);
g.setColor(Color.white);
g.drawString("gives you points",275,275);
bigheartcodeday.characterimage.paintIcon(this,g,175,350);
g.setColor(Color.white);
g.drawString("gives you more lives",275,400);
new Sprite("/resources/keyboard.gif",0,0).characterimage.paintIcon(this,g,250,450);
g.drawString("Use",175,475);
g.drawString("To Move Right and Left",350,475);
g.fill3DRect(20,20,75,75,true);
g.setFont(new FontSprite("/resources/pixelated.ttf",0,0,24).font);
g.setColor(Color.black);
g.drawString("Back",35,65);
}
if(state==GameState.GAME_OVER){
playsound.volume=false;
playsound.play();
super.paintComponent(g);
playbackground.characterimage.paintIcon(this, g, playbackground.x, playbackground.y);
g.setColor(Color.white);
g.setFont(new FontSprite("/resources/pixelated.ttf",200,300,70).font);
g.drawString("Game Over",250,200);
g.setFont(scorefont.font);
g.drawString("Score: " + score, scorefont.x, scorefont.y);
g.setColor(Color.white);
g.fill3DRect(300,425,200,75,true);
g.setFont(scorefont.font);
g.setColor(Color.black);
g.drawString("Main Menu",320,470);
}
if(state==GameState.CREDITS){
bgsound.volume=true;
playsound.volume=false;
playsound.play();
bgsound.play();
super.paintComponent(g);
startscreenbackground.characterimage.paintIcon(this, g, startscreenbackground.x, startscreenbackground.y);
g.setColor(Color.black);
g.fillRect(150,200,500,210);
g.setColor(Color.white);
g.setFont(new FontSprite("/resources/creditsfont.ttf",0,0,24).font);
g.drawString("Programmer: Shubham Patil", 125,300);
g.fill3DRect(625,275,50,50,true);
Sprite github=new Sprite("/resources/github_logo.png",0,0);
Sprite youtubelogo=new Sprite("/resources/youtubelogo.png",0,0);
github.characterimage.paintIcon(this,g,630,280);
g.drawString("Artist: Aareev Panda", 200,400);
g.fill3DRect(625,375,50,50,true);
youtubelogo.characterimage.paintIcon(this,g,630,380);
g.setColor(Color.white);
g.fill3DRect(20,20,75,75,true);
//Play Button Text
g.setFont(new FontSprite("/resources/pixelated.ttf",0,0,24).font);
g.setColor(Color.black);
g.drawString("Back",35,65);
}
if(state==GameState.PLAYING) {
playsound.volume=true;
t.start();
bgsound.volume=false;
bgsound.play();
playsound.play();
super.paintComponent(g);
playbackground.characterimage.paintIcon(this, g, playbackground.x, playbackground.y);
ufo.characterimage.paintIcon(this, g, ufo.x, ufo.y);
badguyone.characterimage.paintIcon(this, g, badguyone.x, badguyone.y);
badguytwo.characterimage.paintIcon(this, g, badguytwo.x, badguytwo.y);
vrgoggles.characterimage.paintIcon(this, g, vrgoggles.x, vrgoggles.y);
if(codedayheart==true){
codeday.characterimage.paintIcon(this,g,codeday.x,codeday.y);
}
if (lives == 3) {
heartone.characterimage.paintIcon(this, g, heartone.x, heartone.y);
hearttwo.characterimage.paintIcon(this, g, hearttwo.x, hearttwo.y);
heartthree.characterimage.paintIcon(this, g, heartthree.x, heartthree.y);
}
if (lives == 2) {
heartone.characterimage.paintIcon(this, g, heartone.x, heartone.y);
hearttwo.characterimage.paintIcon(this, g, hearttwo.x, hearttwo.y);
}
if (lives == 1) {
heartone.characterimage.paintIcon(this, g, heartone.x, heartone.y);
}
g.setFont(scorefont.font);
g.setColor(Color.white);
g.drawString("Score: " + score, scorefont.x, scorefont.y);
}
}
@Override
public void keyTyped(KeyEvent e) {
keystrokes.add(e.getKeyChar());
}
@Override
public void keyPressed(KeyEvent e) {
keystrokes.add(e.getKeyChar());
}
@Override
public void keyReleased(KeyEvent e) {
keystrokes.remove(e.getKeyChar());
}
public void init(){
t.restart();
score=0;
lives=3;
codedayheart=false;
badguyvelocity=1;
}
}
|
package gromcode.main.lesson33.homework33_1;
import java.io.FileNotFoundException;
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
//Solution.writeToFileFromConsole("C:/Users/Zhenya Shepel/Documents/IDEA Projects/Java_Courses/test1.txt");
Solution.writeToFileFromConsole("C:\\Users\\Asus_1\\IdeaProjects\\files\\1.txt");
}
}
|
package com.coffee;
public class Test2 {
public void prt()
{
System.out.println("prt!!");
}
}
|
package com.amodtech.meshdisplayclient;
import android.app.Application;
public class MeshDisplayApplictaion extends Application {
/*
* This class reprsents the MeshDisplayApplictaion
*/
private MeshDisplayClientEngine meshDispEngine;
public void onCreate() {
//Instantiate the meshDisplayEngine
this.meshDispEngine = new MeshDisplayClientEngine(this.getApplicationContext());
}
public MeshDisplayClientEngine getAppMeshDisplayEngine() {
//This method returns the application MeshDisplayEngine
return this.meshDispEngine;
}
}
|
package com.mabang.android.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.mabang.android.R;
import com.mabang.android.entity.vo.BillboardInfo;
import java.util.List;
/**
* Created by Walke.Z on 2017/4/28.
*/
public class XlistAutoAdapter extends BaseAdapter {
private List<BillboardInfo> datas;
public XlistAutoAdapter(List<BillboardInfo> datas) {
this.datas = datas;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
XListViewHolder holder=null;
if (convertView==null){
convertView=LayoutInflater.from(parent.getContext()).inflate(R.layout.lv_ad_preselect_item,parent,false);
holder=new XListViewHolder(convertView);
convertView.setTag(holder);
}else {
holder= (XListViewHolder) convertView.getTag();
}
BillboardInfo billboardInfo = datas.get(position);
holder.tvText.setText(billboardInfo.getLongAddress()+"");
holder.ivSelect.setImageResource(R.mipmap.ad_preselect_no);//先默认不选中
if (billboardInfo.isSelected()){
holder.ivSelect.setImageResource(R.mipmap.ad_preselect_yes);
}
return convertView;
}
private class XListViewHolder {
private final ImageView ivSelect,ivArrow;
private final TextView tvText;
public XListViewHolder(View view) {
ivSelect = ((ImageView) view.findViewById(R.id.lapi_ivSelect));
ivArrow = ((ImageView) view.findViewById(R.id.lapi_ivArrow));
tvText = ((TextView) view.findViewById(R.id.lapi_tvText));
}
}
public void addAll(List<BillboardInfo> list){
datas.addAll(list);
notifyDataSetChanged();
}
public void changeAll(List<BillboardInfo> list){
if (datas!=null){
datas.clear();
}
datas.addAll(list);
notifyDataSetChanged();
}
}
|
package imageasgraph;
/**
* Represents a Graph of Pixels, used alongside interface to require package-specific methods - in
* this case, to set the first pixel of the graph.
*/
public abstract class AbstractGraphOfPixels implements GraphOfPixels {
/**
* If this graph is of size 0, 0, then initializes the first node to be the given one.
*
* @param n The node to be the first node, must be non-empty
*/
abstract void addFirstNode(Node.AbstractNode n) throws IllegalArgumentException;
}
|
package receiver;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestPressePapiers {
private static PressePapiers pp;
@BeforeClass
static public void initTest() {
pp = new PressePapiers();
}
@Test
public void testAccesseurs() {
String s = "Bulles carrées";
pp.setContenu(s);
assertEquals(s, pp.getContenu());
}
}
|
package org.apache.hadoop.hdfs.server.namenode.persistance.storage.clusterj;
import com.mysql.clusterj.Query;
import com.mysql.clusterj.Session;
import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;
import com.mysql.clusterj.query.QueryBuilder;
import com.mysql.clusterj.query.QueryDomainType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.hadoop.hdfs.server.blockmanagement.InvalidatedBlock;
import org.apache.hadoop.hdfs.server.namenode.persistance.data_access.entity.InvalidateBlockDataAccess;
import org.apache.hadoop.hdfs.server.namenode.persistance.storage.StorageException;
import org.apache.hadoop.hdfs.server.namenode.persistance.storage.mysqlserver.CountHelper;
/**
*
* @author Hooman <hooman@sics.se>
*/
public class InvalidatedBlockClusterj extends InvalidateBlockDataAccess {
@PersistenceCapable(table = TABLE_NAME)
public interface InvalidateBlocksDTO {
@PrimaryKey
@Column(name = STORAGE_ID)
String getStorageId();
void setStorageId(String storageId);
@PrimaryKey
@Column(name = BLOCK_ID)
long getBlockId();
void setBlockId(long storageId);
@Column(name = GENERATION_STAMP)
long getGenerationStamp();
void setGenerationStamp(long generationStamp);
@Column(name = NUM_BYTES)
long getNumBytes();
void setNumBytes(long numBytes);
}
private ClusterjConnector connector = ClusterjConnector.INSTANCE;
@Override
public int countAll() throws StorageException {
return CountHelper.countAll(TABLE_NAME);
}
@Override
public List<InvalidatedBlock> findAllInvalidatedBlocks() throws StorageException {
try {
Session session = connector.obtainSession();
QueryBuilder qb = session.getQueryBuilder();
QueryDomainType qdt = qb.createQueryDefinition(InvalidateBlocksDTO.class);
return createList(session.createQuery(qdt).getResultList());
} catch (Exception e) {
throw new StorageException(e);
}
}
@Override
public List<InvalidatedBlock> findInvalidatedBlockByStorageId(String storageId) throws StorageException {
try {
Session session = connector.obtainSession();
QueryBuilder qb = session.getQueryBuilder();
QueryDomainType<InvalidateBlocksDTO> qdt = qb.createQueryDefinition(InvalidateBlocksDTO.class);
qdt.where(qdt.get("storageId").equal(qdt.param("param")));
Query<InvalidateBlocksDTO> query = session.createQuery(qdt);
query.setParameter("param", storageId);
return createList(query.getResultList());
} catch (Exception e) {
throw new StorageException(e);
}
}
@Override
public Collection<InvalidatedBlock> findInvalidatedBlocksByBlockId(long bid) throws StorageException {
try {
Session session = connector.obtainSession();
QueryBuilder qb = session.getQueryBuilder();
QueryDomainType<InvalidateBlocksDTO> qdt = qb.createQueryDefinition(InvalidateBlocksDTO.class);
qdt.where(qdt.get("blockId").equal(qdt.param("param")));
Query<InvalidateBlocksDTO> query = session.createQuery(qdt);
query.setParameter("param", bid);
return createList(query.getResultList());
} catch (Exception e) {
throw new StorageException(e);
}
}
@Override
public InvalidatedBlock findInvBlockByPkey(Object[] params) throws StorageException {
try {
Session session = connector.obtainSession();
InvalidateBlocksDTO invTable = session.find(InvalidateBlocksDTO.class, params);
if (invTable == null) {
return null;
}
return createReplica(invTable);
} catch (Exception e) {
throw new StorageException(e);
}
}
@Override
public void prepare(Collection<InvalidatedBlock> removed, Collection<InvalidatedBlock> newed, Collection<InvalidatedBlock> modified) throws StorageException {
try {
Session session = connector.obtainSession();
for (InvalidatedBlock invBlock : newed) {
InvalidateBlocksDTO newInstance = session.newInstance(InvalidateBlocksDTO.class);
createPersistable(invBlock, newInstance);
session.savePersistent(newInstance);
}
for (InvalidatedBlock invBlock : removed) {
Object[] pk = new Object[2];
pk[0] = invBlock.getBlockId();
pk[1] = invBlock.getStorageId();
session.deletePersistent(InvalidateBlocksDTO.class, pk);
}
} catch (Exception e) {
throw new StorageException(e);
}
}
private List<InvalidatedBlock> createList(List<InvalidateBlocksDTO> dtoList) {
List<InvalidatedBlock> list = new ArrayList<InvalidatedBlock>();
for (InvalidateBlocksDTO dto : dtoList) {
list.add(createReplica(dto));
}
return list;
}
private InvalidatedBlock createReplica(InvalidateBlocksDTO invBlockTable) {
return new InvalidatedBlock(invBlockTable.getStorageId(), invBlockTable.getBlockId(),
invBlockTable.getGenerationStamp(), invBlockTable.getNumBytes());
}
private void createPersistable(InvalidatedBlock invBlock, InvalidateBlocksDTO newInvTable) {
newInvTable.setBlockId(invBlock.getBlockId());
newInvTable.setStorageId(invBlock.getStorageId());
newInvTable.setGenerationStamp(invBlock.getGenerationStamp());
newInvTable.setNumBytes(invBlock.getNumBytes());
}
}
|
package com.awssdt.function;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class PostDataFunctionHandler implements RequestHandler<Object, Object> {
@Override
public Object handleRequest(Object apigwInput, Context context) {
return null;
}
} |
package GUI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CardReader extends HardwareElement implements InputDevice {
String CardID = null;
InputStream is = null;
BufferedReader br = null;
public CardReader(String naam) {
super(naam);
br = new BufferedReader(new InputStreamReader(System.in)); //setup to get input from console
// TODO Auto-generated constructor stub
}
public String getInput() {
System.out.println("To simulate inserting card, enter card number");
try{
String cardNr = br.readLine(); //read line and return it
return cardNr;
}
catch(IOException e){
return null;
}
}
}
|
package vape.springmvc.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vape.springmvc.entity.ProductosNuevos;
import vape.springmvc.dao.ProductosNuevosDAO;
@Service
public class ProductosNuevosServiceImpl implements ProductosNuevosService {
@Autowired
private ProductosNuevosDAO productosNuevosDAO;
@Override
@Transactional
public List < ProductosNuevos > getProductosNuevos() {
return productosNuevosDAO.getProductosNuevos();
}
@Override
@Transactional
public void deleteProductosNuevos(int id) {
productosNuevosDAO.deleteProductosNuevos(id);
}
}
|
package software.sham.sftp;
import org.apache.commons.io.FileUtils;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.command.ScpCommandFactory;
import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.sham.ssh.MockSshServer;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
public class MockSftpServer extends MockSshServer {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private Path baseDirectory;
public MockSftpServer(int port) throws IOException {
this(port, false);
}
private MockSftpServer(int port, boolean enableShell) throws IOException {
super(port, false);
initSftp();
if (enableShell) {
enableShell();
}
start();
}
private void initSftp() {
sshServer.setCommandFactory(new ScpCommandFactory());
sshServer.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
}
public Path getBaseDirectory() {
return baseDirectory;
}
@Override
public void start() throws IOException {
baseDirectory = Files.createTempDirectory("sftproot");
sshServer.setFileSystemFactory(new VirtualFileSystemFactory(baseDirectory.toAbsolutePath().toString()));
super.start();
}
@Override
public void stop() throws IOException {
super.stop();
FileUtils.deleteQuietly(baseDirectory.toFile());
}
public static MockSftpServer createWithShell(int port) throws IOException {
return new MockSftpServer(port, true);
}
}
|
import java.util.Stack;
class Solution1 implements Solution {
@Override
public int numIslands(char[][] grid) {
int nr = grid.length;
if (nr == 0) {
return 0;
}
int nc = grid[0].length;
int[] visit = new int[nr*nc];
int count = 0;
for (int i = 0; i < nr*nc; i++) {
if (visit[i] == 0 && grid[i/nc][i%nc] == '1') {
count++;
Stack<Integer> stack = new Stack<>();
stack.push(i);
while (!stack.isEmpty()) {
int curr = stack.pop();
visit[curr] = 1;
if (curr > nc && visit[curr-nc] == 0 && grid[(curr-nc)/nc][(curr-nc)%nc] == '1') {
stack.push(curr-nc);
}
if (curr+nc < nr*nc && visit[curr+nc] == 0 && grid[(curr+nc)/nc][(curr+nc)%nc] == '1') {
stack.push(curr+nc);
}
if (curr%nc != 0 && visit[curr-1] == 0 && grid[(curr-1)/nc][(curr-1)%nc] == '1') {
stack.push(curr-1);
}
if (curr%nc != nc-1 && visit[curr+1] == 0 && grid[(curr+1)/nc][(curr+1)%nc] == '1') {
stack.push(curr+1);
}
}
} else if (visit[i] == 0) {
visit[i] = 1;
}
}
return count;
}
} |
package com.penglai.haima.utils;
import android.content.Context;
import android.view.View;
/**
* 作者:flyjiang
* 说明: 用于处理View的测量等
*/
public class ViewUtil {
/**
* 根据手机的分辨率从dp的单位转成为px(像素)
*
* @param context 上下文
* @param dpValue 需要转换的DP值
* @return 转换后的DP值
*/
public static float dip2px(final Context context, float dpValue) {
return context == null ? dpValue : (dpValue * context.getResources().getDisplayMetrics().density);
}
/**
* 根据手机的分辨率从px(像素)的单位转成为dp
*
* @param context 上下文
* @param pxValue 需要转换的PX值
* @return 转换后的PX值
*/
public static float px2dip(final Context context, float pxValue) {
return context == null || pxValue == 0 ? pxValue : (pxValue / context.getResources().getDisplayMetrics().density);
}
/**
* 根据手机的分辨率从sp的单位转成为px(像素)
*
* @param context 上下文
* @param spValue 需要转换的SP值
* @return 转换后的PX值
*/
public static float sp2px(final Context context, float spValue) {
return context == null ? spValue : spValue * context.getResources().getDisplayMetrics().density;
}
/**
* 描述:根据手机的分辨率从px(像素)的单位转成为sp
*
* @param context 上下文
* @param pxValue 需要转换的PX值
* @return 转换后的SP值
*/
public static float px2sp(final Context context, float pxValue) {
return context == null || pxValue == 0 ? pxValue : pxValue / context.getResources().getDisplayMetrics().density;
}
/**
* 测量view宽度
*
* @param view 需要测量的View
* @return View的宽度
*/
public static int measureVieWidth(View view) {
if (view == null) {
return 0;
}
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(width, height);
return view.getMeasuredWidth();
}
/**
* 测量view高度
*
* @param view 需要测量的View
* @return View的高度
*/
public static int measureViewHeight(View view) {
if (view == null) {
return 0;
}
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(width, height);
return view.getMeasuredHeight();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.