text
stringlengths 10
2.72M
|
|---|
package com.example.demo.controller;
import com.example.demo.service.AppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AppHomeController {
@Autowired
private AppService appService;
@GetMapping(value = "/home")
public String appHome(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
Model model){
model.addAttribute("apps", appService.getAppList(pageNo, pageSize));
System.out.println(appService.getAppList(pageNo, pageSize));
return "AppHome";
}
@ResponseBody
@GetMapping(value = "/home2")
public String appHome2(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
Model model){
model.addAttribute("apps", appService.getAppList(pageNo, pageSize));
System.out.println(appService.getAppList(pageNo, pageSize));
return "AppHome";
}
}
|
package com.box.androidsdk.content.models;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import com.box.androidsdk.content.BoxApiUser;
import com.box.androidsdk.content.BoxConfig;
import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.BoxFutureTask;
import com.box.androidsdk.content.auth.BoxAuthentication;
import com.box.androidsdk.content.requests.BoxRequest;
import com.box.androidsdk.content.utils.BoxLogUtils;
import com.box.androidsdk.content.utils.SdkUtils;
import com.box.androidsdk.content.utils.StringMappedThreadPoolExecutor;
import com.box.sdk.android.R;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* A BoxSession is responsible for maintaining the mapping between user and authentication tokens
*/
public class BoxSession extends BoxObject implements BoxAuthentication.AuthListener {
private static final long serialVersionUID = 8122900496609434013L;
private static final transient ThreadPoolExecutor AUTH_CREATION_EXECUTOR = SdkUtils.createDefaultThreadPoolExecutor(1, 20, 3600, TimeUnit.SECONDS);
private String mUserAgent = "com.box.sdk.android" + "/" + BoxConfig.SDK_VERSION;
private transient Context mApplicationContext = BoxConfig.APPLICATION_CONTEXT;
private transient BoxAuthentication.AuthListener sessionAuthListener;
private String mUserId;
protected String mClientId;
protected String mClientSecret;
protected String mClientRedirectUrl;
protected BoxAuthentication.BoxAuthenticationInfo mAuthInfo;
protected String mDeviceId;
protected String mDeviceName;
protected BoxMDMData mMDMData;
protected Long mExpiresAt;
protected String mAccountEmail;
private boolean mSuppressAuthErrorUIAfterLogin = false;
/**
* Optional refresh provider.
*/
protected BoxAuthentication.AuthenticationRefreshProvider mRefreshProvider;
protected boolean mEnableBoxAppAuthentication = BoxConfig.ENABLE_BOX_APP_AUTHENTICATION;
private transient WeakReference<BoxFutureTask<BoxSession>> mRefreshTask;
/**
* When using this constructor, if a user has previously been logged in/stored or there is only one user, this user will be authenticated.
* If no user or multiple users have been stored without knowledge of the last one authenticated, ui will be shown to handle the scenario similar
* to BoxSession(null, context).
*
* @param context current context.
*/
public BoxSession(Context context) {
this(context, getBestStoredUserId(context));
}
/**
* @return the user id associated with the only logged in user. If no user is logged in or multiple users are logged in returns null.
*/
private static String getBestStoredUserId(final Context context) {
String lastAuthenticatedUserId = BoxAuthentication.getInstance().getLastAuthenticatedUserId(context);
Map<String, BoxAuthentication.BoxAuthenticationInfo> authInfoMap = BoxAuthentication.getInstance().getStoredAuthInfo(context);
if (authInfoMap != null) {
if (!SdkUtils.isEmptyString(lastAuthenticatedUserId) && authInfoMap.get(lastAuthenticatedUserId) != null) {
return lastAuthenticatedUserId;
}
if (authInfoMap.size() == 1) {
for (String authUserId : authInfoMap.keySet()) {
return authUserId;
}
}
}
return null;
}
/**
* When setting the userId to null ui will be shown to ask which user to authenticate as if at least one user is logged in. If no
* user has been stored will show login ui. If logging in as a valid user id no ui will be displayed.
*
* @param userId user id to login as or null to login a new user.
* @param context current context.
*/
public BoxSession(Context context, String userId) {
this(context, userId, BoxConfig.CLIENT_ID, BoxConfig.CLIENT_SECRET, BoxConfig.REDIRECT_URL);
if (!SdkUtils.isEmptyString(BoxConfig.DEVICE_NAME)){
setDeviceName(BoxConfig.DEVICE_NAME);
}
if (!SdkUtils.isEmptyString(BoxConfig.DEVICE_ID)){
setDeviceName(BoxConfig.DEVICE_ID);
}
}
/**
* Create a BoxSession using a specific box clientId, secret, and redirectUrl. This constructor is not necessary unless
* an application uses multiple api keys.
* Note: When setting the userId to null ui will be shown to ask which user to authenticate as if at least one user is logged in. If no
* user has been stored will show login ui.
*
* @param context current context.
* @param clientId the developer's client id to access the box api.
* @param clientSecret the developer's secret used to interpret the response coming from Box.
* @param redirectUrl the developer's redirect url to use for authenticating via Box.
* @param userId user id to login as or null to login as a new user.
*/
public BoxSession(Context context, String userId, String clientId, String clientSecret, String redirectUrl) {
mClientId = clientId;
mClientSecret = clientSecret;
mClientRedirectUrl = redirectUrl;
if (getRefreshProvider() == null && (SdkUtils.isEmptyString(mClientId) || SdkUtils.isEmptyString(mClientSecret))) {
throw new RuntimeException("Session must have a valid client id and client secret specified.");
}
mApplicationContext = context.getApplicationContext();
if (!SdkUtils.isEmptyString(userId)) {
mAuthInfo = BoxAuthentication.getInstance().getAuthInfo(userId, context);
mUserId = userId;
}
if (mAuthInfo == null) {
mUserId = userId;
mAuthInfo = new BoxAuthentication.BoxAuthenticationInfo();
}
mAuthInfo.setClientId(mClientId);
setupSession();
}
/**
* Construct a new box session object based off of an existing session.
*
* @param session session to use as the base.
*/
protected BoxSession(BoxSession session) {
this.mApplicationContext = session.mApplicationContext;
if (!SdkUtils.isBlank(session.getUserId())){
setUserId(session.getUserId());
}
if (!SdkUtils.isBlank(session.getDeviceId())){
setDeviceId(session.getDeviceId());
}
if (!SdkUtils.isBlank(session.getDeviceName())){
setDeviceName(session.getDeviceName());
}
if (!SdkUtils.isBlank(session.getBoxAccountEmail())){
setBoxAccountEmail(session.getBoxAccountEmail());
}
if (session.getManagementData() != null){
setManagementData(session.getManagementData());
}
if (!SdkUtils.isBlank(session.getClientId())){
mClientId = session.mClientId;
}
if (!SdkUtils.isBlank(session.getClientSecret())){
mClientSecret = session.getClientSecret();
}
if (!SdkUtils.isBlank(session.getRedirectUrl())){
mClientRedirectUrl = session.getRedirectUrl();
}
setAuthInfo(session.getAuthInfo());
setupSession();
}
/**
* This is an advanced constructor that can be used when implementing an authentication flow that differs from the default oauth 2 flow.
*
* @param context current context.
* @param authInfo authentication information that should be used. (Must at the minimum provide an access token).
* @param refreshProvider the refresh provider to use when the access token expires and needs to be refreshed.
* @param <E> an instanceof of a refresh provider that is serializable.
*/
public <E extends BoxAuthentication.AuthenticationRefreshProvider & Serializable> BoxSession(Context context, BoxAuthentication.BoxAuthenticationInfo authInfo, E refreshProvider) {
mApplicationContext = context.getApplicationContext();
setAuthInfo(authInfo);
mRefreshProvider = refreshProvider;
setupSession();
}
protected void setAuthInfo(BoxAuthentication.BoxAuthenticationInfo authInfo) {
if (authInfo == null) {
mAuthInfo = new BoxAuthentication.BoxAuthenticationInfo();
mAuthInfo.setClientId(mClientId);
}
else {
mAuthInfo = authInfo;
}
if (mAuthInfo.getUser() != null && !SdkUtils.isBlank(mAuthInfo.getUser().getId())) {
setUserId(mAuthInfo.getUser().getId());
}
else {
setUserId(null);
}
}
/**
* This is a convenience constructor. It is the equivalent of calling BoxSession(context, authInfo, refreshProvider) and creating an authInfo with just
* an accessToken.
*
* @param context current context
* @param accessToken a valid accessToken.
* @param refreshProvider the refresh provider to use when the access token expires and needs to refreshed.
* @param <E> an instanceof of a refresh provider that is serializable.
*/
public <E extends BoxAuthentication.AuthenticationRefreshProvider & Serializable> BoxSession(Context context, String accessToken, E refreshProvider) {
this(context, createSimpleBoxAuthenticationInfo(accessToken), refreshProvider);
}
private static BoxAuthentication.BoxAuthenticationInfo createSimpleBoxAuthenticationInfo(final String accessToken) {
BoxAuthentication.BoxAuthenticationInfo info = new BoxAuthentication.BoxAuthenticationInfo();
info.setAccessToken(accessToken);
return info;
}
/**
* Sets whether or not Box App authentication is enabled or not.
*
* @param enabled true if the session should try to authenticate via the Box application, false otherwise.
*/
public void setEnableBoxAppAuthentication(boolean enabled) {
mEnableBoxAppAuthentication = enabled;
}
/**
* @return true if authentication via the Box App is enabled (this is by default), false otherwise.
*/
public boolean isEnabledBoxAppAuthentication() {
return mEnableBoxAppAuthentication;
}
/**
* Set the application context if this session loses it for instance when this object is deserialized.
* @param context current context
*/
public void setApplicationContext(final Context context){
mApplicationContext = context.getApplicationContext();
}
/**
* @return the application context used to construct this session.
*/
public Context getApplicationContext() {
return mApplicationContext;
}
/**
* @param listener listener to notify when authentication events (authentication, refreshing, and their exceptions) occur.
*/
public void setSessionAuthListener(BoxAuthentication.AuthListener listener) {
this.sessionAuthListener = listener;
}
protected void setupSession() {
// Because BuildConfig.DEBUG is always false when library projects publish their release variants we use ApplicationInfo
boolean isDebug = false;
try {
if (mApplicationContext != null && mApplicationContext.getPackageManager() != null) {
if (BoxConfig.APPLICATION_CONTEXT == null) {
BoxConfig.APPLICATION_CONTEXT = mApplicationContext;
}
PackageInfo info = mApplicationContext.getPackageManager().getPackageInfo(mApplicationContext.getPackageName(), 0);
isDebug = ((info.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}
} catch (PackageManager.NameNotFoundException e) {
// Do nothing -- debug mode will default to false
}
BoxConfig.IS_DEBUG = isDebug;
BoxAuthentication.getInstance().addListener(this);
}
/**
* @return the user associated with this session. May return null if this is a new session before authentication.
*/
public BoxUser getUser() {
return mAuthInfo.getUser();
}
/**
* @return the user id associated with this session. This can be null if the session was created without a user id and has
* not been authenticated.
*/
public String getUserId() {
return mUserId;
}
protected void setUserId(String userId) {
mUserId = userId;
}
/**
* @return the auth information associated with this session.
*/
public BoxAuthentication.BoxAuthenticationInfo getAuthInfo() {
return mAuthInfo;
}
/**
* @return the custom refresh provider associated with this session. returns null if one is not set.
*/
public BoxAuthentication.AuthenticationRefreshProvider getRefreshProvider() {
if (mRefreshProvider != null) {
return mRefreshProvider;
} else {
return BoxAuthentication.getInstance().getRefreshProvider();
}
}
/**
* @param deviceId the optional unique ID of this device. Used for applications that want to support device-pinning.
*/
public void setDeviceId(final String deviceId){
mDeviceId = deviceId;
}
/**
* @return the device id associated with this session. returns null if one is not set.
*/
public String getDeviceId(){
return mDeviceId;
}
/**
*
* @param deviceName the optional human readable name for this device.
*/
public void setDeviceName(final String deviceName){
mDeviceName = deviceName;
}
/**
* @return the device name associated with this session. returns null if one is not set.
*/
public String getDeviceName(){
return mDeviceName;
}
/**
* @return the user agent to use for network requests with this session.
*/
public String getUserAgent() {
return mUserAgent;
}
/**
* @param mdmData MDM data object that should be used to authenticate this session if required.
*/
public void setManagementData(final BoxMDMData mdmData){
mMDMData = mdmData;
}
/**
* @return mdm data if set.
*/
public BoxMDMData getManagementData(){
return mMDMData;
}
/**
* @param expiresAt (optional) set the time as a unix time stamp in seconds when the refresh token should expire. Must be less than the default 60 days if used.
*/
public void setRefreshTokenExpiresAt(final long expiresAt){
mExpiresAt = expiresAt;
}
/**
* @return the unix time stamp at which refresh token should expire if set, returns null if not set.
*/
public Long getRefreshTokenExpiresAt(){
return mExpiresAt;
}
/**
* @param accountName (optional) set email account to prefill into authentication ui if available.
*/
public void setBoxAccountEmail(final String accountName){
mAccountEmail = accountName;
}
/**
* @return Box Account email if set.
*/
public String getBoxAccountEmail(){
return mAccountEmail;
}
private String mLastAuthCreationTaskId;
/**
* Use authenticate(context) instead.
* @return a box future task (already submitted to an executor) that starts the process of authenticating this user.
* The task can be used to block until the user has completed authentication through whatever ui is necessary(using task.get()).
*/
@Deprecated
public BoxFutureTask<BoxSession> authenticate() {
return authenticate(getApplicationContext());
}
/**
*
* @param context The current context.
* @return a box future task (already submitted to an executor) that starts the process of authenticating this user.
* The task can be used to block until the user has completed authentication through whatever ui is necessary(using task.get()).
*/
public BoxFutureTask<BoxSession> authenticate(final Context context) {
return authenticate(context, null);
}
/**
*
* @param context The current context.
* @param onCompleteListener A listener to get notified when this authenticate task finishes
* @return a box future task (already submitted to an executor) that starts the process of authenticating this user.
* The task can be used to block until the user has completed authentication through whatever ui is necessary(using task.get()).
*/
public BoxFutureTask<BoxSession> authenticate(final Context context, BoxFutureTask.OnCompletedListener<BoxSession> onCompleteListener) {
if (context != null){
mApplicationContext = context.getApplicationContext();
BoxConfig.APPLICATION_CONTEXT = mApplicationContext;
}
if (!SdkUtils.isBlank(mLastAuthCreationTaskId) && AUTH_CREATION_EXECUTOR instanceof StringMappedThreadPoolExecutor){
Runnable runnable = ((StringMappedThreadPoolExecutor) AUTH_CREATION_EXECUTOR).getTaskFor(mLastAuthCreationTaskId);
if (runnable instanceof BoxSessionAuthCreationRequest.BoxAuthCreationTask){
BoxSessionAuthCreationRequest.BoxAuthCreationTask task = ((BoxSessionAuthCreationRequest.BoxAuthCreationTask) runnable);
if(onCompleteListener != null) {
task.addOnCompletedListener(onCompleteListener);
}
task.bringUiToFrontIfNecessary();
return task;
}
}
BoxSessionAuthCreationRequest req = new BoxSessionAuthCreationRequest(this, mEnableBoxAppAuthentication);
BoxFutureTask<BoxSession> task = req.toTask();
if(onCompleteListener != null) {
task.addOnCompletedListener(onCompleteListener);
}
mLastAuthCreationTaskId = task.toString();
AUTH_CREATION_EXECUTOR.execute(task);
return task;
}
/**
* Logout the currently authenticated user.
*
* @return a task that can be used to block until the user associated with this session has been logged out.
*/
public BoxFutureTask<BoxSession> logout() {
final BoxFutureTask<BoxSession> task = (new BoxSessionLogoutRequest(this)).toTask();
new Thread(){
@Override
public void run() {
task.run();
}
}.start();
return task;
}
/**
* Refresh authentication information associated with this session.
*
* @return a task that can be used to block until the information associated with this session has been refreshed.
*/
public BoxFutureTask<BoxSession> refresh() {
if (mRefreshTask != null && mRefreshTask.get() != null){
BoxFutureTask<BoxSession> lastRefreshTask = mRefreshTask.get();
if (!(lastRefreshTask.isCancelled() || lastRefreshTask.isDone())){
return lastRefreshTask;
}
}
final BoxFutureTask<BoxSession> task = (new BoxSessionRefreshRequest(this)).toTask();
new Thread(){
@Override
public void run() {
task.run();
}
}.start();
mRefreshTask = new WeakReference<BoxFutureTask<BoxSession>>(task);
return task;
}
/**
* When set, the content sdk will not show activities/fragments requiring user input,
* for e.g. when a BoxSessionRefreshRequest fails, or specific authentication errors
* happen while sending requests using this session.
* @param suppress true if error ui should be supressed, false otherwise.
*/
public void suppressAuthErrorUIAfterLogin(boolean suppress) {
mSuppressAuthErrorUIAfterLogin = suppress;
}
public boolean suppressesAuthErrorUIAfterLogin() {
return mSuppressAuthErrorUIAfterLogin;
}
/**
* This function gives you the cache location associated with this session. It is
* preferred to use this method when setting up the location of your cache as it ensures
* that all data will be cleared upon logout.
* @return directory associated with the user associated with this session.
*/
public File getCacheDir() {
return new File(getApplicationContext().getFilesDir(), getUserId());
}
/**
* This clears the contents of the directory provided in {@link #getCacheDir()}.
*/
public void clearCache() {
File cacheDir = getCacheDir();
if (cacheDir.exists()) {
File[] files = cacheDir.listFiles();
if (files != null) {
for (File child : files) {
deleteFilesRecursively(child);
}
}
}
}
private void deleteFilesRecursively(File fileOrDirectory) {
if (fileOrDirectory != null) {
if (fileOrDirectory.isDirectory()) {
File[] files = fileOrDirectory.listFiles();
if (files != null) {
for (File child : files) {
deleteFilesRecursively(child);
}
}
}
fileOrDirectory.delete();
}
}
/**
* Called when this session has been refreshed with new authentication info.
*
* @param info the latest info from a successful refresh.
*/
@Override
public void onRefreshed(BoxAuthentication.BoxAuthenticationInfo info) {
if (sameUser(info)) {
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mAuthInfo, info);
if (sessionAuthListener != null) {
sessionAuthListener.onRefreshed(info);
}
}
}
/**
* Called when this user has logged in.
*
* @param info the latest info from going through the login flow.
*/
@Override
public void onAuthCreated(BoxAuthentication.BoxAuthenticationInfo info) {
if (sameUser(info) || getUserId() == null) {
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mAuthInfo, info);
if (info.getUser() != null) {
setUserId(info.getUser().getId());
}
if (sessionAuthListener != null) {
sessionAuthListener.onAuthCreated(info);
}
}
}
/**
* Called when a failure occurs trying to authenticate or refresh.
*
* @param info The last authentication information available, before the exception.
* @param ex the exception that occurred.
*/
@Override
public void onAuthFailure(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
if (sameUser(info) || (info == null && getUserId() == null)) {
if (sessionAuthListener != null) {
sessionAuthListener.onAuthFailure(info, ex);
}
if (ex instanceof BoxException) {
BoxException.ErrorType errorType = ((BoxException) ex).getErrorType();
switch (errorType) {
case NETWORK_ERROR:
toastString(mApplicationContext, R.string.boxsdk_error_network_connection);
break;
case IP_BLOCKED:
}
}
}
}
protected void startAuthenticationUI(){
BoxAuthentication.getInstance().startAuthenticationUI(this);
}
private static void toastString(final Context context, final int id) {
SdkUtils.toastSafely(context, id, Toast.LENGTH_LONG);
}
@Override
public void onLoggedOut(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
if (sameUser(info)) {
getAuthInfo().wipeOutAuth();
setUserId(null);
if (sessionAuthListener != null) {
sessionAuthListener.onLoggedOut(info, ex);
}
}
}
/**
* Returns the associated client id. If none is set, the one defined in BoxConfig will be used
*
* @return the client id this session is associated with.
*/
public String getClientId() {
return mClientId;
}
/**
* Returns the associated client secret. Because client secrets are not managed by the SDK, if another
* client id/secret is used aside from the one defined in the BoxConfig
*
* @return the client secret this session is associated with
*/
public String getClientSecret() {
return mClientSecret;
}
/**
* @return the redirect url this session is using. By default comes from BoxConstants.
*/
public String getRedirectUrl() {
return mClientRedirectUrl;
}
private boolean sameUser(BoxAuthentication.BoxAuthenticationInfo info) {
return info != null && info.getUser() != null && getUserId() != null && getUserId().equals(info.getUser().getId());
}
private static class BoxSessionLogoutRequest extends BoxRequest<BoxSession, BoxSessionLogoutRequest> {
private static final long serialVersionUID = 8123965031279971582L;
private BoxSession mSession;
public BoxSessionLogoutRequest(BoxSession session) {
super(null, " ", null);
this.mSession = session;
}
@Override
protected BoxSession onSend() throws BoxException {
synchronized (mSession) {
if (mSession.getUser() != null) {
BoxAuthentication.getInstance().logout(mSession);
mSession.getAuthInfo().wipeOutAuth();
mSession.setUserId(null);
}
}
return mSession;
}
}
private static class BoxSessionRefreshRequest extends BoxRequest<BoxSession, BoxSessionRefreshRequest> {
private static final long serialVersionUID = 8123965031279971587L;
private BoxSession mSession;
public BoxSessionRefreshRequest(BoxSession session) {
super(null, " ", null);
this.mSession = session;
}
@Override
public BoxSession onSend() throws BoxException {
BoxAuthentication.BoxAuthenticationInfo refreshedInfo = null;
try {
// block until this session is finished refreshing.
refreshedInfo = BoxAuthentication.getInstance().refresh(mSession).get();
} catch (Exception e) {
BoxLogUtils.e("BoxSession", "Unable to repair user", e);
Exception rootException = (e.getCause() instanceof BoxException) ? (Exception)e.getCause() : e;
if (rootException instanceof BoxException ) {
if (mSession.mSuppressAuthErrorUIAfterLogin) {
mSession.onAuthFailure(refreshedInfo, rootException);
} else {
if (rootException instanceof BoxException.RefreshFailure && ((BoxException.RefreshFailure) rootException).isErrorFatal()) {
// if the refresh failure is unrecoverable have the user login again.
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_fatal_refresh);
mSession.startAuthenticationUI();
mSession.onAuthFailure(mSession.getAuthInfo(), rootException);
throw (BoxException) rootException;
} else if (((BoxException) e).getErrorType() == BoxException.ErrorType.TERMS_OF_SERVICE_REQUIRED) {
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_terms_of_service);
mSession.startAuthenticationUI();
mSession.onAuthFailure(mSession.getAuthInfo(), rootException);
BoxLogUtils.e("BoxSession", "TOS refresh exception ", rootException);
throw (BoxException) rootException;
} else {
mSession.onAuthFailure(refreshedInfo, rootException);
throw (BoxException) rootException;
}
}
} else {
throw new BoxException("BoxSessionRefreshRequest failed", rootException);
}
}
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mSession.mAuthInfo,
BoxAuthentication.getInstance().getAuthInfo(mSession.getUserId(), mSession.getApplicationContext()));
return mSession;
}
}
private static class BoxSessionAuthCreationRequest extends BoxRequest<BoxSession, BoxSessionAuthCreationRequest> implements BoxAuthentication.AuthListener {
private static final long serialVersionUID = 8123965031279971545L;
private final BoxSession mSession;
private boolean mIsWaitingForLoginUi;
public BoxSessionAuthCreationRequest(BoxSession session, boolean viaBoxApp) {
super(null, " ", null);
this.mSession = session;
}
@Override
public BoxSession onSend() throws BoxException {
synchronized (mSession) {
if (mSession.getUser() == null) {
if ((mSession.getAuthInfo() != null && !SdkUtils.isBlank(mSession.getAuthInfo().accessToken())) && mSession.getUser() == null) {
// if we have an access token, but no user try to repair by making the call to user endpoint.
try {
BoxApiUser apiUser = new BoxApiUser(mSession);
BoxUser user = apiUser.getCurrentUserInfoRequest().setFields(BoxAuthentication.MINIMUM_USER_FIELDS).send();
mSession.setUserId(user.getId());
mSession.getAuthInfo().setUser(user);
// because this is new information we need to let BoxAuthentication know.
BoxAuthentication.getInstance().onAuthenticated(mSession.getAuthInfo(), mSession.getApplicationContext());
return mSession;
} catch (BoxException e) {
BoxLogUtils.e("BoxSession", "Unable to repair user", e);
if (e instanceof BoxException.RefreshFailure && ((BoxException.RefreshFailure) e).isErrorFatal()) {
// if the refresh failure is unrecoverable have the user login again.
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_fatal_refresh);
} else if (e.getErrorType() == BoxException.ErrorType.TERMS_OF_SERVICE_REQUIRED) {
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_terms_of_service);
} else {
mSession.onAuthFailure(null, e);
throw e;
}
}
// at this point we were unable to repair.
}
BoxAuthentication.getInstance().addListener(this);
launchAuthUI();
return mSession;
} else {
BoxAuthentication.BoxAuthenticationInfo info = BoxAuthentication.getInstance().getAuthInfo(mSession.getUserId(), mSession.getApplicationContext());
if (info != null) {
BoxAuthentication.BoxAuthenticationInfo.cloneInfo(mSession.mAuthInfo, info);
if ((SdkUtils.isBlank(mSession.getAuthInfo().accessToken()) && SdkUtils.isBlank(mSession.getAuthInfo().refreshToken()))){
// if we have neither the access token or refresh token then launch auth UI.
BoxAuthentication.getInstance().addListener(this);
launchAuthUI();
} else {
if (info.getUser() == null || SdkUtils.isBlank(info.getUser().getId())){
try {
//TODO: show some ui while requestion user info
BoxApiUser apiUser = new BoxApiUser(mSession);
BoxUser user = apiUser.getCurrentUserInfoRequest().setFields(BoxAuthentication.MINIMUM_USER_FIELDS).send();
mSession.setUserId(user.getId());
mSession.getAuthInfo().setUser(user);
mSession.onAuthCreated(mSession.getAuthInfo());
return mSession;
} catch (BoxException e) {
BoxLogUtils.e("BoxSession", "Unable to repair user", e);
if (e instanceof BoxException.RefreshFailure && ((BoxException.RefreshFailure) e).isErrorFatal()) {
// if the refresh failure is unrecoverable have the user login again.
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_fatal_refresh);
} else if (e.getErrorType() == BoxException.ErrorType.TERMS_OF_SERVICE_REQUIRED) {
toastString(mSession.getApplicationContext(), R.string.boxsdk_error_terms_of_service);
} else {
mSession.onAuthFailure(null, e);
throw e;
}
}
}
mSession.onAuthCreated(mSession.getAuthInfo());
}
} else {
// Fail to get information of current user. current use no longer valid.
mSession.mAuthInfo.setUser(null);
launchAuthUI();
}
}
return mSession;
}
}
private void launchAuthUI() {
synchronized (mSession) {
mIsWaitingForLoginUi = true;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mSession.getRefreshProvider() != null && mSession.getRefreshProvider().launchAuthUi(mSession.getUserId(), mSession)) {
// Do nothing authentication ui will be handled by developer.
} else {
mSession.startAuthenticationUI();
}
}
});
try {
while(mIsWaitingForLoginUi) {
mSession.wait();
}
} catch (InterruptedException e) {
BoxLogUtils.e(getClass().getSimpleName(), "could not launch auth UI");
}
}
}
@Override
public BoxFutureTask<BoxSession> toTask() {
return new BoxAuthCreationTask(BoxSession.class, this);
}
@Override
public void onRefreshed(BoxAuthentication.BoxAuthenticationInfo info) {
// Do not implement, this class itself only handles auth creation, regardless success or not, failure should be handled by caller.
}
@Override
public void onAuthCreated(BoxAuthentication.BoxAuthenticationInfo info) {
// the session's onAuthCreated listener will handle this.
notifyAuthDone();
}
/**
* Method to notify Auth UI caller that the processing is done
*/
private void notifyAuthDone() {
synchronized (mSession) {
mIsWaitingForLoginUi = false;
mSession.notify();
}
}
@Override
public void onAuthFailure(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
// Do not implement, this class itself only handles auth creation, regardless success or not, failure should be handled by caller.
notifyAuthDone();
}
@Override
public void onLoggedOut(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
// Do not implement, this class itself only handles auth creation, regardless success or not, failure should be handled by caller.
}
static class BoxAuthCreationTask extends BoxFutureTask<BoxSession>{
public BoxAuthCreationTask(final Class<BoxSession> clazz, final BoxRequest request) {
super(clazz, request);
}
public void bringUiToFrontIfNecessary(){
if (mRequest instanceof BoxSessionAuthCreationRequest && ((BoxSessionAuthCreationRequest) mRequest).mIsWaitingForLoginUi){
((BoxSessionAuthCreationRequest) mRequest).mSession.startAuthenticationUI();
}
}
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BoxSessionAuthCreationRequest) || !(((BoxSessionAuthCreationRequest) o).mSession.equals(mSession))){
return false;
}
return super.equals(o);
}
@Override
public int hashCode() {
return mSession.hashCode() + super.hashCode();
}
}
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (BoxConfig.APPLICATION_CONTEXT != null){
setApplicationContext(BoxConfig.APPLICATION_CONTEXT);
}
}
}
|
package com.events;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Objects;
/**
* AccessEvent 刷卡访问事件的实体类对象
* */
//@Data
//@AllArgsConstructor
@NoArgsConstructor
public class AccessEvent implements Serializable {
public Integer id;
public Integer door_id;
public String door_status;
public Integer event_type;
public String employee_sys_no;
public String datetime;
public AccessEvent(AccessEvent indoor) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDoor_id() {
return door_id;
}
public void setDoor_id(int door_id) {
this.door_id = door_id;
}
public String getDoor_status() {
return door_status;
}
public void setDoor_status(String door_status) {
this.door_status = door_status;
}
public int getEvent_type() {
return event_type;
}
public void setEvent_type(int event_type) {
this.event_type = event_type;
}
public String getEmployee_sys_no() {
return employee_sys_no;
}
public void setEmployee_sys_no(String employee_sys_no) {
this.employee_sys_no = employee_sys_no;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public AccessEvent(int id, int door_id, String door_status, int event_type, String employee_sys_no, String datetime) {
this.id = id;
this.door_id = door_id;
this.door_status = door_status;
this.event_type = event_type;
this.employee_sys_no = employee_sys_no;
this.datetime = datetime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AccessEvent that = (AccessEvent) o;
return id == that.id &&
door_id == that.door_id &&
door_status == that.door_status &&
event_type == that.event_type &&
employee_sys_no == that.employee_sys_no &&
Objects.equals(datetime, that.datetime);
}
@Override
public int hashCode() {
return Objects.hash(id, door_id, door_status, event_type, employee_sys_no, datetime);
}
@Override
public String toString() {
return "AccessEvent{" +
"id=" + id +
", door_id=" + door_id +
", door_status=" + door_status +
", event_type=" + event_type +
", employee_sys_no=" + employee_sys_no +
", datetime='" + datetime + '\'' +
'}';
}
}
|
public class Game
{
Frame frame;
Panel panel;
public Game()
{
openFrame();
initGame();
start();
}
// Frame functions
private void openFrame()
{
frame = new Frame();
initPanel();
//initPanelSize();
}
// Panel functions
private void initPanel()
{
panel = frame.getPanel();
}
// Game functions
private void initGame()
{
}
private void start()
{
boolean isFinished = false;
while(!isFinished)
{
panel.display();
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
|
/*
* 12 de Mayo de 2020
* Ismael Salas López
* PROYECTO FINAL
* Clase Arrastra
*/
package salas_lopez_ismael_pf;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSource;
import java.awt.Cursor;
import java.awt.dnd.DragSourceEvent;
import java.awt.datatransfer.Transferable;
/**
*
* @author Ismael Salas López ft Stack Overflow
* La verdad es que esta es una clase adaptada que conseguí en Stack Overflow
* debido a que es más complicado usar Drag and Drop en componentes como JPanels o no lo
* implementan por defecto (sin contar con lo malos que son los tutoriales de Oracle para
* explicar sus propios componentes en algunos casos). Si bien, el código podría considrerse copia
* algunas formas en la que se hacen ciertas cosas difieren, si estudia el código del enlace podrá ver por qué.
* Adjunto el enlace al código.
* https://stackoverflow.com/questions/11201734/java-how-to-drag-and-drop-jpanel-with-its-components
* Adaptación de DragGestureHandler
*/
public class Arrastra implements DragGestureListener, DragSourceListener
{
// Referencia a la Pila que implementa la clase Arrastra
private PilaCartas referencia;
// Constructor
public Arrastra( PilaCartas referencia )
{
this.referencia = referencia;
}
/** Obtiene la referencia */
public PilaCartas getPilaCartas()
{
return referencia;
}
/** Registra el evento del arrastre.
* Cuando el usuario selecciona una de las pilas de cartas
* que integren el manejador de eventos e intenta arrastrarlo,
* se ejecuta esta función, que obtiene las cartas que serán movidas
* (el cómo lo hace se explica en la clase PilaCartas) y las empaca
* para ser transferidas.
* @param evento
*/
@Override
public void dragGestureRecognized( DragGestureEvent evento )
{
// Obtiene la pila de cartas que va a mover, lo hace obteniendo
// la referencia de la Pila sobre la que se invocó el evento
// y llamando a su función getSelección()
PilaCartas pilaAEnviar = getPilaCartas().getSeleccion();
// Crea el paquete de cartas que se van a enviar
Transferable paqueteAMover = new PilaTransferible( pilaAEnviar );
// Inicia el proceso de arrastrar
DragSource fuente = evento.getDragSource();
fuente.startDrag( evento, Cursor.getPredefinedCursor( Cursor.MOVE_CURSOR ), paqueteAMover, this );
}
/** Clase de la interfaz no utilizada. */
@Override
public void dragEnter(DragSourceDragEvent evento )
{
}
/** Clase de la interfaz no utilizada. */
@Override
public void dragOver(DragSourceDragEvent evento )
{
}
/** Clase de la interfaz no utilizada. */
@Override
public void dropActionChanged(DragSourceDragEvent evento)
{
}
/** Clase de la interfaz no utilizada. */
@Override
public void dragExit(DragSourceEvent evento )
{
}
/** Se ejecuta una vez que el proceso de arrastrado y soltado termina.
* Verifica si se hizo la transferencia o no para remover las cartas
* que fueron copiadas, además de actualizar las nuevas posiciones y tamaños de
* las pilas.
* También es el momento adecuado para verificar si el usuario ganó o perdió.
*/
@Override
public void dragDropEnd( DragSourceDropEvent evento )
{
// El soltado de los elementos fue exitoso
if( getPilaCartas().getTransferido() ){
// Función polimórfica de pilacartas: Elimina la selección dada
getPilaCartas().removerSeleccion();
}
// Función polimórfica de PilaCartas: reinicia las variables de selección
getPilaCartas().cancelarSeleccion();
// Reinicia la variable tranferido
getPilaCartas().setTransferido( false );
// Actualiza el background (esto porque estuve experimentando
// cosas raras con los backgrounds)
getPilaCartas().setBackground( getPilaCartas().getBackground() );
// Actualiza la pantalla
getPilaCartas().repaint();
// Actualiza las nuevas posiciones y los tamaños de las pilas
Aplicacion.solitario.actualizarPosiciones();
// Revisa si el usuario ganó
Aplicacion.solitario.victoria();
}
}
|
package com.rolandopalermo.facturacion.ec.bo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import javax.xml.bind.JAXBException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rolandopalermo.facturacion.ec.common.exception.VeronicaException;
import com.rolandopalermo.facturacion.ec.common.sri.Firmador;
import com.rolandopalermo.facturacion.ec.dto.comprobantes.ComprobanteDTO;
import com.rolandopalermo.facturacion.ec.dto.comprobantes.FacturaDTO;
import com.rolandopalermo.facturacion.ec.dto.comprobantes.GuiaRemisionDTO;
import com.rolandopalermo.facturacion.ec.dto.comprobantes.RetencionDTO;
import com.rolandopalermo.facturacion.ec.dto.rest.FacturaRequestDTO;
import com.rolandopalermo.facturacion.ec.dto.rest.GuiaRemisionRequestDTO;
import com.rolandopalermo.facturacion.ec.dto.rest.RetencionRequestDTO;
@Service
public class FirmadorBO {
@Autowired
private GeneradorBO generadorBO;
public byte[] firmarFactura(FacturaRequestDTO firmaRequestDTO)
throws VeronicaException, JAXBException, IOException {
if (firmaRequestDTO.getComprobanteAsObj() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsObj(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else if (firmaRequestDTO.getComprobanteAsBase64() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsBase64(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else {
throw new VeronicaException("No es un tipo de documento válido.");
}
}
public byte[] firmarRetencion(RetencionRequestDTO firmaRequestDTO)
throws VeronicaException, JAXBException, IOException {
if (firmaRequestDTO.getComprobanteAsObj() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsObj(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else if (firmaRequestDTO.getComprobanteAsBase64() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsBase64(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else {
throw new VeronicaException("No es un tipo de documento válido.");
}
}
// Firmado
public byte[] firmarGuiaRemision(GuiaRemisionRequestDTO firmaRequestDTO)
throws VeronicaException, JAXBException, IOException {
if (firmaRequestDTO.getComprobanteAsObj() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsObj(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else if (firmaRequestDTO.getComprobanteAsBase64() != null) {
return firnarComprobanteElectronico(firmaRequestDTO.getComprobanteAsBase64(),
firmaRequestDTO.getRutaArchivoPkcs12(), firmaRequestDTO.getClaveArchivopkcs12());
} else {
throw new VeronicaException("No es un tipo de documento válido.");
}
}
byte[] firnarComprobanteElectronico(ComprobanteDTO comprobanteDTO, String rutaCertificado,
String passwordCertificado) throws VeronicaException, JAXBException, IOException {
byte[] contentAsBase64 = new byte[0];
if (comprobanteDTO instanceof FacturaDTO) {
contentAsBase64 = generadorBO.generarXMLFactura((FacturaDTO) comprobanteDTO);
} else if (comprobanteDTO instanceof RetencionDTO) {
contentAsBase64 = generadorBO.generarXMLRetencion((RetencionDTO) comprobanteDTO);
} else if (comprobanteDTO instanceof GuiaRemisionDTO) {
contentAsBase64 = generadorBO.generarGuiaXMLRemison((GuiaRemisionDTO) comprobanteDTO);
} else {
throw new VeronicaException("No es un tipo de documento válido.");
}
return firnarContenido(contentAsBase64, rutaCertificado, passwordCertificado);
}
byte[] firnarComprobanteElectronico(byte[] comprobanteAsBase64, String rutaCertificado, String passwordCertificado)
throws VeronicaException, IOException {
return firnarContenido(comprobanteAsBase64, rutaCertificado, passwordCertificado);
}
private byte[] firnarContenido(byte[] cotenido, String rutaCertificado, String passwordCertificado)
throws IOException, VeronicaException {
// Actividad 1.- Generar archivo temporales para el XML y su respectivo archivo
// firmado
String rutaArchivoXML = UUID.randomUUID().toString();
File temp = File.createTempFile(rutaArchivoXML, ".xml");
rutaArchivoXML = temp.getAbsolutePath();
String rutaArchivoXMLFirmado = UUID.randomUUID().toString();
File tempFirmado = File.createTempFile(rutaArchivoXMLFirmado, ".xml");
rutaArchivoXMLFirmado = tempFirmado.getAbsolutePath();
// Actividad 2.- Guardar datos en archivo xml
try (FileOutputStream fos = new FileOutputStream(rutaArchivoXML)) {
fos.write(cotenido);
}
// Actividad 3.- Firmar el archivo xml creado temporalmente
Firmador firmador = new Firmador(rutaArchivoXML, rutaArchivoXMLFirmado, rutaCertificado, passwordCertificado);
firmador.firmar();
// 4.- Obtener el contenido del archivo XML
Path path = Paths.get(rutaArchivoXMLFirmado);
byte[] data = Files.readAllBytes(path);
if (!temp.delete() || !tempFirmado.delete()) {
throw new VeronicaException("No se pudo eliminar los archivos temporales.");
}
return data;
}
}
|
package com.fang.example.db.store;
/**
* Created by andy on 6/25/16.
*/
public interface BlockView {
}
|
import java.util.ArrayList;
import java.util.List;
public class KidsWithTheGreatestNumberOfCandies {
public static List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
List<Boolean> booleanList = new ArrayList<>();
int length = candies.length;
int highest = 0;
for (int i = 0; i<length; i++){
if (candies[i] > highest){
highest = candies[i];
}
}
for (int i = 0; i<length; i++){
int check = candies[i] +extraCandies;
if (check >= highest ){
booleanList.add(true);
}
else {
booleanList.add(false);
}
}
return booleanList;
}
public static void main(String[] args) {
int arr[] = {12,1,12};
List<Boolean> arrNew= kidsWithCandies(arr,10);
System.out.println(arrNew);
}
}
|
/*
* 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 tugasminggu11;
/**
*
* @author syaifuddin
*/
public class Keledai extends Binatang implements Herbivora{
private String suara, warnaBulu;
public Keledai(String suara, String warnaBulu, String nama, int jmlKaki) {
super(nama, jmlKaki);
this.suara = suara;
this.warnaBulu = warnaBulu;
}
@Override
public void displayMakan() {
System.out.println("Jenis : Herbivora");
System.out.println("Makanan : Tumbuhan");
}
@Override
public void displayBinatang() {
System.out.println("Nama : " + super.getNama());
System.out.println("Jumlah Kaki : " + super.getJmlKaki());
}
public void displayData(){
System.out.println("Suara : " + this.suara);
System.out.println("Warna Bulu : " + this.warnaBulu);
}
}
|
package com.tencent.mm.plugin.wallet_core.id_verify;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class WalletRealNameVerifyUI$4 implements OnMenuItemClickListener {
final /* synthetic */ WalletRealNameVerifyUI pkE;
WalletRealNameVerifyUI$4(WalletRealNameVerifyUI walletRealNameVerifyUI) {
this.pkE = walletRealNameVerifyUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
((a) this.pkE.cDK()).c(this.pkE, 0);
this.pkE.finish();
return true;
}
}
|
package com.jjw.sparkCore.transformations;
import java.util.Arrays;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;
public class Operator_groupByKey {
public static void main(String[] args) {
SparkConf conf = new SparkConf();
conf.setMaster("local").setAppName("groupByKey");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaPairRDD<String, Integer> parallelizePairs = sc.parallelizePairs(Arrays.asList(
new Tuple2<String,Integer>("a", 1),
new Tuple2<String,Integer>("a", 2),
new Tuple2<String,Integer>("b", 3),
new Tuple2<String,Integer>("c", 4),
new Tuple2<String,Integer>("d", 5),
new Tuple2<String,Integer>("d", 6)
));
JavaPairRDD<String, Iterable<Integer>> groupByKey = parallelizePairs.groupByKey();
groupByKey.foreach(new VoidFunction<Tuple2<String,Iterable<Integer>>>() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void call(Tuple2<String, Iterable<Integer>> t) throws Exception {
System.out.println(t);
}
});
}
}
|
/*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.services.store.contracts.precompile.impl;
import static com.hedera.node.app.service.evm.store.contracts.precompile.codec.EvmDecodingFacade.decodeFunctionCall;
import static com.hedera.services.store.contracts.precompile.AbiConstants.ABI_ID_UPDATE_TOKEN_EXPIRY_INFO;
import static com.hedera.services.store.contracts.precompile.AbiConstants.ABI_ID_UPDATE_TOKEN_EXPIRY_INFO_V2;
import static com.hedera.services.store.contracts.precompile.codec.DecodingFacade.convertAddressBytesToTokenID;
import static com.hedera.services.store.contracts.precompile.codec.DecodingFacade.decodeTokenExpiry;
import com.esaulpaugh.headlong.abi.Tuple;
import com.hedera.mirror.web3.evm.properties.MirrorNodeEvmProperties;
import com.hedera.services.store.contracts.precompile.AbiConstants;
import com.hedera.services.store.contracts.precompile.Precompile;
import com.hedera.services.store.contracts.precompile.SyntheticTxnFactory;
import com.hedera.services.store.contracts.precompile.TokenUpdateLogic;
import com.hedera.services.store.contracts.precompile.codec.BodyParams;
import com.hedera.services.store.contracts.precompile.codec.FunctionParam;
import com.hedera.services.store.contracts.precompile.codec.TokenUpdateExpiryInfoWrapper;
import com.hedera.services.store.contracts.precompile.utils.PrecompilePricingUtils;
import com.hedera.services.txns.validation.ContextOptionValidator;
import com.hederahashgraph.api.proto.java.TransactionBody.Builder;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.util.Set;
import java.util.function.UnaryOperator;
import org.apache.tuweni.bytes.Bytes;
/**
* This class is a modified copy of UpdateTokenExpiryInfoPrecompile from hedera-services repo.
*
* Differences with the original:
* 1. Implements a modified {@link Precompile} interface
* 2. Removed class fields and adapted constructors in order to achieve stateless behaviour
* 3. Body method is modified to accept {@link BodyParams} argument in order to achieve stateless behaviour
*/
public class UpdateTokenExpiryInfoPrecompile extends AbstractTokenUpdatePrecompile {
public UpdateTokenExpiryInfoPrecompile(
TokenUpdateLogic tokenUpdateLogic,
MirrorNodeEvmProperties mirrorNodeEvmProperties,
ContextOptionValidator contextOptionValidator,
SyntheticTxnFactory syntheticTxnFactory,
PrecompilePricingUtils precompilePricingUtils) {
super(
tokenUpdateLogic,
mirrorNodeEvmProperties,
contextOptionValidator,
precompilePricingUtils,
syntheticTxnFactory);
}
@Override
public Builder body(Bytes input, UnaryOperator<byte[]> aliasResolver, BodyParams bodyParams) {
final var functionId = ((FunctionParam) bodyParams).functionId();
final var updateExpiryInfoAbi =
switch (functionId) {
case AbiConstants.ABI_ID_UPDATE_TOKEN_EXPIRY_INFO -> SystemContractAbis.UPDATE_TOKEN_EXPIRY_INFO_V1;
case ABI_ID_UPDATE_TOKEN_EXPIRY_INFO_V2 -> SystemContractAbis.UPDATE_TOKEN_EXPIRY_INFO_V2;
default -> throw new IllegalArgumentException("invalid selector to updateExpiryInfo precompile");
};
final var updateExpiryInfoOp = getTokenUpdateExpiryInfoWrapper(input, aliasResolver, updateExpiryInfoAbi);
return syntheticTxnFactory.createTokenUpdateExpiryInfo(updateExpiryInfoOp);
}
@Override
public Set<Integer> getFunctionSelectors() {
return Set.of(ABI_ID_UPDATE_TOKEN_EXPIRY_INFO, ABI_ID_UPDATE_TOKEN_EXPIRY_INFO_V2);
}
public static TokenUpdateExpiryInfoWrapper getTokenUpdateExpiryInfoWrapper(
Bytes input, UnaryOperator<byte[]> aliasResolver, @NonNull final SystemContractAbis abi) {
final Tuple decodedArguments = decodeFunctionCall(input, abi.selector, abi.decoder);
final var tokenID = convertAddressBytesToTokenID(decodedArguments.get(0));
final Tuple tokenExpiryStruct = decodedArguments.get(1);
final var tokenExpiry = decodeTokenExpiry(tokenExpiryStruct, aliasResolver);
return new TokenUpdateExpiryInfoWrapper(tokenID, tokenExpiry);
}
}
|
package techokami.computronics;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import paulscode.sound.SoundBuffer;
import paulscode.sound.SoundSystem;
import techokami.computronics.gui.GuiTapePlayer;
import techokami.computronics.tile.TileTapeDrive;
import techokami.computronics.tile.TileTapeDrive.State;
import techokami.lib.TechoLibMod;
import techokami.lib.audio.DFPWM;
import techokami.lib.audio.StreamingAudioPlayer;
import techokami.lib.network.MessageHandlerBase;
import techokami.lib.network.Packet;
import techokami.lib.util.GuiUtils;
import techokami.lib.util.WorldUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.client.event.sound.PlayStreamingSourceEvent;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
public class NetworkHandlerServer extends MessageHandlerBase {
@Override
public void onMessage(Packet packet, INetHandler handler, EntityPlayer player, int command)
throws IOException {
switch(command) {
case Packets.PACKET_TAPE_GUI_STATE: {
TileEntity entity = packet.readTileEntity();
State state = State.values()[packet.readUnsignedByte()];
if(entity instanceof TileTapeDrive) {
TileTapeDrive tile = (TileTapeDrive)entity;
tile.switchState(state);
}
} break;
}
}
}
|
package edu.iit.cs445.StateParking.UnitTest;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.iit.cs445.StateParking.Objects.*;
public class NullOrderTest {
private Order order = NullOrder.getinstance();
@Test
public void test() {
assertEquals(order.getId(),-1);
assertEquals(order.getOrderDate(),null);
assertEquals(order.getVehicle(), null);
assertEquals(order.getCard(), null);
order.setFee(100.0);
assertTrue(order.getFee() == -1.0);
assertFalse(order.KeywordMatch(""));
assertTrue(order.isNull());
}
}
|
package com.cdeid.pipeline.other;
import gate.Corpus;
import gate.CorpusController;
import gate.Factory;
import gate.Gate;
import gate.util.GateException;
import gate.util.Out;
import gate.util.persistence.PersistenceManager;
import java.io.File;
import java.io.IOException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* mDEID Copyright (C) 2015-16 A. Dehghan
* ChristieDEID Copyright (C) 2016 Christie NHS Foundation Trust
*
* See GATE/pipeline/preProcessing.xgapp
*/
public class PreProcess {
private static CorpusController preProc;
private static Corpus corpus;
public PreProcess()
{
PreProcess.init();
}
public CorpusController getController(){
return preProc;
}
private static void initGate(){
Logger.getRootLogger().setLevel(Level.OFF);
Out.prln("\n ChristieDEID (UK) v0.1, Copyright (C) 2016 The Christie NHS FT");
Out.prln("\n.Initialising pipeline ...");
/*
* init GATE
*/
Gate.setPluginsHome(new File("GATE/"));
Gate.setGateHome(new File("GATE/"));
Gate.runInSandbox(true);
try {
Gate.init();
} catch (GateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void init()
{
initGate();
try {
/*
* Init pre-processing pipeline:
* 1.Tokenizer
* 2.Sentence splitter
*/
String path = "GATE/pipeline/preProcessing.xgapp";
preProc = (CorpusController) PersistenceManager.loadObjectFromFile(new File(path));
corpus = Factory.newCorpus("c1");
preProc.setCorpus(corpus);
} catch (GateException e) {
System.err.println("Pipeline.initGate(): " + e.getMessage());
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
}
Out.prln(".Initialisation completed ...");
}
/**
* Pre-processing pipeline.
*
* @param gateDoc gate.Document
*/
public void preProcessingPipeline(gate.Document gateDoc)
{
try{
corpus.add(gateDoc);
preProc.execute();
} catch (GateException e) {
System.err.println("Pipeline.preProcessingPipeline(...): " + e.getMessage() );
}
//clean(preProc);
PreProcess.corpus.clear();
PreProcess.corpus.cleanup();
PreProcess.preProc.cleanup();
Factory.deleteResource(corpus);
Factory.deleteResource(preProc);
}
}
|
package com.shopify.shipment;
import java.util.Date;
import com.shopify.order.OrderData;
import lombok.Data;
@Data
public class ShipmentSkuData {
private String orderIdx;
private String goodsCode;
private String goods;
private String goodsType;
private String goodsSku;
private int price;
private int unitCost;
private String taxable;
private String barcode;
private String origin;
private String hscode;
private int boxLength;
private int boxWidth;
private int boxHeight;
private String boxUnit;
private int weight;
private String weightUnit;
private Date regDate;
}
|
/**
* @file: com.innovail.trouble.core - GameApplication.java
* @date: Jul 1, 2013
* @author: bweber
*/
package com.innovail.trouble.core;
/**
*
*/
public class GameApplication
{
public static String InternalPathPrefix = "";
public static void setInternalPathPrefix (final String prefix)
{
InternalPathPrefix = prefix;
}
}
|
package pro.eddiecache.ioc.xml;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import pro.eddiecache.ioc.xml.exception.DocumentException;
public class XmlDocumentHolder implements IDocumentHolder
{
private Map<String, Document> docs = new HashMap<String, Document>();
@Override
public Document getDocument(String filePath)
{
Document doc = docs.get(filePath);
if (doc == null)
{
docs.put(filePath, readDocument(filePath));
}
return docs.get(filePath);
}
private Document readDocument(String filePath)
{
try
{
SAXReader reader = new SAXReader(true);
reader.setEntityResolver(new IoCEntityResolver());
File xmlFile = new File(filePath);
Document doc = reader.read(xmlFile);
return doc;
}
catch (Exception e)
{
e.printStackTrace();
throw new DocumentException(e.getMessage());
}
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class LedenShareEmpowers implements Serializable {
private String appId = "";
private String pkId = "";
private String shareType = "";
private String nodeSign = "";
private String deletag = "";
private String annex = "";
private String createUserId = "";
private Date createDatetime;
private String updateUserId = "";
private Date updateDatetime;
private boolean deletag2;
private boolean recive = false; //接收
private boolean issue = false; //分发
private boolean multiple = false; //综合
public boolean isRecive() {
return recive;
}
public void setRecive(boolean recive) {
this.recive = recive;
}
public boolean isIssue() {
return issue;
}
public void setIssue(boolean issue) {
this.issue = issue;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
public boolean isDeletag2() {
return deletag2;
}
public void setDeletag2(boolean deletag2) {
if (deletag2 == false)
setDeletag("1");
else if (deletag2 == true)
setDeletag("0");
this.deletag2 = deletag2;
}
private static final long serialVersionUID = 1L;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getPkId() {
return pkId;
}
public void setPkId(String pkId) {
this.pkId = pkId;
}
public String getShareType() {
return shareType;
}
public void setShareType(String shareType) {
this.shareType = shareType;
}
public String getNodeSign() {
return nodeSign;
}
public void setNodeSign(String nodeSign) {
this.nodeSign = nodeSign;
}
public String getDeletag() {
return deletag;
}
public void setDeletag(String deletag) {
this.deletag = deletag;
}
public String getAnnex() {
return annex;
}
public void setAnnex(String annex) {
this.annex = annex;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getCreateDatetime() {
return createDatetime;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public Date getUpdateDatetime() {
return updateDatetime;
}
public void setCreateDatetime() {
this.createDatetime = new Date();
}
public void setUpdateDatetime() {
this.updateDatetime = new Date();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", appId=").append(appId);
sb.append(", pkId=").append(pkId);
sb.append(", shareType=").append(shareType);
sb.append(", nodeSign=").append(nodeSign);
sb.append(", deletag=").append(deletag);
sb.append(", annex=").append(annex);
sb.append(", createUserId=").append(createUserId);
sb.append(", createDatetime=").append(createDatetime);
sb.append(", updateUserId=").append(updateUserId);
sb.append(", updateDatetime=").append(updateDatetime);
sb.append("]");
return sb.toString();
}
}
|
package br.edu.ifam.saf.api.endpoint;
import org.codehaus.jackson.map.ObjectMapper;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import br.edu.ifam.saf.api.data.ItemRelatorio;
import br.edu.ifam.saf.api.data.ItemRelatorioResponse;
import br.edu.ifam.saf.api.util.MediaType;
@SuppressWarnings("unchecked")
@Stateless
@Path("/relatorios")
public class RelatorioEndpoint {
@PersistenceContext
EntityManager em;
@GET
@Produces(MediaType.APPLICATION_JSON_UTF8)
@Path("/mais_alugados")
public Response maisAlugados() {
Query query = em.createNativeQuery(
"SELECT\n" +
" i.nome AS descricao,\n" +
" count(ia.id) AS total\n" +
"\n" +
"FROM item i\n" +
" JOIN item_aluguel ia ON ia.item_id = i.id\n" +
"GROUP BY i.id");
List<ItemRelatorio> itens = new ArrayList<>();
List<Object[]> results = (List<Object[]>) query.getResultList();
for (Object[] result : results) {
itens.add(new ItemRelatorio(((String) result[0]), ((Number) result[1]).doubleValue()));
}
return Response.ok(new ItemRelatorioResponse(itens)).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON_UTF8)
@Path("/usuario_mais_frequentes")
public Response usuarioMaisFrequentes() {
Query query = em.createNativeQuery(
"SELECT\n" +
" u.nome,\n" +
" count(ia.aluguel_id)\n" +
"FROM item_aluguel ia\n" +
" JOIN aluguel a ON ia.aluguel_id = a.id\n" +
" JOIN usuario u ON a.cliente_id = u.id\n" +
"GROUP BY u.id");
List<ItemRelatorio> itens = new ArrayList<>();
List<Object[]> results = (List<Object[]>) query.getResultList();
for (Object[] result : results) {
itens.add(new ItemRelatorio(((String) result[0]), ((Number) result[1]).doubleValue()));
}
return Response.ok(new ItemRelatorioResponse(itens)).build();
}
@GET
@Produces(MediaType.APPLICATION_JSON_UTF8)
@Path("/media_itens_por_aluguel")
public Response mediaItensPorAluguel() {
Query query = em.createNativeQuery(
"SELECT AVG(c)\n" +
"FROM (SELECT count(ia.item_id) AS c\n" +
" FROM item_aluguel ia\n" +
" GROUP BY ia.aluguel_id) c");
Number media = (Number) query.getSingleResult();
return Response.ok(new ItemRelatorioResponse(new ItemRelatorio("Média", media.doubleValue()))).build();
}
}
|
package net.sourceforge.vrapper.vim.commands;
import java.util.Stack;
import net.sourceforge.vrapper.platform.SearchAndReplaceService;
import net.sourceforge.vrapper.utils.Position;
import net.sourceforge.vrapper.utils.Search;
import net.sourceforge.vrapper.utils.SearchOffset;
import net.sourceforge.vrapper.utils.SearchResult;
import net.sourceforge.vrapper.utils.StartEndTextRange;
import net.sourceforge.vrapper.utils.TextRange;
import net.sourceforge.vrapper.vim.EditorAdaptor;
/**
* The cursor is inside a pair of XML tags. Find the open tag *before* the cursor
* that matches the closing tag *after* the cursor. Note that We don't know which
* open tag name we're looking for until we find the unbalanced closing tag after
* the cursor. This is to handle malformed XML documents with lingering open tags.
* This aligns with how Vim handles things.
*/
public class XmlTagDelimitedText implements DelimitedText {
private TextRange endTag;
/**
* Find the open tag this cursor is inside. To do that,
* we first have to find the closing tag we're inside.
*/
public TextRange leftDelimiter(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException {
if(count == 0) {
count = 1;
}
String tagName;
TextRange openTag = null;
Position startOpenSearch = editorAdaptor.getCursorService().getPosition();
Position startCloseSearch = editorAdaptor.getCursorService().getPosition();
for(int i=0; i < count; i++) {
//find the first unbalanced closing tag after start
endTag = getUnbalancedClosingTag(startCloseSearch, editorAdaptor);
tagName = getClosingTagName(endTag, editorAdaptor);
//find the first unbalanced open tag before start that
//matches the name of the closing tag we found
openTag = getUnbalancedOpenTag(startOpenSearch, tagName, editorAdaptor);
//prepare for next iteration (if any)
//to find the parent open and closing tags to the ones we just found
startOpenSearch = openTag.getLeftBound();
startCloseSearch = endTag.getRightBound();
}
return openTag;
}
/**
* Find the closing tag this cursor is inside.
*/
public TextRange rightDelimiter(EditorAdaptor editorAdaptor, int count) throws CommandExecutionException {
if(count == 0) {
count = 1;
}
if(endTag != null && count == 1) {
//if someone already ran leftDelimiter(), just re-use that tag
return endTag;
}
else {
TextRange closeTag = null;
Position start = editorAdaptor.getCursorService().getPosition();
for(int i=0; i < count; i++) {
closeTag = getUnbalancedClosingTag(start, editorAdaptor);
//prepare for next iteration (if any)
start = closeTag.getRightBound();
}
return closeTag;
}
}
/**
* Search forwards for XML tags. Push every open tag, pop every close tag.
* If we get a close tag without an open tag, we're inside that tag.
*/
public TextRange getUnbalancedClosingTag(Position start, EditorAdaptor editorAdaptor) throws CommandExecutionException {
Stack<String> openTags = new Stack<String>();
TextRange tag;
String contents;
String tagName;
while(true) { //we'll either hit a 'return' or throw an exception
tag = findNextTag(start, editorAdaptor);
contents = editorAdaptor.getModelContent().getText(tag);
start = tag.getRightBound(); //prepare for next iteration
if(contents.startsWith("</")) { //close tag
tagName = getClosingTagName(tag, editorAdaptor);
if(openTags.empty() ) {
//we hit a close tag before finding any open tags
//the cursor must be inside this tag
return tag;
}
else if(openTags.peek().equals(tagName)) {
//found the matching close tag for this open tag
//ignore it and keep moving
openTags.pop();
}
else {
//there must've been a mis-matched open tag
//does this closing tag match with anything we've seen?
while(!openTags.empty()) {
if(openTags.peek().equals(tagName)) {
//we found the match to this close tag
//just skip that unexpected open tag
break;
}
//see if the previous tag matches
//this closing tag's name
openTags.pop();
}
//did we exhaust the list?
//this must be the closing tag we're inside
if(openTags.empty()) {
return tag;
}
}
}
else { //open tag, see if we'll find it's matching close tag
tagName = getOpenTagName(tag, editorAdaptor);
openTags.push(tagName);
}
}
}
/**
* Search for the next XML tag after start. Can either be an open tag or
* close tag. We'll let the calling method figure out what to do with it.
*/
private TextRange findNextTag(Position start, EditorAdaptor editorAdaptor) throws CommandExecutionException {
//regex usually stops at newlines but open tags might have
//multiple lines of attributes. So, include newlines in search.
Search findTag = new Search("<(.|\n)*?>", false, false, true, SearchOffset.NONE, true);
SearchAndReplaceService searchAndReplace = editorAdaptor.getSearchAndReplaceService();
SearchResult result = searchAndReplace.find(findTag, start);
if( ! result.isFound()) {
//we couldn't find a tag
throw new CommandExecutionException("The cursor is not within an XML tag");
}
return new StartEndTextRange(result.getLeftBound(), result.getRightBound());
}
/**
* Search backwards for XML tags. Push every close tag, pop every open tag.
* If we get the open tag we're looking for without a matching close tag, we're inside that tag.
*/
public TextRange getUnbalancedOpenTag(Position start, String toFindTagName, EditorAdaptor editorAdaptor) throws CommandExecutionException {
Stack<String> closeTags = new Stack<String>();
TextRange tag;
String contents;
String tagName;
while(true) { //we'll either hit a 'return' or throw an exception
tag = findPreviousTag(start, editorAdaptor, toFindTagName);
contents = editorAdaptor.getModelContent().getText(tag);
start = tag.getLeftBound(); //prepare for next iteration
if(contents.startsWith("</")) { //close tag, see if we'll find it's matching open tag
tagName = getClosingTagName(tag, editorAdaptor);
closeTags.push(tagName);
}
else { //open tag
tagName = getOpenTagName(tag, editorAdaptor);
if(closeTags.empty() && tagName.equals(toFindTagName) ) {
//we hit the desired open tag before finding any close tags
//the cursor must be inside this tag
return tag;
}
else if(!closeTags.empty() && closeTags.peek().equals(tagName)) {
//found the matching open tag for this close tag
//ignore it and keep moving
closeTags.pop();
}
else if(tagName.equals(toFindTagName)) {
//we don't have the corresponding close tag for this open tag
//and it matches the name we're looking for
//the cursor must be inside this tag
return tag;
}
else {
//we found an open tag without a corresponding close tag
//but it wasn't the open tag we wanted
//ignore it and keep moving (this is how vim handles it)
}
}
}
}
/**
* Search for the previous XML tag before start. Can either be an open tag or
* close tag. We'll let the calling method figure out what to do with it.
*/
private TextRange findPreviousTag(Position start, EditorAdaptor editorAdaptor, String toFindTagName) throws CommandExecutionException {
//regex usually stops at newlines but open tags might have
//multiple lines of attributes. So, include newlines in search.
Search findTag = new Search("<(.|\n)*?>", true, false, true, SearchOffset.NONE, true);
SearchAndReplaceService searchAndReplace = editorAdaptor.getSearchAndReplaceService();
SearchResult result = searchAndReplace.find(findTag, start);
if( ! result.isFound()) {
//we couldn't find a tag
throw new CommandExecutionException("Could not find matching open tag for </"+toFindTagName+">");
}
return new StartEndTextRange(result.getLeftBound(), result.getRightBound());
}
/**
* Just a few convenience methods
*/
private String getOpenTagName(TextRange tagRange, EditorAdaptor editorAdaptor) {
String contents = editorAdaptor.getModelContent().getText(tagRange);
//name goes from '<' to first space or first '>'
return contents.indexOf(' ') > -1 ? contents.substring(1, contents.indexOf(' ')) : contents.substring(1, contents.indexOf('>'));
}
private String getClosingTagName(TextRange tagRange, EditorAdaptor editorAdaptor) {
String tag = editorAdaptor.getModelContent().getText(tagRange);
//chop off leading '</' and trailing '>'
return tag.substring(2, tag.length()-1);
}
}
|
package com.smxknife.energy.services.alarm.spi.service;
import com.smxknife.energy.services.alarm.spi.domain.AlarmRule;
import java.util.List;
/**
* @author smxknife
* 2021/5/17
*/
public interface AlarmRuleService {
List<AlarmRule> getAll();
void createRule(AlarmRule rule);
void edit(AlarmRule rule);
void deleteByUid(String uid);
}
|
package com.define.attachment.service;
import com.define.attachment.domain.FileDO;
import com.define.ueditor.domain.UeditorImageDO;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;
/**
* 文件管理
*
* @author caiww
* @email caiwwh@gzdefine.com
* @date 2019-03-15 10:40:45
*/
public interface FileService {
FileDO get(Long id);
List<FileDO> list(Map<String, Object> map);
int count(Map<String, Object> map);
int save(FileDO sysFile);
int update(FileDO sysFile);
int remove(Long id);
int batchRemove(Long[] ids);
Boolean isExist(String url);
UeditorImageDO uploadFile(MultipartFile file) throws Exception;
UeditorImageDO uploadScrawl(String file) throws Exception;
String formetFileSize(long filesize);
String getUploadFileUrl(int fileType);
}
|
package es.uma.sportjump.sjs.model.entities;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import es.uma.sportjump.sjs.model.entities.test.util.CoachTestUtil;
public class CoachModelEntityTest {
private static EntityManagerFactory entityManagerFactory = null;
private static CoachTestUtil coachUtil;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
entityManagerFactory = Persistence.createEntityManagerFactory("sportjumpJpaPU");
coachUtil = CoachTestUtil.getInstance(entityManagerFactory);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
entityManagerFactory = null;
coachUtil = null;
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testCRUD() {
// Definition Coach
String name = "Mourinho";
String surname = "Garcia";
String userName = "Jose";
String email = "asdf@asdf.es";
String dni = "88779988R";
// Create Coach
Long idCoach = coachUtil.createCoach(name,surname, userName, email,dni);
// Make assert
assertNotNull(idCoach);
// Read Coach
Coach coach = coachUtil.readCoach(idCoach);
// Make assert
coachUtil.makeAssertCoach(name, coach);
// Update Coach
String newName = "Guardiola";
coachUtil.updateCoach(idCoach, newName);
// Read coach
coach = coachUtil.readCoach(idCoach);
// Make assert
coachUtil.makeAssertCoach(newName,coach);
// Delete Coach
coachUtil.deleteCoach(idCoach);
// Read Coach
coach = coachUtil.readCoach(idCoach);
// Make assert
assertNull(coach);
}
}
|
//dp题
class Solution {
public boolean isMatch(String s, String p) {
int slen = s.length();
int plen = p.length();
boolean[][] dp = new boolean[slen + 1][plen + 1];
for(int j = 0; j < plen + 1; j++){
for(int i = 0; i < slen + 1; i++){
if(j == 0){
dp[i][j] = (i == 0);
continue;
}
char x = p.charAt(j - 1);
if(x == '.'){
dp[i][j] = (i != 0 && dp[i - 1][j - 1]);
}
else if(x == '*'){
dp[i][j] = (i == 0) ? dp[i][j - 2] :
dp[i][j - 2] || (dp[i - 1][j] && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1)));
}
else{
dp[i][j] = (i != 0 && dp[i - 1][j - 1] && s.charAt(i - 1) == p.charAt(j - 1));
}
}
}
return dp[slen][plen];
}
}
|
package com.tencent.mm.plugin.wear.model.e;
import com.tencent.mm.plugin.wear.model.a;
class a$1 implements Runnable {
final /* synthetic */ byte[] pJP;
final /* synthetic */ a pJQ;
a$1(a aVar, byte[] bArr) {
this.pJQ = aVar;
this.pJP = bArr;
}
public final void run() {
a.bSl().pIM.ba(this.pJP);
}
}
|
package com.tencent.mm.plugin.aa;
import com.tencent.mm.ab.d.a;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.messenger.foundation.a.n;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.protocal.d;
import com.tencent.mm.s.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import java.util.Map;
class b$5 implements n {
final /* synthetic */ b ezx;
b$5(b bVar) {
this.ezx = bVar;
}
public final void onNewXmlReceived(String str, Map<String, String> map, a aVar) {
x.d("MicroMsg.SubCoreAA", "paymsgtype: %d, current version: %d", new Object[]{Integer.valueOf(bi.getInt((String) map.get(".sysmsg.paymsg.PayMsgType"), 0)), Integer.valueOf(d.qVN)});
if (bi.getInt((String) map.get(".sysmsg.paymsg.PayMsgType"), 0) == 32) {
int i = bi.getInt((String) map.get(".sysmsg.paymsg.receiveorpayreddot"), 0);
int i2 = bi.getInt((String) map.get(".sysmsg.paymsg.grouppayreddot"), 0);
int i3 = bi.getInt((String) map.get(".sysmsg.paymsg.facingreceivereddot"), 0);
int i4 = bi.getInt((String) map.get(".sysmsg.paymsg.f2fhongbaoreddot"), 0);
int i5 = bi.getInt((String) map.get(".sysmsg.paymsg.rewardcodereddot"), 0);
int i6 = bi.getInt((String) map.get(".sysmsg.paymsg.android_minclientversion"), 0);
String aG = bi.aG((String) map.get(".sysmsg.paymsg.facingreceivereddotwording"), "");
g.Ek();
g.Ei().DT().a(aa.a.sYu, aG);
if (d.qVN >= i6) {
boolean z;
if (i == 1) {
x.i("MicroMsg.SubCoreAA", "mark recv or pay red dot");
c.Cp().v(262159, true);
z = true;
} else {
z = false;
}
if (i2 == 1) {
x.i("MicroMsg.SubCoreAA", "mark group pay red dot");
c.Cp().b(aa.a.sZc, true);
z = true;
}
if (i3 == 1) {
x.i("MicroMsg.SubCoreAA", "mark f2f recv red dot");
c.Cp().b(aa.a.sZd, true);
z = true;
}
if (i4 == 1) {
x.i("MicroMsg.SubCoreAA", "mark f2f hb red dot");
c.Cp().b(aa.a.sZe, true);
z = true;
}
if (i5 == 1) {
x.i("MicroMsg.SubCoreAA", "mark qr reward red dot");
c.Cp().b(aa.a.sZf, true);
z = true;
}
if (z) {
g.Ei().DT().a(aa.a.sZh, Boolean.valueOf(false));
}
}
h.mEJ.h(14396, new Object[]{Integer.valueOf(1)});
}
}
}
|
package com.tencent.mm.plugin.remittance.model;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.md;
import com.tencent.mm.protocal.c.me;
import com.tencent.mm.sdk.platformtools.x;
public final class n extends l implements k {
private e diJ;
private b eAN;
private md mxs;
public n(String str, String str2, String str3, String str4, int i) {
a aVar = new a();
aVar.dIG = new md();
aVar.dIH = new me();
aVar.dIF = 1273;
aVar.uri = "/cgi-bin/mmpay-bin/f2fpaycheck";
aVar.dII = 0;
aVar.dIJ = 0;
this.eAN = aVar.KT();
this.mxs = (md) this.eAN.dID.dIL;
this.mxs.rcD = str;
this.mxs.rcE = str2;
this.mxs.rqo = str3;
this.mxs.rqp = str4;
this.mxs.amount = i;
x.d("MicroMsg.NetSceneF2fPayCheck", "NetSceneF2fPayCheck, f2fId: %s, transId: %s, extendStr: %s, amount: %s", new Object[]{str, str2, str3, Integer.valueOf(i)});
}
public final int getType() {
return 1273;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.eAN, this);
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetSceneF2fPayCheck", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str});
if (this.diJ != null) {
this.diJ.a(i2, i3, str, this);
}
}
}
|
package megadescanso;
public class ProfessorModalidade {
private String dtAptidao;
private Professor professor;
private Modalidade modalidade;
public ProfessorModalidade() {
super();
}
public ProfessorModalidade(String dtAptidao, Professor professor,
Modalidade modalidade) {
super();
this.dtAptidao = dtAptidao;
this.professor = professor;
this.modalidade = modalidade;
}
public String getDtAptidao() {
return dtAptidao;
}
public void setDtAptidao(String dtAptidao) {
this.dtAptidao = dtAptidao;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
public Modalidade getModalidade() {
return modalidade;
}
public void setModalidade(Modalidade modalidade) {
this.modalidade = modalidade;
}
}
|
package bean;
/**
* Created by zhuxinquan on 16-8-14.
*/
public class MessageService {
private Message[] fakeMessage;
public MessageService(){
fakeMessage = new Message[3];
fakeMessage[0] = new Message("caterpillar", "caterpillar's message");
fakeMessage[1] = new Message("momor", "momor's message");
fakeMessage[2] = new Message("hamimi", "hamimi's message");
}
public Message[] getMessage(){
return fakeMessage;
}
}
|
package JoinProject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class MapSideJoin {
//Mappers need to emitt differrent types but reducer has to be passed only one type hence the wrapper
public static class SalesOrderDataMapper extends Mapper<Object,Text,ProductIdKey,JoinGenericWritable>{
IntWritable pId=new IntWritable();
public void map(Object key,Text value,Context context) throws IOException,InterruptedException{
String[] recordFields = value.toString().split("\\t");
int productId = Integer.parseInt(recordFields[4]);
int orderQty = Integer.parseInt(recordFields[3]);
double lineTotal = Double.parseDouble(recordFields[8]);
pId.set(productId);
ProductIdKey recordKey = new ProductIdKey(pId, ProductIdKey.DATA_RECORD);
SalesOrderDataRecord record = new SalesOrderDataRecord(orderQty, lineTotal);
JoinGenericWritable genericRecord = new JoinGenericWritable(record);
context.write(recordKey, genericRecord);
}
}
//Mappers need to emit differrent types but reducer has to be passed only one type hence the wrapper
public static class ProductMapper extends Mapper<Object,Text,ProductIdKey,JoinGenericWritable>{
IntWritable pId=new IntWritable();
private HashMap<Integer, String> productSubCategories = new HashMap<Integer, String>();
private Path[] localFiles;
private BufferedReader brReader;
private void readProductSubcategoriesFile(Path path) throws IOException{
brReader = new BufferedReader(new FileReader(path.toString()));
String strLineRead = "";
while ((strLineRead = brReader.readLine()) != null) {
String recordFields[] = strLineRead.split("\\t");
int key = Integer.parseInt(recordFields[0]);
String productSubcategoryName = recordFields[2];
productSubCategories.put(key, productSubcategoryName);
}
}
public void setup(Context context) throws IOException{
localFiles =DistributedCache.getLocalCacheFiles(context.getConfiguration());
if(localFiles[0]!=null)
readProductSubcategoriesFile(localFiles[0]);
}
public void map(Object key,Text value,Context context) throws IOException,InterruptedException{
String[] recordFields = value.toString().split("\\t");
int productId = Integer.parseInt(recordFields[0]);
int productSubcategoryId = recordFields[18].length() > 0 ? Integer.parseInt(recordFields[18]) : 0;
String pName=recordFields[1];
String pNumber=recordFields[2];
String productSubcategoryName = productSubcategoryId > 0 ? productSubCategories.get(productSubcategoryId) : "";
pId.set(Integer.parseInt(recordFields[0]));
ProductIdKey recordKey = new ProductIdKey(pId, ProductIdKey.PRODUCT_RECORD);
ProductRecord record=new ProductRecord(pName,pNumber,productSubcategoryName);
JoinGenericWritable genericRecord = new JoinGenericWritable(record);
context.write(recordKey, genericRecord);
}
}
public static class JoinGroupingComparator extends WritableComparator{
//join criteria is ProductIdKey
public JoinGroupingComparator() {
super(ProductIdKey.class,true);
}
public int compare(WritableComparable a,WritableComparable b) {
ProductIdKey first = (ProductIdKey) a;
ProductIdKey second = (ProductIdKey) b;
return first.ProductId.compareTo(second.ProductId);
}
}
public static class JoinRecuder extends Reducer<ProductIdKey, JoinGenericWritable, NullWritable, Text>{
public void reduce(ProductIdKey key, Iterable<JoinGenericWritable> values, Context context) throws IOException, InterruptedException{
StringBuilder output = new StringBuilder();
int sumOrderQty = 0;
double sumLineTotal = 0.0;
for (JoinGenericWritable v : values) {
Writable record = v.get();
if (key.recordType.equals(ProductIdKey.PRODUCT_RECORD)){
ProductRecord pRecord = (ProductRecord)record;
output.append(Integer.parseInt(key.ProductId.toString())).append(", ");
output.append(pRecord.productName.toString()).append(", ");
output.append(pRecord.productNumber.toString()).append(", ");
output.append(pRecord.productSubcategoryName.toString()).append(", ");
} else {
SalesOrderDataRecord record2 = (SalesOrderDataRecord)record;
sumOrderQty += Integer.parseInt(record2.orderQty.toString());
sumLineTotal += Double.parseDouble(record2.lineTotal.toString());
}
}
if (sumOrderQty > 0) {
context.write(NullWritable.get(), new Text(output.toString() + sumOrderQty + ", " + sumLineTotal));
}
}
}
public static class JoinSortingComparator extends WritableComparator {
public JoinSortingComparator()
{
super (ProductIdKey.class, true);
}
@Override
public int compare (WritableComparable a, WritableComparable b){
ProductIdKey first = (ProductIdKey) a;
ProductIdKey second = (ProductIdKey) b;
return first.compareTo(second);
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf,"ReduceSideJoin");
job.setJarByClass(MapSideJoin.class);
// job.addCacheFile(new URI(args[2]));
DistributedCache.addCacheFile(new URI(args[2]), job.getConfiguration());
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setMapOutputKeyClass(ProductIdKey.class);
job.setMapOutputValueClass(JoinGenericWritable.class);
MultipleInputs.addInputPath(job, new Path(args[0]), TextInputFormat.class, SalesOrderDataMapper.class);
MultipleInputs.addInputPath(job, new Path(args[1]), TextInputFormat.class, ProductMapper.class);
job.setReducerClass(JoinRecuder.class);
job.setSortComparatorClass(JoinSortingComparator.class);
job.setGroupingComparatorClass(JoinGroupingComparator.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
FileSystem.get(conf).delete(new Path(args[3]),true);
FileOutputFormat.setOutputPath(job, new Path(args[3]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
package Dao;
import java.sql.Timestamp;
public class Order
{
private int orderid;
private int userid;
private int productid;
private int qnty;
private int categoryid;
private String ordernumber;
private String productname;
private String address;
private Timestamp createdate;
private Timestamp updateddate;
private String totalprice;
private String usertype;
private String mobile;
private String uom;
private String marginedprice;
private String price;
private String categoryname;
private String orderstatus;
private String agentname;
private String agentemail;
private String villagecity;
private String taluka;
private String district;
private String pincode;
private String name;
private String emailid;
private String mrp;
public String getMrp() {
return mrp;
}
public void setMrp(String mrp) {
this.mrp = mrp;
}
public int getOrderid() {
return orderid;
}
public void setOrderid(int orderid) {
this.orderid = orderid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public int getProductid() {
return productid;
}
public void setProductid(int productid) {
this.productid = productid;
}
public int getQnty() {
return qnty;
}
public void setQnty(int qnty) {
this.qnty = qnty;
}
public int getCategoryid() {
return categoryid;
}
public void setCategoryid(int categoryid) {
this.categoryid = categoryid;
}
public String getOrdernumber() {
return ordernumber;
}
public void setOrdernumber(String ordernumber) {
this.ordernumber = ordernumber;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Timestamp getCreatedate() {
return createdate;
}
public void setCreatedate(Timestamp createdate) {
this.createdate = createdate;
}
public Timestamp getUpdateddate() {
return updateddate;
}
public void setUpdateddate(Timestamp updateddate) {
this.updateddate = updateddate;
}
public String getTotalprice() {
return totalprice;
}
public void setTotalprice(String totalprice) {
this.totalprice = totalprice;
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getUom() {
return uom;
}
public void setUom(String uom) {
this.uom = uom;
}
public String getMarginedprice() {
return marginedprice;
}
public void setMarginedprice(String marginedprice) {
this.marginedprice = marginedprice;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCategoryname() {
return categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public String getOrderstatus() {
return orderstatus;
}
public void setOrderstatus(String orderstatus) {
this.orderstatus = orderstatus;
}
public String getAgentname() {
return agentname;
}
public void setAgentname(String agentname) {
this.agentname = agentname;
}
public String getAgentemail() {
return agentemail;
}
public void setAgentemail(String agentemail) {
this.agentemail = agentemail;
}
public String getVillagecity() {
return villagecity;
}
public void setVillagecity(String villagecity) {
this.villagecity = villagecity;
}
public String getTaluka() {
return taluka;
}
public void setTaluka(String taluka) {
this.taluka = taluka;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
@Override
public String toString() {
return "Order [orderid=" + orderid + ", userid=" + userid + ", productid=" + productid + ", qnty=" + qnty
+ ", categoryid=" + categoryid + ", ordernumber=" + ordernumber + ", productname=" + productname
+ ", address=" + address + ", createdate=" + createdate + ", updateddate=" + updateddate
+ ", totalprice=" + totalprice + ", usertype=" + usertype + ", mobile=" + mobile + ", uom=" + uom
+ ", marginedprice=" + marginedprice + ", price=" + price + ", categoryname=" + categoryname
+ ", orderstatus=" + orderstatus + ", agentname=" + agentname + ", agentemail=" + agentemail
+ ", villagecity=" + villagecity + ", taluka=" + taluka + ", district=" + district + ", pincode="
+ pincode + ", name=" + name + ", emailid=" + emailid + ", mrp=" + mrp + "]";
}
}
|
package com.rc.portal.vo;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.rc.app.framework.webapp.model.BaseModel;
public class TCouponCardExample extends BaseModel{
protected String orderByClause;
protected List oredCriteria;
public TCouponCardExample() {
oredCriteria = new ArrayList();
}
protected TCouponCardExample(TCouponCardExample example) {
this.orderByClause = example.orderByClause;
this.oredCriteria = example.oredCriteria;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public List getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
}
public static class Criteria {
protected List criteriaWithoutValue;
protected List criteriaWithSingleValue;
protected List criteriaWithListValue;
protected List criteriaWithBetweenValue;
protected Criteria() {
super();
criteriaWithoutValue = new ArrayList();
criteriaWithSingleValue = new ArrayList();
criteriaWithListValue = new ArrayList();
criteriaWithBetweenValue = new ArrayList();
}
public boolean isValid() {
return criteriaWithoutValue.size() > 0
|| criteriaWithSingleValue.size() > 0
|| criteriaWithListValue.size() > 0
|| criteriaWithBetweenValue.size() > 0;
}
public List getCriteriaWithoutValue() {
return criteriaWithoutValue;
}
public List getCriteriaWithSingleValue() {
return criteriaWithSingleValue;
}
public List getCriteriaWithListValue() {
return criteriaWithListValue;
}
public List getCriteriaWithBetweenValue() {
return criteriaWithBetweenValue;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteriaWithoutValue.add(condition);
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("value", value);
criteriaWithSingleValue.add(map);
}
protected void addCriterion(String condition, List values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
Map map = new HashMap();
map.put("condition", condition);
map.put("values", values);
criteriaWithListValue.add(map);
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
List list = new ArrayList();
list.add(value1);
list.add(value2);
Map map = new HashMap();
map.put("condition", condition);
map.put("values", list);
criteriaWithBetweenValue.add(map);
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("id =", value, "id");
return this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("id <>", value, "id");
return this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("id >", value, "id");
return this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("id >=", value, "id");
return this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("id <", value, "id");
return this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("id <=", value, "id");
return this;
}
public Criteria andIdIn(List values) {
addCriterion("id in", values, "id");
return this;
}
public Criteria andIdNotIn(List values) {
addCriterion("id not in", values, "id");
return this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("id between", value1, value2, "id");
return this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("id not between", value1, value2, "id");
return this;
}
public Criteria andCardNoIsNull() {
addCriterion("card_no is null");
return this;
}
public Criteria andCardNoIsNotNull() {
addCriterion("card_no is not null");
return this;
}
public Criteria andCardNoEqualTo(String value) {
addCriterion("card_no =", value, "cardNo");
return this;
}
public Criteria andCardNoNotEqualTo(String value) {
addCriterion("card_no <>", value, "cardNo");
return this;
}
public Criteria andCardNoGreaterThan(String value) {
addCriterion("card_no >", value, "cardNo");
return this;
}
public Criteria andCardNoGreaterThanOrEqualTo(String value) {
addCriterion("card_no >=", value, "cardNo");
return this;
}
public Criteria andCardNoLessThan(String value) {
addCriterion("card_no <", value, "cardNo");
return this;
}
public Criteria andCardNoLessThanOrEqualTo(String value) {
addCriterion("card_no <=", value, "cardNo");
return this;
}
public Criteria andCardNoLike(String value) {
addCriterion("card_no like", value, "cardNo");
return this;
}
public Criteria andCardNoNotLike(String value) {
addCriterion("card_no not like", value, "cardNo");
return this;
}
public Criteria andCardNoIn(List values) {
addCriterion("card_no in", values, "cardNo");
return this;
}
public Criteria andCardNoNotIn(List values) {
addCriterion("card_no not in", values, "cardNo");
return this;
}
public Criteria andCardNoBetween(String value1, String value2) {
addCriterion("card_no between", value1, value2, "cardNo");
return this;
}
public Criteria andCardNoNotBetween(String value1, String value2) {
addCriterion("card_no not between", value1, value2, "cardNo");
return this;
}
public Criteria andIsUseIsNull() {
addCriterion("is_use is null");
return this;
}
public Criteria andIsUseIsNotNull() {
addCriterion("is_use is not null");
return this;
}
public Criteria andIsUseEqualTo(Integer value) {
addCriterion("is_use =", value, "isUse");
return this;
}
public Criteria andIsUseNotEqualTo(Integer value) {
addCriterion("is_use <>", value, "isUse");
return this;
}
public Criteria andIsUseGreaterThan(Integer value) {
addCriterion("is_use >", value, "isUse");
return this;
}
public Criteria andIsUseGreaterThanOrEqualTo(Integer value) {
addCriterion("is_use >=", value, "isUse");
return this;
}
public Criteria andIsUseLessThan(Integer value) {
addCriterion("is_use <", value, "isUse");
return this;
}
public Criteria andIsUseLessThanOrEqualTo(Integer value) {
addCriterion("is_use <=", value, "isUse");
return this;
}
public Criteria andIsUseIn(List values) {
addCriterion("is_use in", values, "isUse");
return this;
}
public Criteria andIsUseNotIn(List values) {
addCriterion("is_use not in", values, "isUse");
return this;
}
public Criteria andIsUseBetween(Integer value1, Integer value2) {
addCriterion("is_use between", value1, value2, "isUse");
return this;
}
public Criteria andIsUseNotBetween(Integer value1, Integer value2) {
addCriterion("is_use not between", value1, value2, "isUse");
return this;
}
public Criteria andUseTimeIsNull() {
addCriterion("use_time is null");
return this;
}
public Criteria andUseTimeIsNotNull() {
addCriterion("use_time is not null");
return this;
}
public Criteria andUseTimeEqualTo(Date value) {
addCriterion("use_time =", value, "useTime");
return this;
}
public Criteria andUseTimeNotEqualTo(Date value) {
addCriterion("use_time <>", value, "useTime");
return this;
}
public Criteria andUseTimeGreaterThan(Date value) {
addCriterion("use_time >", value, "useTime");
return this;
}
public Criteria andUseTimeGreaterThanOrEqualTo(Date value) {
addCriterion("use_time >=", value, "useTime");
return this;
}
public Criteria andUseTimeLessThan(Date value) {
addCriterion("use_time <", value, "useTime");
return this;
}
public Criteria andUseTimeLessThanOrEqualTo(Date value) {
addCriterion("use_time <=", value, "useTime");
return this;
}
public Criteria andUseTimeIn(List values) {
addCriterion("use_time in", values, "useTime");
return this;
}
public Criteria andUseTimeNotIn(List values) {
addCriterion("use_time not in", values, "useTime");
return this;
}
public Criteria andUseTimeBetween(Date value1, Date value2) {
addCriterion("use_time between", value1, value2, "useTime");
return this;
}
public Criteria andUseTimeNotBetween(Date value1, Date value2) {
addCriterion("use_time not between", value1, value2, "useTime");
return this;
}
public Criteria andMemberIdIsNull() {
addCriterion("member_id is null");
return this;
}
public Criteria andMemberIdIsNotNull() {
addCriterion("member_id is not null");
return this;
}
public Criteria andMemberIdEqualTo(Long value) {
addCriterion("member_id =", value, "memberId");
return this;
}
public Criteria andMemberIdNotEqualTo(Long value) {
addCriterion("member_id <>", value, "memberId");
return this;
}
public Criteria andMemberIdGreaterThan(Long value) {
addCriterion("member_id >", value, "memberId");
return this;
}
public Criteria andMemberIdGreaterThanOrEqualTo(Long value) {
addCriterion("member_id >=", value, "memberId");
return this;
}
public Criteria andMemberIdLessThan(Long value) {
addCriterion("member_id <", value, "memberId");
return this;
}
public Criteria andMemberIdLessThanOrEqualTo(Long value) {
addCriterion("member_id <=", value, "memberId");
return this;
}
public Criteria andMemberIdIn(List values) {
addCriterion("member_id in", values, "memberId");
return this;
}
public Criteria andMemberIdNotIn(List values) {
addCriterion("member_id not in", values, "memberId");
return this;
}
public Criteria andMemberIdBetween(Long value1, Long value2) {
addCriterion("member_id between", value1, value2, "memberId");
return this;
}
public Criteria andMemberIdNotBetween(Long value1, Long value2) {
addCriterion("member_id not between", value1, value2, "memberId");
return this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return this;
}
public Criteria andCreateTimeIn(List values) {
addCriterion("create_time in", values, "createTime");
return this;
}
public Criteria andCreateTimeNotIn(List values) {
addCriterion("create_time not in", values, "createTime");
return this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return this;
}
public Criteria andTicketIdIsNull() {
addCriterion("ticket_id is null");
return this;
}
public Criteria andTicketIdIsNotNull() {
addCriterion("ticket_id is not null");
return this;
}
public Criteria andTicketIdEqualTo(Long value) {
addCriterion("ticket_id =", value, "ticketId");
return this;
}
public Criteria andTicketIdNotEqualTo(Long value) {
addCriterion("ticket_id <>", value, "ticketId");
return this;
}
public Criteria andTicketIdGreaterThan(Long value) {
addCriterion("ticket_id >", value, "ticketId");
return this;
}
public Criteria andTicketIdGreaterThanOrEqualTo(Long value) {
addCriterion("ticket_id >=", value, "ticketId");
return this;
}
public Criteria andTicketIdLessThan(Long value) {
addCriterion("ticket_id <", value, "ticketId");
return this;
}
public Criteria andTicketIdLessThanOrEqualTo(Long value) {
addCriterion("ticket_id <=", value, "ticketId");
return this;
}
public Criteria andTicketIdIn(List values) {
addCriterion("ticket_id in", values, "ticketId");
return this;
}
public Criteria andTicketIdNotIn(List values) {
addCriterion("ticket_id not in", values, "ticketId");
return this;
}
public Criteria andTicketIdBetween(Long value1, Long value2) {
addCriterion("ticket_id between", value1, value2, "ticketId");
return this;
}
public Criteria andTicketIdNotBetween(Long value1, Long value2) {
addCriterion("ticket_id not between", value1, value2, "ticketId");
return this;
}
}
}
|
package com.newaswan.seven;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class FacebookActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebookactivity);
}
}
|
package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model;
/**
* Created by rohitsingh on 16/07/16.
*/
public class OrderInfo {
private int token;
private Order order;
private Customer customer;
private IdCodeName deliveryPartner;
private IdCodeName channelPartner;
private boolean mDuplicatePrinted;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public IdCodeName getDeliveryPartner() {
return deliveryPartner;
}
public void setDeliveryPartner(IdCodeName deliveryPartner) {
this.deliveryPartner = deliveryPartner;
}
public IdCodeName getChannelPartner() {
return channelPartner;
}
public void setChannelPartner(IdCodeName channelPartner) {
this.channelPartner = channelPartner;
}
@Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof OrderInfo) {
Order order = ((OrderInfo) obj).getOrder();
if (order != null) {
if (this.getOrder() != null) {
return order.getGenerateOrderId().equals(this.getOrder().getGenerateOrderId());
}
}
}
}
return false;
}
public boolean isDuplicatePrinted() {
return mDuplicatePrinted;
}
public void setDuplicatePrinted(boolean mDuplicatePrinted) {
this.mDuplicatePrinted = mDuplicatePrinted;
}
public int getToken() {
return token;
}
public void setToken(int token) {
this.token = token;
}
}
|
package edu.imtl.BlueKare.Utils;
//matrix class
public class MatrixUtil {
public static float[] crossMatrix(float a1, float a2, float a3, float b1, float b2, float b3){
// cross product
float i = a2*b3 - a3*b2;
float j = a3*b1 - a1*b3;
float k = a1*b2 - a2*b1;
// unit vector
float unit = (float)Math.sqrt(i*i + j*j + k*k);
i /= unit;
j /= unit;
k /= unit;
return new float[]{i,j,k};
}
}
|
package lokinsky.dope.plugin;
import lokinsky.dope.plugin.Logic.PDO_MYSQL;
import lokinsky.dope.plugin.Models.Client;
import java.sql.SQLException;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class DopeListener implements Listener {
private DopeEventObserver dopeEventObserver;
private PDO_MYSQL pdo_mysql;
public void set_event_observer(DopeEventObserver dopeEventObserver) {
this.dopeEventObserver = dopeEventObserver;
}
public DopeListener() {
}
public DopeListener(PDO_MYSQL pdo_mysql) {
this.pdo_mysql = pdo_mysql;
}
@EventHandler
public void onLogin(PlayerLoginEvent event) throws SQLException {
pdo_mysql.sql.get("get_user").setString(1, event.getPlayer().getName());
pdo_mysql.sql.get("get_user").execute();
if(pdo_mysql.sql.get("get_user").getResultSet().next()) {
dopeEventObserver.getClients().add(new Client(event.getPlayer().getName(),event.getPlayer().getUniqueId()));
dopeEventObserver.refreshClients();
}else {
event.disallow(Result.KICK_OTHER, "You must register before play –– minecraft.fools.dope");
}
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
}
@EventHandler
public void onMovement(PlayerMoveEvent event) {
if(!dopeEventObserver.getClients().get(event.getPlayer().getName()).isAuth()) {
event.getPlayer().teleport(event.getFrom());
event.getPlayer().sendMessage("Login first with command /dlogin <password>.");
dopeEventObserver.Logger("PlayerMoveEvent@"+event.getPlayer().getName());
}
}
@EventHandler
public void onDisconnect(PlayerQuitEvent event) {
dopeEventObserver.getClients().remove(event.getPlayer().getName());
dopeEventObserver.refreshClients();
}
}
|
package Chapter17;
import java.util.Arrays;
/**
* Created by sg on 08.03.18.
*/
public class Question6
{
/*
* Uses sorting. Time: O(nlogn) due to sorting, Space: O(n)
*/
static void minSorting( int[] input )
{
int minIndex = -1, maxIndex = -1;
int[] copy = input.clone();
Arrays.sort( copy );
for ( int i = 0; i < copy.length; i++ ) {
// we can break when i > length - i - 1; which gives an O(logn) loop
if ( copy[ i ] != input[ i ] && minIndex == -1 ) {// it's unset
minIndex = i;
}
if ( copy[ copy.length - i - 1 ] != input[ input.length - i - 1 ] && maxIndex == -1 ) {
maxIndex = copy.length - i - 1;
}
if ( minIndex != -1 && maxIndex != -1 ) {
// optimization
break;
}
}
System.out.println( minIndex + " " + maxIndex );
}
public static void main( String[] args )
{
minSorting( new int[] { 1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19 } ); // inbetween
minSorting( new int[] { 6, 5, 4, 7, 10 } ); // at the start
minSorting( new int[] { 2, 5, 6, 10, 7 } ); // at the end
minSorting( new int[] { 2, 6, 5, 7, 10 } ); // in the middle for odd number of elements
minSorting( new int[] { 2, 4, 7, 5, 11, 12 } ); // in the middle for even number of elements
minSorting( new int[] { 2, 5, 6, 7, 9 } ); // already sorted
minSorting( new int[] { 11, 9, 6, 5, 1 } ); // sorted in reverse
minSorting( new int[] { 2, 7, 7, 5, 7 } ); // with repetions middle to end
minSorting( new int[] { 2, 7, 7, 7, 5 } );
minSorting( new int[] { 7, 2, 6, 7, 8 } ); // with repetetions that are in place
minSorting( new int[] { 7, 2, 7, 6, 8 } ); // with repetetions that are not in place
// toptal
minSorting( new int[] { 1, 5, 4, 9, 8, 7, 12, 13, 14 } ); // each index that is already in place counts as +1.
// From the unsorted ones we need to find the #number of sets
minSorting( new int[] { 5, 3, 4, 6, 9, 8, 7 } );
}
}
|
package com.capgemini.exceptions;
public class DuplicateVehicleException extends Exception {
public DuplicateVehicleException(String message) {
super(message);
}
}
|
package bai_tap.Point_MoveablePoint;
public class Test {
public static void main(String[] args) {
Point unknownPoint = new Point(20,30);
System.out.println(unknownPoint);
unknownPoint.setXY(10,20);
System.out.println(unknownPoint);
unknownPoint = new MoveAblePoint(unknownPoint.getX(),unknownPoint.getY(),10,20);
System.out.println(unknownPoint);
((MoveAblePoint) unknownPoint).move();
System.out.println(unknownPoint);
MoveAblePoint anotherPoint = new MoveAblePoint(20,20);
System.out.println(anotherPoint);
anotherPoint.move();
System.out.println(anotherPoint);
System.out.println(anotherPoint);
}
}
|
package com.cinema_ticketing_sys.movie_cutting.dao;
import com.cinema_ticketing_sys.movie_cutting.entity.MovieCutting;
/**
* Created by huitianrui on 2017/5/28.
*/
public interface MovieCuttingsDAO {
/**
* 通过id查询场次
* @param id
* @return
*/
MovieCutting findCuttingById(int id);
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.AusbringzeileType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.AusbringzeileType.Abmass;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.SchweissnahtListeType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.TFapoIdentifikationType;
import java.io.StringWriter;
import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class AusbringzeileTypeBuilder
{
public static String marshal(AusbringzeileType ausbringzeileType)
throws JAXBException
{
JAXBElement<AusbringzeileType> jaxbElement = new JAXBElement<>(new QName("TESTING"), AusbringzeileType.class , ausbringzeileType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private TFapoIdentifikationType auftragRef;
private BigInteger anzahlTafeln;
private double breite;
private double dicke;
private double laenge;
private double gewicht;
private Double durchmesserAussen;
private Double durchmesserInnen;
private Abmass abmass;
private Boolean absetzen;
private Boolean mischverbund;
private Boolean reststreifen;
private SchweissnahtListeType schweissnahtListe;
private BigInteger lfdNr;
private String planIdent;
public AusbringzeileTypeBuilder setAuftragRef(TFapoIdentifikationType value)
{
this.auftragRef = value;
return this;
}
public AusbringzeileTypeBuilder setAnzahlTafeln(BigInteger value)
{
this.anzahlTafeln = value;
return this;
}
public AusbringzeileTypeBuilder setBreite(double value)
{
this.breite = value;
return this;
}
public AusbringzeileTypeBuilder setDicke(double value)
{
this.dicke = value;
return this;
}
public AusbringzeileTypeBuilder setLaenge(double value)
{
this.laenge = value;
return this;
}
public AusbringzeileTypeBuilder setGewicht(double value)
{
this.gewicht = value;
return this;
}
public AusbringzeileTypeBuilder setDurchmesserAussen(Double value)
{
this.durchmesserAussen = value;
return this;
}
public AusbringzeileTypeBuilder setDurchmesserInnen(Double value)
{
this.durchmesserInnen = value;
return this;
}
public AusbringzeileTypeBuilder setAbmass(Abmass value)
{
this.abmass = value;
return this;
}
public AusbringzeileTypeBuilder setAbsetzen(Boolean value)
{
this.absetzen = value;
return this;
}
public AusbringzeileTypeBuilder setMischverbund(Boolean value)
{
this.mischverbund = value;
return this;
}
public AusbringzeileTypeBuilder setReststreifen(Boolean value)
{
this.reststreifen = value;
return this;
}
public AusbringzeileTypeBuilder setSchweissnahtListe(SchweissnahtListeType value)
{
this.schweissnahtListe = value;
return this;
}
public AusbringzeileTypeBuilder setLfdNr(BigInteger value)
{
this.lfdNr = value;
return this;
}
public AusbringzeileTypeBuilder setPlanIdent(String value)
{
this.planIdent = value;
return this;
}
public AusbringzeileType build()
{
AusbringzeileType result = new AusbringzeileType();
result.setAuftragRef(auftragRef);
result.setAnzahlTafeln(anzahlTafeln);
result.setBreite(breite);
result.setDicke(dicke);
result.setLaenge(laenge);
result.setGewicht(gewicht);
result.setDurchmesserAussen(durchmesserAussen);
result.setDurchmesserInnen(durchmesserInnen);
result.setAbmass(abmass);
result.setAbsetzen(absetzen);
result.setMischverbund(mischverbund);
result.setReststreifen(reststreifen);
result.setSchweissnahtListe(schweissnahtListe);
result.setLfdNr(lfdNr);
result.setPlanIdent(planIdent);
return result;
}
}
|
package com.techlab.case1.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.techlab.case1.Foo;
public class FooTest2 {
public static void main(String[] args) {
Foo obj = new Foo();
Class<?> cls = obj.getClass();
Method[] methods = cls.getMethods();
for (int m = 0; m < methods.length; m++) {
Annotation[] annotations = methods[m].getAnnotations();
System.out.println("Annotation count" + annotations.length);
System.out.println("Method name:" + methods[m]);
}
}
}
|
package supportGUI;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;
import robotsimulator.SimulatorEngine;
class LogPanel
extends JPanel
{
protected static final double userShrinkFactor = 0.25D;
private LogMessage logMessage;
private HelpMessage helpMessage;
protected LogPanel()
{
super(new BorderLayout());
Border loweredbevel = BorderFactory.createLoweredBevelBorder();
logMessage = new LogMessage();
helpMessage = new HelpMessage();
logMessage.setBorder(loweredbevel);
helpMessage.setBorder(loweredbevel);
add(logMessage, "Center");
add(helpMessage, "East");
}
protected LogMessage getLogGUI()
{
return logMessage;
}
protected void bind(SimulatorEngine engine) { logMessage.bind(engine); }
protected void start(int width, int height) {
resetSize(width, height);
logMessage.start(width - (int)(0.25D * width), height);
helpMessage.start((int)(0.25D * width), height);
}
private void resetSize(int width, int height) {
setPreferredSize(new Dimension(width, height));
}
}
|
package com.twitter.challenge.repo;
import com.google.gson.annotations.SerializedName;
public class WeatherResponse {
/**
* coord : {"lon":-122.42,"lat":37.77}
* weather : {"temp":14.77,"pressure":1007,"humidity":85}
* wind : {"speed":0.51,"deg":284}
* rain : {"3h":1}
* clouds : {"cloudiness":65}
* name : San Francisco
*/
private CoordBean coord;
private WeatherBean weather;
private WindBean wind;
private RainBean rain;
private CloudsBean clouds;
private String name;
public CoordBean getCoord() {
return coord;
}
public void setCoord(CoordBean coord) {
this.coord = coord;
}
public WeatherBean getWeather() {
return weather;
}
public void setWeather(WeatherBean weather) {
this.weather = weather;
}
public WindBean getWind() {
return wind;
}
public void setWind(WindBean wind) {
this.wind = wind;
}
public RainBean getRain() {
return rain;
}
public void setRain(RainBean rain) {
this.rain = rain;
}
public CloudsBean getClouds() {
return clouds;
}
public void setClouds(CloudsBean clouds) {
this.clouds = clouds;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static class CoordBean {
/**
* lon : -122.42
* lat : 37.77
*/
private double lon;
private double lat;
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
}
public static class WeatherBean {
/**
* temp : 14.77
* pressure : 1007
* humidity : 85
*/
private double temp;
private int pressure;
private int humidity;
public double getTemp() {
return temp;
}
public void setTemp(double temp) {
this.temp = temp;
}
public int getPressure() {
return pressure;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
public int getHumidity() {
return humidity;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
}
public static class WindBean {
/**
* speed : 0.51
* deg : 284
*/
private double speed;
private int deg;
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public int getDeg() {
return deg;
}
public void setDeg(int deg) {
this.deg = deg;
}
}
public static class RainBean {
/**
* 3h : 1
*/
@SerializedName("3h")
private int _$3h;
public int get_$3h() {
return _$3h;
}
public void set_$3h(int _$3h) {
this._$3h = _$3h;
}
}
public static class CloudsBean {
/**
* cloudiness : 65
*/
private int cloudiness;
public int getCloudiness() {
return cloudiness;
}
public void setCloudiness(int cloudiness) {
this.cloudiness = cloudiness;
}
}
}
|
package la.opi.verificacionciudadana.util;
import android.content.Context;
import android.location.LocationManager;
import android.widget.Toast;
/**
* Created by Jhordan on 25/03/15.
*/
public class LocationStatus {
public static Boolean locationStatus(Context context) {
try {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(context, "error inesperado gps", Toast.LENGTH_LONG).show();
}
return false;
}
}
|
public class WorkingWithParticles extends BaseGameActivity {
//====================================================
// CONSTANTS
//====================================================
public static final int WIDTH = 800;
public static final int HEIGHT = 480;
//====================================================
// VARIABLES
//====================================================
private Scene mScene;
private Camera mCamera;
// Particle texture region
private ITextureRegion mParticleTextureRegion;
//====================================================
// CREATE ENGINE OPTIONS
//====================================================
@Override
public EngineOptions onCreateEngineOptions() {
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new FillResolutionPolicy(), mCamera);
return engineOptions;
}
//====================================================
// CREATE RESOURCES
//====================================================
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
BuildableBitmapTextureAtlas texture = new BuildableBitmapTextureAtlas(mEngine.getTextureManager(), 32, 32, TextureOptions.BILINEAR);
mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(texture, getAssets(), "marble.png");
texture.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
texture.load();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
//====================================================
// CREATE SCENE
//====================================================
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
//====================================================
// POPULATE SCENE
//====================================================
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
// Create the particle emitter
PointParticleEmitter particleEmitter = new PointParticleEmitter(0, 0);
// Create the particle system
SpriteParticleSystem particleSystem = new SpriteParticleSystem(particleEmitter, 10, 20, 200, mParticleTextureRegion, mEngine.getVertexBufferObjectManager());
// Setup particle initializers
particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-50, 50, -10, -400));
particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(10, 15));
// Setup particle modifiers
particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(3, 6, 0.2f, 2f, 0.2f, 2f));
// Set the position in which particles will spawn
particleEmitter.setCenter(WIDTH / 2, HEIGHT);
// Attach our particle system to the scene
mScene.attachChild(particleSystem);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
|
package conferenceplanner;
import org.junit.Test;
import static org.junit.Assert.*;
public class _ConferenceTest {
// A conference can contain multiple tracks
public void conferenceCanContainMultipleTracksTest() {
Conference conference = new Conference();
}
}
|
package to;
import annotation.TestAnnotation;
public class ToWithNoEmptyConstructor {
@TestAnnotation(name="name")
private CharSequence field;
public ToWithNoEmptyConstructor(String name) {
this.field = name;
}
public CharSequence getName() {
return this.field;
}
@Override
public String toString() {
return String.format("ToWithAnnotation [name=%s]", field);
}
public static ToWithNoEmptyConstructor withName(String name) {
return new ToWithNoEmptyConstructor(name);
}
}
|
/**
*
*/
package simplejava.nio.channel;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
/**
* @title PipeTest
*/
public class PipeTest {
public static void main(String[] args) throws IOException, InterruptedException {
Pipe pipe = Pipe.open();
ReadableByteChannel in = pipe.source();
WritableByteChannel out = Channels.newChannel (System.out);
ByteBuffer buff = ByteBuffer.allocate(100);
Thread th = new Worker(pipe.sink(), 3);
th.start();
while(in.read(buff) > 0) {
buff.flip();
out.write(buff);
buff.clear();
}
out.close();
in.close();
}
static class Worker extends Thread {
private String[] str = {
"No good deed goes unpunished",
"To be, or what?",
"No matter where you go, there you are",
"Just say \"Yo\"",
"My karma ran over my dogma"
};
private Random rand = new Random();
private WritableByteChannel channel;
private int reps;
Worker(WritableByteChannel channel, int reps) {
this.channel = channel;
this.reps = reps;
}
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(100);
try {
for (int i = 0; i < this.reps; i++) {
doSomeWork(buffer);
// channel may not take it all at once
while (channel.write(buffer) > 0) {
// empty }
}
}
this.channel.close();
} catch (Exception e) {
// easy way out; this is demo code
e.printStackTrace();
}
}
private void doSomeWork(ByteBuffer buffer) {
int product = rand.nextInt(str.length);
buffer.clear();
buffer.put(str[product].getBytes());
buffer.put("\r\n".getBytes());
buffer.flip();
}
}
}
|
package participate;
import java.sql.Connection;
import java.sql.DriverManager;
public class participate {
public static void main(String[] args) {
Connection con = null;
String className="org.gjt.mm.mysql.Driver";
String url ="jdbc:mysql://localhost:3306/shxdb?useSSL=false&useUnicode=true&characterEncoding=euckr";
String user ="root2";
String passwd ="1120";
try {
Class.forName(className);
con=DriverManager.getConnection(url, user, passwd);
System.out.println("Connect Success!");
} catch(Exception e) {
System.out.println("Connect Failed!");
e.printStackTrace();
} finally {
try {
if(con!=null && !con.isClosed()) {
con.close();
}
}catch(Exception e) {
e.printStackTrace();
}
}
// TODO Auto-generated method stub
}
}
|
package zxn.web.funtions;
import zxn.domain.Category;
import zxn.service.BusinessService;
import zxn.service.impl.BusinessServiceImpl;
public class MyFuntion {
public static String getCategoryName(String category){
BusinessService s = new BusinessServiceImpl();
Category c = s.findCategoryById(category);
if (c!=null) {
return c.getName();
}
return "";
}
}
|
package Intrumentos_Virtuales;
import java.awt.*;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.MeterInterval;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.data.Range;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.DefaultValueDataset;
import org.jfree.data.general.ValueDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class Barometro extends ApplicationFrame {
private static DefaultValueDataset dataset;
public JFreeChart chart;
public Barometro(String titulo, Double dato) {
super(titulo);
JPanel chartPanel = createDemoPanel(dato, titulo);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
}
private static JFreeChart createChart(ValueDataset dataset,String titulo) {
MeterPlot plot = new MeterPlot(dataset);
plot.setRange(new Range(980, 1080));
/* plot.addInterval(new MeterInterval("Alto", new Range(0.0,1080),
Color.RED, new BasicStroke(1.0f), Color.GRAY));*/
/*plot.addInterval(new MeterInterval("Alto", new Range(980.0,1080),
Color.RED, new BasicStroke(1.0f), Color.GRAY));
plot.addInterval(new MeterInterval("Alto", new Range(1080.0,2000),
Color.RED, new BasicStroke(1.0f), Color.GRAY));*/
/*plot.addInterval(new MeterInterval("High", new Range(180.0, 280.0)));
plot.addInterval(new MeterInterval("High", new Range(280.0, 380.0)));
plot.addInterval(new MeterInterval("High", new Range(380.0, 480.0)));
plot.addInterval(new MeterInterval("High", new Range(480.0, 580.0)));
plot.addInterval(new MeterInterval("High", new Range(580.0, 680.0)));
plot.addInterval(new MeterInterval("High", new Range(680.0, 780.0)));
plot.addInterval(new MeterInterval("High", new Range(780.0, 880.0)));
plot.addInterval(new MeterInterval("High", new Range(880.0, 980.0)));
plot.addInterval(new MeterInterval("High", new Range(980.0, 1080.0)));*/
//plot.setDialOutlinePaint(Color.RED);
plot.setMeterAngle(330);
plot.setForegroundAlpha(1.0F);
plot.setDialOutlinePaint(Color.blue);
plot.setUnits("mBar");
JFreeChart chart1 = new JFreeChart(titulo,
JFreeChart.DEFAULT_TITLE_FONT, plot, false);
return chart1;
}
/**
* Creates a panel for the demo (used by SuperDemo.java).
*
* @return A panel.
*/
public JPanel createDemoPanel(Double dato, String titulo) {
dataset = new DefaultValueDataset(dato);
chart = createChart(dataset, titulo);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new ChartPanel(chart));
return panel;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.mutabene.service.manager;
import cz.mutabene.model.entity.ArticleEntity;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.lucene.index.Term;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Property;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.stereotype.Service;
/**
*
* @author novakst6
*/
@Service("ArticleManager")
public class ArticleManager extends GenericManager<ArticleEntity> {
@PostConstruct
public void doIndex() throws InterruptedException{
Session session = sessionFactory.openSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer(ArticleEntity.class).startAndWait();
fullTextSession.close();
}
public List<ArticleEntity> findPageDeleted(int start, int page, Boolean deleted){
Session s = sessionFactory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Query q = s.createQuery("SELECT e FROM ArticleEntity as e WHERE e.deleted = :deleted");
q.setParameter("deleted", deleted);
q.setMaxResults(page);
q.setFirstResult(start);
List<ArticleEntity> list = q.list();
tx.commit();
return list;
} catch (Exception e) {
if(tx != null){
tx.rollback();
}
System.out.println("ERROR >> "+e.getMessage());
return new LinkedList<ArticleEntity>();
} finally {
if(s != null){
s.close();
}
}
}
public int getCountDeleted(Boolean deleted){
Session s = sessionFactory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Query q = s.createQuery("SELECT count(*) FROM ArticleEntity as e WHERE e.deleted = :deleted ");
q.setParameter("deleted", deleted);
List<Long> list = q.list();
Long count = list.get(0);
tx.commit();
return count.intValue();
} catch (Exception e) {
if(tx != null){
tx.rollback();
}
return 0;
} finally {
if(s != null){
s.close();
}
}
}
public List<ArticleEntity> findPageDeleteByUserIds(int start, int page, Boolean deleted, List<Long> userIds){
Session s = sessionFactory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Query q = s.createQuery("SELECT e FROM ArticleEntity as e WHERE e.deleted = :deleted AND e.author.id IN :(userIds)");
q.setParameter("deleted", deleted);
q.setParameterList("userIds", userIds);
q.setMaxResults(page);
q.setFirstResult(start);
List<ArticleEntity> list = q.list();
tx.commit();
return list;
} catch (Exception e) {
if(tx != null){
tx.rollback();
}
System.out.println("ERROR >> "+e.getMessage());
return new LinkedList<ArticleEntity>();
} finally {
if(s != null){
s.close();
}
}
}
public int getCountDeletedUserIds(Boolean deleted,List<Long> userIds){
Session s = sessionFactory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Query q = s.createQuery("SELECT count(*) FROM ArticleEntity as e WHERE e.deleted = :deleted AND e.author.id IN :(userIds)");
q.setParameter("deleted", deleted);
q.setParameterList("userIds", userIds);
List<Long> list = q.list();
Long count = list.get(0);
tx.commit();
return count.intValue();
} catch (Exception e) {
if(tx != null){
tx.rollback();
}
return 0;
} finally {
if(s != null){
s.close();
}
}
}
public List<ArticleEntity> findFullText(Boolean deleted, String keywords){
Session s = sessionFactory.openSession();
FullTextSession fullTextSession = Search.getFullTextSession(s);
Transaction tx = null;
try {
tx = fullTextSession.beginTransaction();
QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(ArticleEntity.class).get();
org.apache.lucene.search.Query query = qb.keyword().onFields("title","text","author.email","author.googleName").matching(keywords).createQuery();
Query q = fullTextSession.createFullTextQuery(query, ArticleEntity.class);
List<ArticleEntity> list = q.list();
List<ArticleEntity> filtered = new LinkedList<ArticleEntity>();
for(ArticleEntity a: list){
if(!a.getDeleted()){
filtered.add(a);
}
}
tx.commit();
return filtered;
} catch (Exception e) {
if(tx != null){
tx.rollback();
}
System.out.println("ERROR >> "+e.getMessage());
return new LinkedList<ArticleEntity>();
} finally {
if(s != null){
s.close();
}
}
}
}
|
package com.naztech.services;
public class InnerAnnomiousNestedClass {
/*
}
class NestedClass{
void fun() {
class LocalInnerClass{
void show() {
System.out.println("Is in LocalInnerClass");
}
}
}
void h() {
InnerClass k=new InnerClass();
}
public class InnerClass{
void show() {
System.out.println("Is In InnerClass");
}
}
}
*/
static String a=null;
static void d() {
System.out.println(a);
class b{
}
b n=new b();
}
}
|
package ch04;
public class ThreadExample3 {
public static void main(String[] args) {
Runnable task = ()->{
try {
while(true) {
System.out.println("Hello,Lambda Runnable!");
Thread.sleep(500);
}
}catch (InterruptedException e) {
System.out.println("I'm interrupted");
}
};
Thread thread = new Thread(task);
thread.start();
System.out.println("Hello! My Lambda Child!");
}
}
|
package com.lhx.shiro.demo.dao.auth;
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Repository;
import com.lhx.shiro.demo.domain.auth.Resource;
import com.lhx.shiro.demo.domain.auth.Role;
import com.lhx.shiro.demo.domain.auth.query.ResourceQuery;
@Repository
public interface ResourceMapper {
int deleteByPrimaryKey(Long id);
long insert(Resource entity);
Resource selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Resource entity);
Set<String> selectResourceUrlsByRoles(List<Role> roles);
long selectCountsBySelective(ResourceQuery query);
List<Resource> selectListBySelective(ResourceQuery query);
int delete(String resourceCode);
}
|
package com.smxknife.zookeeper.curator.v5.demo01;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.util.concurrent.TimeUnit;
/**
* @author smxknife
* 2020/9/22
*/
public class ListenerDemo {
public static void main(String[] args) throws InterruptedException {
CuratorFramework framework = CuratorFrameworkFactory.builder().connectString("localhost:2191")
.namespace("demo01")
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.build();
framework.start();
CuratorCache cache = CuratorCache.build(framework, "/");
cache.start();
cache.listenable().addListener(new NodeListener());
TimeUnit.HOURS.sleep(1);
}
}
|
/**
* @author Paweł Włoch ©SoftLab
* @date 25 sty 2019
*/
package com.softlab.ubscoding.webserver.test.service;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.softlab.ubscoding.webserver.service.XChangeService;
@RunWith(SpringRunner.class)
@ContextConfiguration
@TestPropertySource("classpath:application-test.properties")
public class XChangeServiceTest {
@Configuration
@ComponentScan(basePackages = "com.softlab.ubscoding.webserver.service", excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.softlab.ubscoding.webserver.service.AlertService.class))
static class Config {
}
@Autowired
private XChangeService xChangeService;
@Test
public void shouldConnectWithBitcoinAndReturnNotNullTicker() throws Exception {
Ticker ticker = xChangeService.getTickerForCurrencyPair(CurrencyPair.BTC_USD);
assertNotNull(ticker);
}
}
|
package com.mideas.rpg.v2.hud.instance;
import java.util.ArrayList;
import com.mideas.rpg.v2.utils.Frame;
public class InstanceMenuFrame extends Frame {
private InstanceCategoryButton selectedMenu;
private final Frame parentFrame;
private final ArrayList<InstanceCategoryButton> buttonList;
public InstanceMenuFrame(String name, Frame parentFrame)
{
super(name);
this.parentFrame = parentFrame;
this.buttonList = new ArrayList<InstanceCategoryButton>();
}
@Override
public void draw()
{
for (int i = 0; i < this.buttonList.size(); ++i)
this.buttonList.get(i).draw();
}
@Override
public boolean mouseEvent()
{
for (int i = 0; i < this.buttonList.size(); ++i)
if (this.buttonList.get(i).mouseEvent())
return (true);
return (false);
}
@Override
public boolean keyboardEvent()
{
for (int i = 0; i < this.buttonList.size(); ++i)
if (this.buttonList.get(i).keyboardEvent())
return (true);
return (false);
}
@Override
public void open()
{
mouseEvent();
}
@Override
public void close()
{
for (int i = 0; i < this.buttonList.size(); ++i)
this.buttonList.get(i).resetState();
}
@Override
public boolean isOpen()
{
return (false);
}
@Override
public void reset()
{
}
public InstanceCategoryButton getSelectedMenu()
{
return (this.selectedMenu);
}
public void setSelectedMenu(InstanceCategoryButton menu)
{
this.selectedMenu = menu;
}
@Override
public void shouldUpdateSize()
{
for (int i = 0; i < this.buttonList.size(); ++i)
this.buttonList.get(i).shouldUpdateSize();
}
public void addButton(InstanceCategoryButton button)
{
button.setX(InstanceCategoryButton.BUTTON_X_OFFSET);
button.setY(InstanceCategoryButton.BUTTON_Y_DEFAULT_OFFSET + this.buttonList.size() * InstanceCategoryButton.BUTTON_Y_OFFSET);
this.buttonList.add(button);
if (this.buttonList.size() == 1)
this.selectedMenu = button;
}
@Override
public void updateSize()
{
}
}
|
package main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Fixer
{
//Removes triangles that are at the same spot
public static ArrayList<String> fixOBJ(ArrayList<String> rawFile)
{
String material = "";
ArrayList<String> verticies = new ArrayList<String>();
ArrayList<String> textures = new ArrayList<String>();
ArrayList<String> normals = new ArrayList<String>();
ArrayList<String> faces = new ArrayList<String>();
ArrayList<Triangle> triList = new ArrayList<Triangle>();
int size = rawFile.size();
for(int i = 0; i < size; i++)
{
String currLine = rawFile.get(i);
if(currLine.startsWith("mtllib"))
{
material = currLine;
}
else if(currLine.startsWith("v "))
{
verticies.add(currLine);
}
else if(currLine.startsWith("vn"))
{
normals.add(currLine);
}
else if(currLine.startsWith("vt"))
{
textures.add(currLine);
}
else if(currLine.startsWith("f")||currLine.startsWith("usemtl"))
{
faces.add(currLine);
if(currLine.startsWith("f"))
{
String[] arr = currLine.split(" ");
int v1 = Integer.parseInt(arr[1].substring(0, arr[1].indexOf("/")));
int v2 = Integer.parseInt(arr[2].substring(0, arr[2].indexOf("/")));
int v3 = Integer.parseInt(arr[3].substring(0, arr[3].indexOf("/")));
triList.add(new Triangle(v1, v2, v3));
}
}
}
for(int i = 0; i < faces.size(); i++)
{
String currLine = faces.get(i);
if(currLine.startsWith("f"))
{
String[] arr = currLine.split(" ");
int v1 = Integer.parseInt(arr[1].substring(0, arr[1].indexOf("/")));
int v2 = Integer.parseInt(arr[2].substring(0, arr[2].indexOf("/")));
int v3 = Integer.parseInt(arr[3].substring(0, arr[3].indexOf("/")));
size = triList.size();
for(int c = 0; c < size; c++)
{
Triangle checkTri = triList.get(c);
if(v1 == checkTri.v1 &&
v2 == checkTri.v2 &&
v3 == checkTri.v3)
{
if(checkTri.used)
{
c = size;
faces.remove(i);
i--;
}
else
{
checkTri.used = true;
}
}
}
}
}
//assign all triangles using the same 3 vertex coordinates to use the same vertex index
for (int triIdx = 0; triIdx < faces.size(); triIdx++)
{
String tri = faces.get(triIdx);
if (tri.startsWith("f"))
{
String[] arr = tri.split(" ");
int v1 = Integer.parseInt(arr[1].substring(0, arr[1].indexOf("/")));
int v2 = Integer.parseInt(arr[2].substring(0, arr[2].indexOf("/")));
int v3 = Integer.parseInt(arr[3].substring(0, arr[3].indexOf("/")));
int newv1 = -1;
int newv2 = -1;
int newv3 = -1;
String[] vertex1 = verticies.get(v1-1).split(" ");
float x1 = Float.parseFloat(vertex1[1]);
float y1 = Float.parseFloat(vertex1[2]);
float z1 = Float.parseFloat(vertex1[3]);
String[] vertex2 = verticies.get(v2-1).split(" ");
float x2 = Float.parseFloat(vertex2[1]);
float y2 = Float.parseFloat(vertex2[2]);
float z2 = Float.parseFloat(vertex2[3]);
String[] vertex3 = verticies.get(v3-1).split(" ");
float x3 = Float.parseFloat(vertex3[1]);
float y3 = Float.parseFloat(vertex3[2]);
float z3 = Float.parseFloat(vertex3[3]);
for (int i = 0; i < verticies.size(); i++)
{
String[] thisVertex = verticies.get(i).split(" ");
float x = Float.parseFloat(thisVertex[1]);
float y = Float.parseFloat(thisVertex[2]);
float z = Float.parseFloat(thisVertex[3]);
if (x == x1 && y == y1 && z == z1)
{
newv1 = i+1;
}
if (x == x2 && y == y2 && z == z2)
{
newv2 = i+1;
}
if (x == x3 && y == y3 && z == z3)
{
newv3 = i+1;
}
}
String[] dat1 = arr[1].split("/");
String[] dat2 = arr[2].split("/");
String[] dat3 = arr[3].split("/");
faces.set(triIdx, "f "+
newv1+"/"+dat1[1]+"/"+dat1[2]+" "+
newv2+"/"+dat2[1]+"/"+dat2[2]+" "+
newv3+"/"+dat3[1]+"/"+dat3[2]);
}
}
//put all unused verticies at the origin
for (int i = 0; i < verticies.size(); i++)
{
int idxToLookFor = i+1;
//am i used by ANY triangle?
boolean used = false;
for (int t = 0; t < faces.size(); t++)
{
String tri = faces.get(t);
if (tri.startsWith("f"))
{
String[] arr = tri.split(" ");
int v1 = Integer.parseInt(arr[1].substring(0, arr[1].indexOf("/")));
int v2 = Integer.parseInt(arr[2].substring(0, arr[2].indexOf("/")));
int v3 = Integer.parseInt(arr[3].substring(0, arr[3].indexOf("/")));
if (v1 == idxToLookFor ||
v2 == idxToLookFor ||
v3 == idxToLookFor)
{
used = true;
break;
}
}
}
if (used == false)
{
verticies.set(i, "v 0 0 0");
}
}
ArrayList<String> newFile = new ArrayList<String>();
newFile.add(material);
while(verticies.size() > 0)
{
newFile.add(verticies.get(0));
verticies.remove(0);
}
while(textures.size() > 0)
{
newFile.add(textures.get(0));
textures.remove(0);
}
while(normals.size() > 0)
{
newFile.add(normals.get(0));
normals.remove(0);
}
while(faces.size() > 0)
{
newFile.add(faces.get(0));
faces.remove(0);
}
return newFile;
}
//Organize the materials so that all the triangles using the same material
//are part of the same group
public static void organizeOBJ(ArrayList<String> rawFile)
{
String materialFile = "";
String currMaterial = "";
ArrayList<String> verticies = new ArrayList<String>();
ArrayList<String> textures = new ArrayList<String>();
ArrayList<String> normals = new ArrayList<String>();
HashMap<String, ArrayList<String>> groupMap = new HashMap<String, ArrayList<String>>();
int size = rawFile.size();
for(int i = 0; i < size; i++)
{
String currLine = rawFile.get(i);
if(currLine.startsWith("mtllib"))
{
materialFile = currLine;
}
else if(currLine.startsWith("v "))
{
verticies.add(currLine);
}
else if(currLine.startsWith("vn"))
{
normals.add(currLine);
}
else if(currLine.startsWith("vt"))
{
textures.add(currLine);
}
else if(currLine.startsWith("usemtl"))
{
String[] arr = currLine.split(" ");
currMaterial = arr[1];
if(!groupMap.containsKey(currMaterial))
{
ArrayList<String> faceGroup = new ArrayList<String>();
faceGroup.add(currLine);
groupMap.put(currMaterial, faceGroup);
}
}
else if(currLine.startsWith("f"))
{
groupMap.get(currMaterial).add(currLine);
}
}
rawFile.clear();
rawFile.add(materialFile);
while(verticies.size() > 0)
{
rawFile.add(verticies.get(0));
verticies.remove(0);
}
while(textures.size() > 0)
{
rawFile.add(textures.get(0));
textures.remove(0);
}
while(normals.size() > 0)
{
rawFile.add(normals.get(0));
normals.remove(0);
}
Iterator<String> keySetIterator = groupMap.keySet().iterator();
while(keySetIterator.hasNext())
{
String key = keySetIterator.next();
ArrayList<String> group = groupMap.get(key);
while(group.size() > 0)
{
rawFile.add(group.get(0));
group.remove(0);
}
}
}
//If there exist two different materials that use the same exact image for the texture,
//the materials will be merged into one material, and the references in the .obj will
//be updated to use this new material
public static void fixMaterials(ArrayList<String> rawOBJFile, ArrayList<String> rawMTLFile)
{
ArrayList<Material> matList = new ArrayList<Material>();
//Scan through material file and match the material names
//with their filenames
int size = rawMTLFile.size();
for(int i = 0; i < size; i++)
{
String currLine = rawMTLFile.get(i);
if(currLine.startsWith("newmtl"))
{
String[] arr = currLine.split(" ");
String name = arr[1];
matList.add(new Material(name));
}
else if(currLine.indexOf("map_Kd") >= 0)
{
String fileName = currLine.substring(currLine.indexOf("map_Kd")+7);
matList.get(matList.size()-1).fileName = fileName;
}
else if(currLine.indexOf("Ns ") >= 0)
{
matList.get(matList.size()-1).shineDamper = currLine;
String valueString = currLine.substring(currLine.indexOf("Ns ")+3);
valueString = valueString.trim();
float value = Float.parseFloat(valueString);
if (value <= 0)
{
matList.get(matList.size()-1).shineDamper = "Ns 20";
}
}
else if(currLine.indexOf("Ni ") >= 0)
{
matList.get(matList.size()-1).reflectivity = currLine;
}
else if(currLine.indexOf("Tr ") >= 0)
{
matList.get(matList.size()-1).transparency = currLine;
}
else if(currLine.indexOf("d ") >= 0)
{
matList.get(matList.size()-1).fakeLighting = currLine;
}
else if(currLine.indexOf("glow ") >= 0)
{
matList.get(matList.size()-1).glowAmount = currLine;
}
else if(currLine.indexOf("scrollX ") >= 0)
{
matList.get(matList.size()-1).scrollX = currLine;
}
else if(currLine.indexOf("scrollY ") >= 0)
{
matList.get(matList.size()-1).scrollY = currLine;
}
}
//filename to material
HashMap<String, Material> materialMap = new HashMap<String, Material>();
//material name to filename
HashMap<String, String> matNameMap = new HashMap<String, String>();
//Fill material map
for (Material mat : matList)
{
if (materialMap.containsKey(mat.fileName) == false)
{
materialMap.put(mat.fileName, mat);
}
matNameMap.put(mat.name, mat.fileName);
}
size = rawOBJFile.size();
for (int i = 0; i < size; i++)
{
String currLine = rawOBJFile.get(i);
if (currLine.startsWith("usemtl"))
{
String[] arr = currLine.split(" ");
String name = arr[1];
String fileName = "";
//search through entire matList until you find the image filename
//associated with your material name
fileName = matNameMap.get(name);
//now that you know what file you need for the image,
//set your new material name to the first one in the material
//array that uses the same image filename
rawOBJFile.remove(i);
rawOBJFile.add(i, "usemtl "+materialMap.get(fileName).name);
}
}
rawMTLFile.clear();
rawMTLFile.add("# Material Count: "+materialMap.size());
rawMTLFile.add("");
for (Map.Entry<String, Material> entry : materialMap.entrySet())
{
Material mat = entry.getValue();
rawMTLFile.add("newmtl " + mat.name);
rawMTLFile.add(mat.shineDamper);
rawMTLFile.add(mat.reflectivity);
rawMTLFile.add(mat.transparency);
rawMTLFile.add(mat.fakeLighting);
rawMTLFile.add(mat.scrollX);
rawMTLFile.add(mat.scrollY);
rawMTLFile.add("map_Kd " + mat.fileName);
rawMTLFile.add("");
}
}
//removes a material from a obj and mtl
public static void removeMaterial(ArrayList<String> obj, ArrayList<String> mtl, String matToRemove)
{
String currMat = "";
for(int i = 0; i < obj.size(); i++)
{
String currLine = obj.get(i);
if(currLine.startsWith("usemtl"))
{
String[] arr = currLine.split(" ");
currMat = arr[1];
if(currMat.equals(matToRemove))
{
obj.remove(i);
i--;
}
}
else if(currLine.startsWith("f"))
{
if(currMat.equals(matToRemove))
{
obj.remove(i);
i--;
}
}
}
currMat = "";
for(int i = 0; i < mtl.size(); i++)
{
String currLine = mtl.get(i);
if(currLine.contains("newmtl"))
{
String[] arr = currLine.trim().split(" ");
currMat = arr[1];
if(currMat.equals(matToRemove))
{
mtl.remove(i);
i--;
}
}
else if(currMat.equals(matToRemove))
{
mtl.remove(i);
i--;
}
}
}
//Changes material names that start with a prefix to a new name
public static ArrayList<String> changeMaterials(ArrayList<String> file, String prefix, String newName)
{
String currMat = "";
for(int i = 0; i < file.size(); i++)
{
String currLine = file.get(i);
if(currLine.startsWith("usemtl"))
{
String[] arr = currLine.split(" ");
currMat = arr[1];
if(currMat.startsWith(prefix))
{
file.set(i, arr[0]+" "+newName);
}
}
}
return file;
}
//Changes material filenames that are equal to an old name to a new name
public static ArrayList<String> changeMaterialsFilenames(ArrayList<String> mtl, String newName, String oldName)
{
String currMat = "";
for (int i = 0; i < mtl.size(); i++)
{
String currLine = mtl.get(i);
if (currLine.contains("map_Kd"))
{
String[] arr = currLine.split(" ");
currMat = arr[1];
if (currMat.equals(oldName))
{
mtl.set(i, arr[0]+" "+newName);
}
}
}
return mtl;
}
/*
public static ArrayList<String> changeMaterialsName(ArrayList<String> obj, ArrayList<String> mtl, String newName, String oldName)
{
String currMat = "";
for (int i = 0; i < obj.size(); i++)
{
String currLine = obj.get(i);
if (currLine.startsWith("usemtl"))
{
String[] arr = currLine.split(" ");
currMat = arr[1];
for (int c = 0; c < mtl.size(); c++)
{
String mtlLine = mtl.get(c);
String[] dat = mtlLine.split(" ");
if (dat.length >= 2)
{
if (dat[0].equals("newmtl") && dat[1].equals(currMat))
{
for (c = c+1; c < mtl.size(); c++)
{
String mtlLine2 = mtl.get(c);
String[] dat2 = mtlLine2.split(" ");
if (dat2[0].contains("map_Kd") && dat2[1].equals(oldName))
{
}
}
}
}
}
}
}
return file;
}
*/
//Removes everything after and including # per line
public static ArrayList<String> removeComments(ArrayList<String> file)
{
for (int i = 0; i < file.size(); i++)
{
String currLine = file.get(i);
if (currLine.contains("#"))
{
String[] arr = currLine.split("#");
if (currLine.indexOf("#") == 0)
{
file.set(i, "");
}
else
{
file.set(i, arr[0]);
}
}
}
return file;
}
}
|
package com.tencent.mm.plugin.subapp.ui.voicetranstext;
import com.tencent.mm.sdk.platformtools.al.a;
import com.tencent.mm.sdk.platformtools.x;
class VoiceTransTextUI$4 implements a {
final /* synthetic */ int oqo;
final /* synthetic */ VoiceTransTextUI ouz;
VoiceTransTextUI$4(VoiceTransTextUI voiceTransTextUI, int i) {
this.ouz = voiceTransTextUI;
this.oqo = i;
}
public final boolean vD() {
if (!VoiceTransTextUI.m(this.ouz)) {
x.d("MicroMsg.VoiceTransTextUI", "timmer get, delay:%d", new Object[]{Integer.valueOf(this.oqo)});
VoiceTransTextUI.c(this.ouz, VoiceTransTextUI.a.ouI);
}
return false;
}
}
|
package test15PiDataProvidersEx;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Optional;
import org.testng.annotations.Test;
import test15PiDataProvidersEx.ExcelUtils;
import util.BaseTest;
public class Ex5readExcelGoogle extends BaseTest{
@DataProvider(name = "excelData")
public static Object[][] Authentication() throws Exception {
return ExcelUtils.getTableArray("C://test//data.xlsx", "output");
}
@Test(dataProvider = "excelData")
public void Registration_data(String name, @Optional("")String pass,@Optional("")String status ) throws Exception {
driver.get("https://www.google.com");
WebElement searchText = driver.findElement(By.name("q"));
searchText.sendKeys(name);
searchText.submit();
Thread.sleep(5000);
}
}
|
package com.tencent.mm.plugin.mmsight.ui;
import com.tencent.mm.api.d;
import com.tencent.mm.api.l;
import com.tencent.mm.sdk.platformtools.x;
class a$5 implements l {
final /* synthetic */ a lpk;
a$5(a aVar) {
this.lpk = aVar;
}
public final void a(d dVar) {
x.i("MicroMsg.MMSightVideoEditor", "photoEditor [onSelectedFeature] features:%s", new Object[]{dVar.name()});
if (dVar == d.bwS) {
a.a(this.lpk);
}
}
public final void a(d dVar, int i) {
x.i("MicroMsg.MMSightVideoEditor", "photoEditor [onSelectedDetailFeature] features:%s index:%s", new Object[]{dVar.name(), Integer.valueOf(i)});
}
public final void aD(boolean z) {
if (z) {
this.lpk.bGc.showVKB();
} else {
this.lpk.bGc.hideVKB(this.lpk.loY);
}
}
}
|
/**
*
*/
/**
* @author Darkaz
*
*/
public class prob1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int res = 0;
for (int i = 0; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0)
res = res + i;
}
System.out.println(res);
int j = 4%3 ;
System.out.println(j);
}
}
|
package edu.self.engine;
public class Controller {
private Engine engine;
public Controller(Engine engine) {
this.engine = engine;
}
}
|
package subjects.sample;
import java.util.LinkedList;
/**
* @description: 二叉树
* @author: dsy
* @date: 2020/4/10 13:22
*/
public class BinaryTree<T> {
/**
* 先序创建二叉树 返回根节点
*/
public TreeNode<T> createTreePre(LinkedList<T> dataList) {
TreeNode<T> root = null;
T data = dataList.removeFirst();
if (data != null) {
root = new TreeNode<T>(data, null, null);
root.leftChild = createTreePre(dataList);
root.rightChild = createTreePre(dataList);
}
return root;
}
/**
* 先序遍历二叉树(递归)
*/
public void printTreePreRecur(TreeNode root) {
if (root != null) {
System.out.println(root.data);
printTreePreRecur(root.leftChild);
printTreePreRecur(root.rightChild);
}
}
/**
* 中序遍历(递归)
*/
public void printTreeMidRecur(TreeNode root) {
if (root != null) {
printTreeMidRecur(root.leftChild);
System.out.println(root.data);
printTreeMidRecur(root.rightChild);
}
}
/**
* 后序遍历(递归)
*/
public void printTreeLastRecur(TreeNode root) {
if (root != null) {
printTreeLastRecur(root.leftChild);
printTreeLastRecur(root.rightChild);
System.out.println(root.data);
}
}
/**
* 先序遍历二叉树(非递归)
*/
public void printTreePreUnrecur(TreeNode root) {
//p为当前节点
TreeNode p = root;
LinkedList<TreeNode> stack = new LinkedList<>();
//栈不为空时,或者p不为空时循环
while (p != null || !stack.isEmpty()) {
}
}
/**
* 树节点类
*/
class TreeNode<T> {
public T data;
public TreeNode<T> leftChild;
public TreeNode<T> rightChild;
public TreeNode(T data, TreeNode<T> leftChild, TreeNode<T> rightChild) {
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public TreeNode<T> getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode<T> leftChild) {
this.leftChild = leftChild;
}
public TreeNode<T> getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode<T> rightChild) {
this.rightChild = rightChild;
}
}
}
|
package com.example.pramath.textadventure2.MapData;
import com.example.pramath.textadventure2.Coordinate;
public class Map {
// Origin is top left corner
private final Coordinate bounds;
private final MapElement[][] map;
public Map() {
this.bounds = new Coordinate();
map = new MapElement[0][0];
}
Map(MapElement[][] mapArray) {
this.bounds = new Coordinate(mapArray[0].length, mapArray.length);
map = mapArray;
}
public boolean isValidSpotToMoveTo(Coordinate position) {
int x = position.getX();
int y = position.getY();
MapElement cell = map[x][y];
return cell instanceof Floor || (cell instanceof Door && !((Door) cell).isLocked());
}
public String toPlainText() {
int height = bounds.getY();
int width = bounds.getX();
StringBuilder mapString = new StringBuilder();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
MapElement element = map[i][j];
if (element instanceof Wall) {
mapString.append('X');
} else if (element instanceof Door) {
mapString.append(((Door)element).isLocked() ? 'L' : 'U');
} else if (element instanceof Table) {
mapString.append('T');
} else {
mapString.append(' ');
}
}
}
return mapString.toString();
}
}
|
package com.zznode.opentnms.isearch.otnRouteService.manage;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import com.zznode.opentnms.isearch.otnRouteService.service.BusiAnalyser;
public class MyKeyedPoolableObjectFactory implements KeyedPoolableObjectFactory {
// 创建对象实例。同时可以分配这个对象适用的资源。
public Object makeObject(Object key) throws Exception {
return new BusiAnalyser((String)key);
}
public void activateObject(Object arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
}
public void destroyObject(Object arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
}
public void passivateObject(Object arg0, Object arg1) throws Exception {
// TODO Auto-generated method stub
}
public boolean validateObject(Object arg0, Object arg1) {
// TODO Auto-generated method stub
return false;
}
}
|
package task89;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* @author Igor
*/
public class Test89 {
@Test
public void testToInteger() {
assertEquals(8, Roman.toInteger("VIII"));
assertEquals(9, Roman.toInteger("IX"));
assertEquals(4444, Roman.toInteger("MMMMCDXLIV"));
assertEquals(49, Roman.toInteger("XLIX"));
}
@Test
public void testToRoman(){
assertEquals("VIII", Roman.toRoman(8));
assertEquals("IX", Roman.toRoman(9));
assertEquals("XLIV", Roman.toRoman(44));
assertEquals("MCMXLIV", Roman.toRoman(1944));
assertEquals("MCMXL", Roman.toRoman(1940));
System.out.println(Roman.toRoman(60000));
}
}
|
/*
* 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 remise;
import java.util.Scanner;
/**
*
* @author 80010-92-01
*/
public class Remise {
public static void main(String[] args) {
float pu;
int qte;
float tva = 1.2f;
float total;
float port;
float remise;
Scanner lectureClavier = new Scanner(System.in);
System.out.print("Entrez le prix unitaire : ");
pu = lectureClavier.nextInt();
System.out.print("Entrez la quantité : ");
qte = lectureClavier.nextInt();
total = pu * qte * tva;
port = total * 2f /100f;
System.out.println(total);
System.out.println(port);
if( total < 500f ){ port = total * 2f /100f;
if ( port < 6f ){ port = 6f; }
else { }}
else { port = 0f; }
if ( total>100f && total<200){ remise = (total * 5/100); total = total - remise; }
if (total > 200f){ remise = (total * 10/100); total = total - remise; }
System.out.println(port);
System.out.println(total);
}
}
|
import java.util.Scanner;
public class DhonisBattingPosition {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("The number of the over when the last wicket fell:");
int number_of_the_over=sc.nextInt();
System.out.println("The ball in over when the wicket fell:");
int ball_in_the_over=sc.nextInt();
System.out.println("Total overs in the innings:");
int total_overs=sc.nextInt();
float result=((number_of_the_over*6)+ball_in_the_over)*100f;
float result2= (result/(total_overs*6))/100f;
System.out.println(result2);
if(result2>=0.75) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
|
package Management.HumanResources.Staff;
import Management.HumanResources.DepartmentType;
import Management.HumanResources.FinancialSystem.Permission;
import Management.HumanResources.LeaveRequest;
import Presentation.Protocol.IOManager;
/**
* 会计类
* @author 尚丙奇
* @since 2021-10-16 14:00
*/
public class Accountant extends Staff implements Permission {
/**
* 会计类的构造函数,在创建时设置其所属的部门。
*/
public Accountant(){
setDepartment(DepartmentType.Finance);
}
/**
* 员工无法处理自己的请假请求,通过责任链传递给其直接的leader
* @param request 员工的请假请求
*/
@Override
public void handleRequest(LeaveRequest request) {
leader.handleRequest(request);
}
/**
* 访问财务系统
* @author 尚丙奇
* @since 2021-10-16 14:00
*/
public void accessFinancialSystem() {
IOManager.getInstance().print(
"财务处员工" + name + "访问了财务系统。",
"財務處員工" + name + "訪問了財務系統。",
"Employee of the financial department " + name + "accessed the financial system.");
}
}
|
package com.dataflow.exportable;
import com.github.javaparser.ast.expr.SimpleName;
import java.util.ArrayList;
import java.util.List;
public class TemplateClass {
public SimpleName className;
public String archetype;
public String templateId;
public List<TemplateField> fields;
public boolean isCompositionBase;
public boolean isEnumValueSet;
public TemplateClass(SimpleName className)
{
this.className = className;
this.fields = new ArrayList<>();
this.isCompositionBase = this.className.toString().endsWith("Composition");
this.isEnumValueSet = false;
}
public String toString(){
StringBuilder output = new StringBuilder("Class: " + this.className + "\nFields: ");
for(TemplateField field: this.fields)
{
output.append(field.toString() + "\n");
}
return output.toString();
}
}
|
package com.text.mytab;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TabHost.OnTabChangeListener;
public class IndexActicity extends ActivityGroup {
private int index_tab = 0;
private TabWidget tabWidget;
View tab1;
View tab2;
View tab4;
View tab3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.index_layout);
DisplayMetrics dm = new DisplayMetrics();
Log.i("adfa","dfadf");
getWindowManager().getDefaultDisplay().getMetrics(dm);
Constant.WIDTH = dm.widthPixels;
Constant.HEIGHT= dm.heightPixels;
//TabHost t =getTabHost();
TabHost t = (TabHost)findViewById(R.id.t1);
t.setBackgroundDrawable(getResources().getDrawable(R.drawable.inde_bg));
t.setup(this.getLocalActivityManager());
t.setPadding(0, 0, 0, 0);
tabWidget = t.getTabWidget();
LayoutInflater fi = LayoutInflater.from(IndexActicity.this);
View view = fi.inflate(R.layout.tab_layout, null);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.tablayout);
tab1 = view.findViewById(R.id.tab1);
tab2 = view.findViewById(R.id.tab2);
tab3 = view.findViewById(R.id.tab3);
tab4 = view.findViewById(R.id.tab4);
ll.removeAllViews();
t.addTab(t.newTabSpec("1").setIndicator(tab1
).setContent(
new Intent(IndexActicity.this,
TabActivity1.class)));
t.addTab(t.newTabSpec("2").setIndicator(tab2
).setContent(
new Intent(IndexActicity.this,
TabActivity2.class)));
t.addTab(t.newTabSpec("3").setIndicator(tab3
).setContent(
new Intent(IndexActicity.this,
TabActivity3.class)));
t.addTab(t.newTabSpec("4").setIndicator(tab4).setContent(
new Intent(IndexActicity.this, TabActivity4.class)));
tabWidget.setBackgroundColor(getResources().getColor(R.color.alpha_00));
tabWidget.setBaselineAligned(true);
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.menu_bg));
for (int i = 0; i < tabWidget.getChildCount(); i++) {
tabWidget.getChildAt(i).getLayoutParams().width = Constant.WIDTH / 4;
tabWidget.getChildAt(i).getLayoutParams().height=50;
}
t.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
tabChanged(tabId);
}
});
}
//捕获tab变化事件
public void tabChanged(String tabId) {
if (index_tab != (Integer.valueOf(tabId) - 1)) {
tabWidget.getChildAt(Integer.valueOf(tabId) - 1)
.setBackgroundDrawable(
getResources().getDrawable(R.drawable.menu_bg));
tabWidget.getChildAt(index_tab).setBackgroundDrawable(null);
index_tab = Integer.valueOf(tabId) - 1;
}
}
}
|
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import java.util.*;
import java.io.*;
/*
* @Xtest
* @summary compiler accepts all values
* @author Mahmood Ali
* @author Yuri Gaevsky
* @compile TargetTypes.java
*/
@Target({TYPE_USE, TYPE_PARAMETER, TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface A {}
/** wildcard bound */
class T0x1C {
void m0x1C(List<? extends @A String> lst) {}
}
/** wildcard bound generic/array */
class T0x1D<T> {
void m0x1D(List<? extends @A List<int[]>> lst) {}
}
/** typecast */
class T0x00 {
void m0x00(Long l1) {
Object l2 = (@A Long) l1;
}
}
/** typecast generic/array */
class T0x01<T> {
void m0x01(List<T> list) {
List<T> l = (List<@A T>) list;
}
}
/** instanceof */
class T0x02 {
boolean m0x02(String s) {
return (s instanceof @A String);
}
}
/** object creation (new) */
class T0x04 {
void m0x04() {
new @A ArrayList<String>();
}
}
/** local variable */
class T0x08 {
void m0x08() {
@A String s = null;
}
}
/** method parameter generic/array */
class T0x0D {
void m0x0D(HashMap<@A Object, List<@A List<@A Class>>> s1) {}
}
/** method receiver */
class T0x06 {
void m0x06(@A T0x06 this) {}
}
/** method return type generic/array */
class T0x0B {
Class<@A Object> m0x0B() { return null; }
}
/** field generic/array */
class T0x0F {
HashMap<@A Object, @A Object> c1;
}
/** method type parameter */
class T0x20<T, U> {
<@A T, @A U> void m0x20() {}
}
/** class type parameter */
class T0x22<@A T, @A U> {
}
/** class type parameter bound */
class T0x10<T extends @A Object> {
}
/** method type parameter bound */
class T0x12<T> {
<T extends @A Object> void m0x12() {}
}
/** class type parameter bound generic/array */
class T0x11<T extends List<@A T>> {
}
/** method type parameter bound generic/array */
class T0x13 {
static <T extends Comparable<@A T>> T m0x13() {
return null;
}
}
/** class extends/implements generic/array */
class T0x15<T> extends ArrayList<@A T> {
}
/** type test (instanceof) generic/array */
class T0x03<T> {
void m0x03(T typeObj, Object obj) {
boolean ok = obj instanceof String @A [];
}
}
/** object creation (new) generic/array */
class T0x05<T> {
void m0x05() {
new ArrayList<@A T>();
}
}
/** local variable generic/array */
class T0x09<T> {
void g() {
List<@A String> l = null;
}
void a() {
String @A [] as = null;
}
}
/** type argument in constructor call generic/array */
class T0x19 {
<T> T0x19() {}
void g() {
new <List<@A String>> T0x19();
}
}
/** type argument in method call generic/array */
class T0x1B<T> {
void m0x1B() {
Collections.<T @A []>emptyList();
}
}
/** type argument in constructor call */
class T0x18<T> {
<T> T0x18() {}
void m() {
new <@A Integer> T0x18();
}
}
/** type argument in method call */
class T0x1A<T,U> {
public static <T, U> T m() { return null; }
static void m0x1A() {
T0x1A.<@A Integer, @A Short>m();
}
}
/** class extends/implements */
class T0x14 extends @A Object implements @A Serializable, @A Cloneable {
}
/** exception type in throws */
class T0x16 {
void m0x16() throws @A Exception {}
}
/** resource variables **/
class ResourceVariables {
void m() throws Exception {
try (@A InputStream is = new @A FileInputStream("x")){}
}
}
/** exception parameters **/
class ExceptionParameters {
void multipleExceptions() {
try {
new Object();
} catch (@A Exception e) {}
try {
new Object();
} catch (@A Exception e) {}
try {
new Object();
} catch (@A Exception e) {}
}
}
|
/*
* Copyright 2015 The Apache Software Foundation.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza.implementation.literal;
import org.apache.clerezza.Literal;
/**
* @author developer
*/
public abstract class AbstractLiteral implements Literal {
@Override
public int hashCode() {
int result = 0;
if (getLanguage() != null) {
result = getLanguage().hashCode();
}
result += getLexicalForm().hashCode();
result += getDataType().hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Literal) {
Literal other = (Literal) obj;
if (getLanguage() == null) {
if (other.getLanguage() != null) {
return false;
}
} else {
if (!getLanguage().equals(other.getLanguage())) {
return false;
}
}
boolean res = getDataType().equals(other.getDataType()) && getLexicalForm().equals(other.getLexicalForm());
return res;
} else {
return false;
}
}
}
|
package com.websharp.dwtz.activity.user;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.websharp.dwtz.R;
import com.websharp.dwtz.activity.BaseActivity;
import com.websharp.dwtz.activity.invalid.ActivityInvalidList;
import com.websharp.dwtz.activity.main.MainActivity;
import com.websharp.dwtz.activity.order.ActivityAddOrder;
import com.websharp.dwtz.activity.order.ActivityOrderList;
import com.websharp.dwtz.activity.web.ActivityWebview;
import com.websharp.dwtz.dao.EntityUser;
import com.websharp.dwtz.data.GlobalData;
import com.websharp.dwtz.http.AsyncHttpCallBack;
import com.websharp.dwtz.http.SJECHttpHandler;
import com.websharputil.code.DescUtil;
import com.websharputil.common.AppData;
import com.websharputil.common.LogUtil;
import com.websharputil.common.PrefUtil;
import com.websharputil.common.Util;
import com.websharputil.json.JSONUtils;
import com.websharputil.widget.ThumbImageView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ActivityLogin extends BaseActivity {
private TextView tv_regist;
private EditText et_username;
private EditText et_password;
private Button btn_login;
@Override
public void initLayout() {
setContentView(R.layout.activity_login);
// Intent intent = new Intent(
// android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// startActivity(intent);
}
@Override
public void init() {
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(this);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
@Override
public void bindData() {
initParam();
// et_username.setText("13771781982");
// et_password.setText("123456");
String prefUser = PrefUtil.getPref(ActivityLogin.this, "user", "");
if (!prefUser.isEmpty()) {
GlobalData.curUser = JSONUtils.fromJson(prefUser,
EntityUser.class);
et_username.setText(GlobalData.curUser.UserID);
et_password.setText(GlobalData.curUser.Password);
btn_login.performClick();
//Util.startActivity(ActivityLogin.this, MainActivity.class, true);
}
// et_username.setText("18934597841");
// et_password.setText("123456");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
// String username = et_username.getText().toString().trim();
// GlobalData.curUser = username;
// if(username.equals("1")){
// //门卫验货
// Util.startActivity(ActivityLogin.this, ActivityAddOrder.class,
// false);
// }else if(username.equals("2")){
// //卸货/屠宰
// Util.startActivity(ActivityLogin.this, ActivityOrderList.class,
// false);
// }else if(username.equals("3")){
// //销毁
// Util.startActivity(ActivityLogin.this, ActivityOrderList.class,
// false);
// }else{
// Util.startActivity(ActivityLogin.this, ActivityAddOrder.class,
// false);
// }
try {
AsyncLogin();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
AsyncHttpCallBack cb = new AsyncHttpCallBack() {
@Override
public void onSuccess(String response) {
super.onSuccess(response);
LogUtil.d("%s", response);
JSONObject obj;
try {
obj = new JSONObject(response);
if (obj.optString("result").equals("true")) {
String str = PrefUtil.getPref(ActivityLogin.this, "user",
"");
PrefUtil.setPref(ActivityLogin.this, "user", obj
.getJSONObject("data").toString());
GlobalData.curUser = JSONUtils.fromJson(
obj.getJSONObject("data").toString(),
EntityUser.class);
PrefUtil.setPref(ActivityLogin.this, "lastphone",
GlobalData.curUser.Telephone.trim());
Util.createToast(
ActivityLogin.this,R.string.common_login_success,
3000).show();
Util.startActivity(ActivityLogin.this, MainActivity.class, true);
} else {
Util.createToast(
ActivityLogin.this,
obj.optString("desc",
getString(R.string.common_login_failed)),
3000).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String message) {
super.onFailure(message);
LogUtil.d("%s", message);
}
};
private void AsyncLogin() throws Exception {
new SJECHttpHandler(cb, this).login(et_username.getText().toString()
.trim(), et_password.getText().toString().trim());
}
}
|
package com.yinghai.a24divine_user;
import android.content.Context;
import com.tencent.tinker.loader.app.TinkerApplication;
import static com.tencent.tinker.loader.shareutil.ShareConstants.TINKER_ENABLE_ALL;
/**
* Created by:fanson
* Created on:2017/9/28 14:52
* Describe:
*/
public class SampleApplication extends TinkerApplication {
public static Context context;
public SampleApplication() {
super(TINKER_ENABLE_ALL, "com.yinghai.a24divine_user.SampleApplicationLike",
"com.tencent.tinker.loader.TinkerLoader", false);
//参数解析
// 参数1:tinkerFlags 表示Tinker支持的类型 dex only、library only or all suuport,default: TINKER_ENABLE_ALL
// 参数2:delegateClassName Application代理类 这里填写你自定义的ApplicationLike
// 参数3:loaderClassName Tinker的加载器,使用默认即可
// 参数4:tinkerLoadVerifyFlag 加载dex或者lib是否验证md5,默认为false
}
/*@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}*/
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() { return context;}
}
|
package com.lingnet.vocs.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.lingnet.common.entity.BaseEntity;
@Table(name = "REFUND")
@Entity
public class Refund extends BaseEntity {
// 编号
private String code;
// 工单号
private String workOrderCode;
// 合同号
private String contractCode;
// 退款金额
private Double amount;
// 退款日期
private Date refundDate;
// 合作商客户标识
private String partnerOrCustomer;
// 收款方Id
private String partnerId;
// 收款方明细
private String partnerName;
// 收款方负责人姓名
private String contact;
// 负责人联系方式
private String phone;
// 备注
private String remark;
// 审核状态
private String verifyStatus;
// 发起退款的合作商
private String ownerId;
@Column(name = "code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name = "work_order_code")
public String getWorkOrderCode() {
return workOrderCode;
}
public void setWorkOrderCode(String workOrderCode) {
this.workOrderCode = workOrderCode;
}
@Column(name = "contract_code")
public String getContractCode() {
return contractCode;
}
public void setContractCode(String contractCode) {
this.contractCode = contractCode;
}
@Column(name = "amount")
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
@Column(name = "refund_date")
public Date getRefundDate() {
return refundDate;
}
public void setRefundDate(Date refundDate) {
this.refundDate = refundDate;
}
@Column(name = "partner_id")
public String getPartnerId() {
return partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
@Column(name = "contact")
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "remark")
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Column(name = "partner_or_customer")
public String getPartnerOrCustomer() {
return partnerOrCustomer;
}
public void setPartnerOrCustomer(String partnerOrCustomer) {
this.partnerOrCustomer = partnerOrCustomer;
}
@Transient
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
@Column(name = "verify_status")
public String getVerifyStatus() {
return verifyStatus;
}
public void setVerifyStatus(String verifyStatus) {
this.verifyStatus = verifyStatus;
}
@Column(name = "owner_id")
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
}
|
package com.george.projectmanagement.repository;
import com.george.projectmanagement.model.Project;
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.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@SpringBootTest
@RunWith(SpringRunner.class)
@DataJpaTest
//@SqlGroup({
// @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {"classpath:schema.sql", "classpath:data.sql"}),
// @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:drop.sql")
//})
public class ProjectRepositoryIntergrationTest {
@Autowired
ProjectRepository projectRepository;
@Test
public void ifNewProjectSaved_thenSuccess(){
int currentProjects = projectRepository.findAll().size();
Project project = new Project("new test project", "COMPLETE", "Test description");
projectRepository.save(project);
assertEquals(currentProjects + 1, projectRepository.findAll().size());
}
// end
}
|
package day18_ReadingUserInput;
import java.util.Scanner;
public class Lab4NumberOfmaleAnadNumbersOfFamles {
public static void main(String[] args) {
Scanner User_Input = new Scanner(System.in);
System.out.print("Please enter the number of males: ");
double numberOfMales= User_Input.nextInt();
per(numberOfMales);
System.out.print("Please enter the number of females: ");
double numberOfFemales=User_Input.nextInt();
per(numberOfFemales);
double TotalNumbers= numberOfMales+numberOfFemales;
double perMales=per(numberOfMales)/TotalNumbers;
double perFemales=per(numberOfFemales)/TotalNumbers;
System.out.println("Percentages of the males is: %"+ perMales);
System.out.println("Percentages of the femmales is: %"+ perFemales);
} public static double per(double amount) {
double per =amount*100;
return per;
}
}
|
package in.hocg.app.params;
import in.hocg.defaults.base.params.BaseParams;
/**
* Created by hocgin on 16-12-20.
*/
public class N0Params extends BaseParams {
}
|
package collection.visualizer.examples;
import java.util.Date;
import collection.visualizer.controller.AController;
import collection.visualizer.datatype.bean.ABeanVisualizer;
import collection.visualizer.examples.OE.CreateCustomView;
import collection.visualizer.examples.bean.ABeanDate;
import collection.visualizer.examples.bean.ABeanDateEventTrapper;
import collection.visualizer.examples.bean.ABeanDateLayoutManager;
public class Bean {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
try {
ABeanDate date = new ABeanDate();
ABeanVisualizer visualizer = new ABeanVisualizer(
new ABeanDateLayoutManager(100, 100, 50), date);
ABeanDateEventTrapper trapper = new ABeanDateEventTrapper(
(ABeanDateLayoutManager) visualizer.getLayoutManager(),
new ABeanDate());
visualizer.visualize(date);
visualizer.addTrapper(trapper);
Object[] menuItems = {};
CreateCustomView viewCreator1 = new CreateCustomView();
viewCreator1.createView(menuItems, visualizer, visualizer
.getLayoutManager().getPseudoCode(), true, false);
Clock timer = new Clock();
while (true) {
Date d = new Date();
date.setDate(d);
((AController)visualizer.getController()).next();
timer.waitOneSecond();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void waitOneSecond() {
try {
this.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Clase que se encarga de simular un canal de comunicaci��n al
* hacer un traslado de Segmentos, de un buffer de entrada a un
* buffer de salida
*
* @author Vilchis Dom��nguez Miguel Alonso
* <mvilchis@ciencias.unam.mx>
*
* @version 1.0
*
*/
public class ComunicationChannel{
private SendChannel sChannel; //Canal para envio de segmenetos con datos
private WarningChannel wChannel; //Canal para envio de segmentos de avisos
private ConcurrentLinkedQueue<Segment> warningsIn;
private ConcurrentLinkedQueue<Segment> bufferIn;
/**
* Constructor de la clase, se encarga de inicializar los threads necesarios
* y ponerlos en ejecuci��n
* @param failureProbability <int> n��mero del 1 al 10 que representa la probabilidad
* con la que fallar�� el canal, failureProbability/20
*
* @param bufferIn <ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los segmentos
* que van del cliente al canal de comunicacion
*
* @param bufferOut<ConcurrentLinkedQueue <Segment>> buffer que almacenar�� los segmentos
* que van del canal al servidor
*
* @param warningsIn<ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los avisos del
* servidor al cliente, debido a fallo en paquetes
*
* @param warningsOut<ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los avisos
* del canal de comunicaci��n al cliente.
*/
public ComunicationChannel(int failureProbability, ConcurrentLinkedQueue<Segment> bufferIn,
ConcurrentLinkedQueue<Segment> bufferOut, ConcurrentLinkedQueue<Segment> warningsIn,
ConcurrentLinkedQueue<Segment> warningsOut){
this.bufferIn = bufferIn;
this.warningsIn = warningsIn;
sChannel = new SendChannel(failureProbability, bufferIn, bufferOut);
sChannel.start();
wChannel = new WarningChannel(warningsIn, warningsOut);
wChannel.start();
}
public void sendWarning(Segment warning){
warningsIn.add(warning);
}
public void sendDataSegment(Segment segment){
bufferIn.add(segment);
}
}
/**
* Clase que representa el canal de avisos, estos avisos se producen
* cuando el servidor nota que hay algo mal en el segmento que le fue enviado
*
* @author Miguel Alonso Vilchis Dom��nguez
* <mvilchis@ciencias.unam.mx>
* @version 1.0
*
*/
class WarningChannel extends Thread{
private ConcurrentLinkedQueue<Segment> warningsIn;
private ConcurrentLinkedQueue<Segment> warningsOut;
/**
* Constructor de la clase, toma como parametro los dos buffers con los que va a trabajar
* @param warningsIn <ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los avisos del
* servidor al cliente, debido a fallo en paquetes
* @param warningsOut <ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los avisos
* del canal de comunicaci��n al cliente.
*/
public WarningChannel(ConcurrentLinkedQueue<Segment> warningsIn,
ConcurrentLinkedQueue<Segment> warningsOut) {
super("WarningChannel");
this.warningsIn = warningsIn;
this.warningsOut = warningsOut;
}
/**
* M��todo run. se encarga de ver si hay alg��n paquete en el buffer de entrada,
* para colocarlo en el buffer de salida.
*/
public void run() {
while(true){
if(!warningsIn.isEmpty()) {
warningsOut.add(warningsIn.poll());
}
}
}
}
/**
* Clase que representa el canal de Segmentos de datos
*
* @author Miguel Alonso Vilchis Dom��nguez
* <mvilchis@ciencias.unam.mx>
* @version 1.0
*/
class SendChannel extends Thread{
private ConcurrentLinkedQueue<Segment> bufferIn; //buffer de entrada de segmentos
private ConcurrentLinkedQueue<Segment> bufferOut; // buffer de salida de segmentos
private Random random;
private int failureProbability; //n��mero que representa la probabilidad de fallo
public static final int TOTAL_PROBABILITY = 20; //Constante de segmentos totales
/**
* Constructor de la clase toma como parametro los buffers con los que va a trabajar
* y la probabilidad de fallo.
* @param failureProbability<int> n��mero del 1 al 10 que representa la probabilidad
* con la que fallar�� el canal, failureProbability/20
*
* @param bufferIn <ConcurrentLinkedQueue<Segment>> buffer que almacenar�� los segmentos
* que van del cliente al canal de comunicacion
*
* @param bufferOut<ConcurrentLinkedQueue <Segment>> buffer que almacenar�� los segmentos
* que van del canal al servidor
*
*/
public SendChannel(int failureProbability, ConcurrentLinkedQueue<Segment> bufferIn,
ConcurrentLinkedQueue<Segment> bufferOut){
super("SendChannel");
this.bufferIn = bufferIn;
this.bufferOut = bufferOut;
this.failureProbability = failureProbability;
this.random = new Random();
}
private Segment changeSegment(Segment segmentTmp) {
byte [] payload = segmentTmp.getPayload();
int total = payload.length;
int affectedByte = random.nextInt(total);
int probability = random.nextInt(TOTAL_PROBABILITY);
// probability = failureProbability-1;
if (probability < failureProbability) {
byte tmp[] = new byte[1];
random.nextBytes(tmp);
payload[affectedByte] = tmp[0];
}
segmentTmp.setPayload(payload);
return segmentTmp;
}
/**
* M��todo run, se encarga de ver si hay alg��n paquete en el buffer de entrada
* de haberlo, modifica un byte con probabilidad failureProbability/20 y
* lo agrega al buffer de salida.
*/
public void run() {
while(true){
if(!bufferIn.isEmpty()) {
bufferOut.add( changeSegment(bufferIn.poll()) );
}
}
}
}
|
package cn.edu.tju.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Helper class to deal with dates
*
*/
public class Dates {
private SimpleDateFormat simpleDateFormat;
public Dates() {
simpleDateFormat = new SimpleDateFormat();
}
public Dates(String pattern) {
simpleDateFormat = new SimpleDateFormat(pattern);
}
public String format(Date date) {
return simpleDateFormat.format(date);
}
public Date format(String date) {
try {
return simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
|
package Frame;
import Model.CreamCart;
import Model.Ocasion;
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
/*
Класс, отвечающий за настройку окна приложения
*/
public class MainFrame {
// Переменные класса
private Font font = new Font("Impact", Font.BOLD, 32);
private int width = 1400;
private int height = 700;
private JFrame screen = new JFrame() {};
private JPanel infoPanel = new JPanel();
private JPanel inputPanel = new JPanel();
private JPanel msgPanel = new JPanel();
// Структуры, хранящие пары Ключ:Значение (информационные компоненты)
// и управленческие
private Map<String, JComponent> data = new HashMap<>();
private Map<String, JComponent> buttons = new HashMap<>();
//Базовый конструктор класса
public MainFrame() {}
//Конструктор с кастомными базовыми значениями высоты и длины окна
public MainFrame(int width, int height) {
this.width = width;
this.height = height;
}
//Основная настройка окна
public void setupScreen(CreamCart cart, Ocasion ocasion) {
screen.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = toolkit.getScreenSize();
screen.setBounds(dimension.width/4, dimension.height/4, width, height);
screen.setTitle("Производство мороженого");
screen.setLayout(new GridLayout(2, 2)); //выбор способа размещения элементов
setupPanel(cart, ocasion);
}
//Настройка панелей окна
private void setupPanel(CreamCart cart, Ocasion ocasion) {
//настройка информационной панели
infoPanel.setLayout(new GridLayout(3, 2)); //выбор способа размещения элементов
infoPanel.setName("info_panel");
screen.add(infoPanel); //добавление панели на основной экран
//Создание, добавление на панель и добавление в структуру элементов
data.put("temperature", setupInfoComponent(infoPanel,"Температура", "0"));
data.put("pressure", setupInfoComponent(infoPanel,"Давление", "0"));
data.put("status", setupInfoComponent(infoPanel,"Состояние", "-"));
//настройка панели кнопок
inputPanel.setLayout(new GridLayout(3, 2)); //выбор способа размещения элементов
inputPanel.setName("input_panel");
screen.add(inputPanel); //добавление панели на основной экран
//Создание, добавление на панель и добавление в структуру элементов
buttons.put("heat_up", setupInputComponent(inputPanel, "Греть", new Actions.TemperatureUp(cart)));
buttons.put("cool_down", setupInputComponent(inputPanel, "Охлаждать", new Actions.TemperatureDown(cart)));
buttons.put("press_up", setupInputComponent(inputPanel, "Повысить давление", new Actions.PressureUp(cart)));
buttons.put("press_down", setupInputComponent(inputPanel, "Понизить давление", new Actions.PressureDown(cart)));
// buttons.put("run_gen", setupInputComponent(inputPanel, "Запустить генератор", new Actions.RebootGenerator(cart)));
buttons.put("add", setupInputComponent(inputPanel, "Засыпать ингридиенты", new Actions.AddIngridients(cart)));
//настройка дополнительной панели сообщений
msgPanel.setLayout(new FlowLayout()); //выбор способа размещения элементов
screen.add(msgPanel); //добавление панели на основной экран
//Создание, добавление на панель и добавление в структуру элементов
data.put("tips", setupInfoComponent(msgPanel, "Советы: ", "Все готово к работе"));
data.put("portions", setupInfoComponent(msgPanel, "Готово штук: ", "0"));
buttons.put("start", setupInputComponent(msgPanel, "Начать работу", new Actions.StartAction(cart, ocasion)));
//отрисовка окна
screen.setVisible(true);
}
// Метод, создающий информационные компоненты, и возвращающий их
private JTextArea setupInfoComponent(JPanel panel, String labelText, String defaultText) {
JLabel label = new JLabel(labelText + ": ");
label.setFont(font);
JTextArea text = new JTextArea();
label.setLabelFor(text);
text.setFont(font);
text.setText(defaultText);
panel.add(label);
panel.add(text);
return text;
}
// Метод, создающий кнопки, и возвращающий их
private JButton setupInputComponent(JPanel panel, String buttonText, Actions.BaseAction action) {
JButton button = new JButton(buttonText);
button.setFont(font);
button.addActionListener(action);
panel.add(button);
return button;
}
//Методы получения приватных переменных извне
public Map<String, JComponent> getData() {
return data;
}
public Map<String, JComponent> getButtons() {
return buttons;
}
}
|
package com.example.smartsoft.models.dto;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.Value;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
@Getter
@XmlRootElement(name = "Values")
public class ValuteDto {
private String id;
private String numCode;
private String charCode;
private int nominal;
private String name;
private String value;
@XmlAttribute (name="ID")
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "NumCode")
public void setNumCode(String numCode) {
this.numCode = numCode;
}
@XmlElement(name = "CharCode")
public void setCharCode(String charCode) {
this.charCode = charCode;
}
@XmlElement(name = "Nominal")
public void setNominal(int nominal) {
this.nominal = nominal;
}
@XmlElement(name = "Name")
public void setName(String name) {
this.name = name;
}
@XmlElement(name = "Value")
public void setValue(String value) {
this.value = value;
}
}
|
package cn.ganzhiqiang.searchnlp.util;
import cn.ganzhiqiang.searchnlp.DictAttribute;
import com.google.common.collect.Lists;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.TreeMap;
/**
* @author zq_gan
* @since 2020/5/3
**/
public class IOUtil {
public static TreeMap<String, DictAttribute> loadDictionary(String path) throws IOException {
TreeMap<String, DictAttribute> map = new TreeMap<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null){
String[] params = line.split(",");
if (map.get(params[0]) == null) {
DictAttribute dictAttribute = new DictAttribute();
dictAttribute.setText(params[0]);
DictAttribute.Attribute attribute = new DictAttribute.Attribute();
attribute.setType(params[1]);
attribute.setNature(params[2]);
attribute.setFrequency(Integer.parseInt(params[3]));
attribute.setBusinessId(Long.parseLong(params[4]));
dictAttribute.setAttributes(Lists.newArrayList(attribute));
map.put(dictAttribute.getText(), dictAttribute);
} else {
List<DictAttribute.Attribute> attributes = map.get(params[0]).getAttributes();
DictAttribute.Attribute attribute = new DictAttribute.Attribute();
attribute.setType(params[1]);
attribute.setNature(params[2]);
attribute.setFrequency(Integer.parseInt(params[3]));
attribute.setBusinessId(Long.parseLong(params[4]));
attributes.add(attribute);
}
}
return map;
}
}
|
package agents.qoagent;
/**
* The AutomatedAgentDelayedMessageThread class allows to send a message in a delay
* @author Raz Lin
* @version 1.0
* @see AutomatedAgent
*/
public class AutomatedAgentDelayedMessageThread extends Thread {
public final static long SLEEP_TIME_FACTOR = 3; // sleep half of turn time
private String m_sOffer;
private String m_sResponse;
private int m_nCurrentTurn;
private long m_lSleepTime;
private AutomatedAgent m_agent;
private int m_nMessageType = NO_TYPE;
public static final int NEW_OFFER_TYPE = 0;
public static final int RESPONSE_TYPE = 1;
public static final int NO_TYPE = -1;
public static final long RESPONSE_SLEEP_TIME_MILLIS = 15000; // 15 seconds
AutomatedAgentDelayedMessageThread(AutomatedAgent agent, String sOffer, int nCurrentTurn)
{
m_nMessageType = NEW_OFFER_TYPE;
m_agent = agent;
m_sOffer = sOffer;
m_nCurrentTurn = nCurrentTurn;
// sleep for a while - time in milliseconds
long lSecondsPerTurn = m_agent.getSecondsForTurn();
long lMillisPerTurn = lSecondsPerTurn * 1000;
m_lSleepTime = lMillisPerTurn / SLEEP_TIME_FACTOR;
}
AutomatedAgentDelayedMessageThread(AutomatedAgent agent, String sResponse)
{
m_nMessageType = RESPONSE_TYPE;
m_agent = agent;
m_sResponse = sResponse;
// sleep for 15 seconds before answering
m_lSleepTime = RESPONSE_SLEEP_TIME_MILLIS;
}
public void run()
{
try {
sleep((long)m_lSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("[AA]ERROR: Error during sleep" + e.getMessage() + " [AutomatedAgentDelayedMessageThread::run(35)]");
System.err.println("[AA]ERROR: Error during sleep" + e.getMessage() + " [AutomatedAgentDelayedMessageThread::run(35)]");
}
if (m_nMessageType == NEW_OFFER_TYPE)
{
// check if message is still valid
boolean bSendOffer = m_agent.getSendOfferFlag();
int nCurrentTurn = m_agent.getCurrentTurn();
if (nCurrentTurn == m_nCurrentTurn)
{
// check whether to send the message or not
if (bSendOffer)
m_agent.printMessageToServer(m_sOffer);
}
}
else if (m_nMessageType == RESPONSE_TYPE)
{
m_agent.printMessageToServer(m_sResponse);
}
}
}
|
package one;
import java.util.Arrays;
public class LIS {
public int[] ls(int[] arr) {
int max = 0;
int[] predecessor = new int[arr.length];
int[] maxTracker = new int[arr.length + 1];
for(int i = 0; i < arr.length; i++) {
int lo = 1;
int hi = max;
while(lo <= hi) {
int mid = (lo + hi)/2 + (lo + hi)%2;
if(arr[maxTracker[mid]] < arr[i])
lo = mid + 1;
else
hi = mid - 1;
}
int newMax = lo;
predecessor[i] = maxTracker[newMax - 1];
maxTracker[newMax] = i;
if(newMax > max) {
max = newMax;
}
}
System.out.println(Arrays.toString(predecessor));
System.out.println(Arrays.toString(maxTracker));
int[] output = new int[max];
for(int i = max - 1, k = maxTracker[max]; i >= 0; i--) {
output[i] = arr[k];
k = predecessor[k];
}
return output;
}
/**
* @param args
*/
public static void main(String[] args) {
LIS lis = new LIS();
int[] source = {10, 22, 9, 33, 21, 50, 41, 55, 60, 70, 80, 56, 57, 58 };
int result[] = lis.ls(source);
System.out.println(Arrays.toString(result));
}
}
|
package com.tencent.mm.plugin.websearch;
public final class a {
}
|
package com.example.headfirst.designpattern;
/**
* 工厂:装饰者
* create by Administrator : zhanghechun on 2020/4/10
*/
public class CountingDuckFactory extends AbstractDuckFactory {
@Override
Quackable createMallardDuck() {
return new QuackCounter(new MallardDuck());
}
@Override
Quackable createRedHeadDuck() {
return new QuackCounter(new RedheadDuck());
}
@Override
Quackable createDuckCall() {
return new QuackCounter(new DuckCall());
}
@Override
Quackable createRubberDuck() {
return new QuackCounter(new RubberDuck());
}
}
|
import java.util.Random;
/**
* Created by wangshuyang on 2017/4/5.
*/
public class BubbleSort {
public static void print(int[] array, int n){
for (int i = 0; i < n; i++){
System.out.print(array[i] + ",");
}
System.out.println();
}
public static void bubble(int[] array, int length){
int temp;
for (int i = 0; i < length-1; i++){
for (int j = 0; j < length - i -1; j++){
if (array[j] > array[j + 1]){
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
Random random = new Random();
int[] intArray = new int[10];
for (int i = 0; i < 10; i++){
intArray[i] = random.nextInt(100);
}
print(intArray,10);
bubble(intArray,10);
print(intArray,10);
}
}
|
package com.tencent.mm.ui.bizchat;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.ac.a.n;
import com.tencent.mm.model.au;
class BizChatroomInfoUI$5 implements OnCancelListener {
final /* synthetic */ BizChatroomInfoUI tFD;
final /* synthetic */ n tFw;
BizChatroomInfoUI$5(BizChatroomInfoUI bizChatroomInfoUI, n nVar) {
this.tFD = bizChatroomInfoUI;
this.tFw = nVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.tFw);
}
}
|
package pacman.ghost;
import org.junit.Test;
import static org.junit.Assert.*;
public class PhaseTest {
@Test
public void getDurationChaseTest() {
int expected = 20;
assertEquals("getDuration() for Phase.CHASE is not working correctly",
expected, Phase.CHASE.getDuration());
}
@Test
public void getDurationScatterTest() {
int expected = 10;
assertEquals("getDuration() for Phase.SCATTER is not working correctly",
expected, Phase.SCATTER.getDuration());
}
@Test
public void getDurationFrightenedTest() {
int expected = 30;
assertEquals("getDuration() for Phase.FRIGHTENED is not working correctly",
expected, Phase.FRIGHTENED.getDuration());
}
}
|
package com.raspyboxdroid.model;
public class Relay {
private int id;
private int channel;
private String device;
private boolean active;
public Relay() {
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
class te$a {
public static final te a = new te();
}
|
package fr.mb.volontario.model.bean;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "domaine")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Domaine implements Serializable {
private Integer idDomaine;
private String nom;
private String description;
private Set<Mission> missions=new HashSet<>();
private Set<Association>associations=new HashSet<>();
public Domaine() {
}
@Id
@Column(name = "id_domaine", nullable = false, unique = true)
public Integer getIdDomaine() {
return idDomaine;
}
public void setIdDomaine(Integer idDomaine) {
this.idDomaine = idDomaine;
}
@Basic
@Column(name = "nom", nullable = false)
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
@Basic
@Column(name = "description", nullable = false)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Domaine domaine = (Domaine) o;
return Objects.equals(idDomaine, domaine.idDomaine) &&
Objects.equals(nom, domaine.nom) &&
Objects.equals(description, domaine.description);
}
@Override
public int hashCode() {
return Objects.hash(idDomaine, nom, description);
}
@OneToMany(mappedBy = "domaine", fetch = FetchType.LAZY)
@JsonIgnore
public Set<Mission> getMissions() {
return missions;
}
public void setMissions(Set<Mission> missions) {
this.missions = missions;
}
@ManyToMany(mappedBy = "domaines", fetch = FetchType.LAZY)
@JsonIgnore
public Set<Association> getAssociations() {
return associations;
}
public void setAssociations(Set<Association> associations) {
this.associations = associations;
}
}
|
package union.find;
import java.util.Arrays;
public class QuickUnionUF {
private int[] id;
public QuickUnionUF(int N) {
id = new int[N];
for(int i=0; i< N; i++) {
id[i] = i;
}
}
public int root(int i) {
while(id[i] != i) {
i = id[i];
}
return i;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
public void union(int p, int q) {
int pRoot = root(p);
int qRoot = root(q);
id[pRoot] = qRoot;
}
/**
* @param args
*/
public static void main(String[] args) {
QuickUnionUF qUF = new QuickUnionUF(10);
System.out.println(Arrays.toString(qUF.id));
qUF.union(1, 5);
qUF.union(1, 8);
qUF.union(2, 9);
qUF.union(4, 7);
qUF.union(2, 9);
System.out.println(Arrays.toString(qUF.id));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.