text
stringlengths
10
2.72M
import java.io.*; public class q9 { public static void main(String[] args){ try{ String path= "t.txt"; File f = new File(path); PrintWriter writer = new PrintWriter(f); writer.println("Testing,"); writer.println("1, 2, 3."); writer.println("This is my output file."); writer.close(); }catch(Exception e ) { } } }
package org.workers.impl.combat_instructor; import org.OrionTutorial; import org.osbot.rs07.api.ui.RS2Widget; import org.osbot.rs07.api.ui.Tab; import org.workers.TutorialWorker; import viking.api.Timing; public class OpenEquipmentStats extends TutorialWorker { private static final int MASTER = 387, CHILD = 17; public OpenEquipmentStats(OrionTutorial mission) { super(mission); } @Override public boolean shouldExecute() { return true; } @Override public void work() { script.log(this, false, "Open Equipment Stats"); if(tabs.open(Tab.EQUIPMENT)) { RS2Widget widget = widgets.get(MASTER, CHILD); if(widget != null && widget.interact() && Timing.waitCondition(() -> widgets.getWidgetContainingText("Equip Your Character...") != null, 3500)) { RS2Widget close = widgets.getWidgetContainingText("Close"); if(close != null) close.interact(); } } } }
package org.sagebionetworks.repo.manager.authentication; import java.util.Date; import org.sagebionetworks.repo.manager.AuthenticationManager; import org.sagebionetworks.repo.manager.UserCredentialValidator; import org.sagebionetworks.repo.manager.oauth.OIDCTokenHelper; import org.sagebionetworks.repo.manager.password.InvalidPasswordException; import org.sagebionetworks.repo.manager.password.PasswordValidator; import org.sagebionetworks.repo.model.AuthorizationUtils; import org.sagebionetworks.repo.model.UnauthenticatedException; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.auth.AuthenticatedOn; import org.sagebionetworks.repo.model.auth.AuthenticationDAO; import org.sagebionetworks.repo.model.auth.ChangePasswordInterface; import org.sagebionetworks.repo.model.auth.ChangePasswordWithCurrentPassword; import org.sagebionetworks.repo.model.auth.ChangePasswordWithToken; import org.sagebionetworks.repo.model.auth.LoginRequest; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.PasswordResetSignedToken; import org.sagebionetworks.repo.model.principal.AliasType; import org.sagebionetworks.repo.model.principal.PrincipalAlias; import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO; import org.sagebionetworks.repo.transactions.WriteTransaction; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.securitytools.PBKDF2Utils; import org.sagebionetworks.util.Clock; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; public class AuthenticationManagerImpl implements AuthenticationManager { public static final long LOCK_TIMOUTE_SEC = 5*60; public static final int MAX_CONCURRENT_LOCKS = 10; public static final String ACCOUNT_LOCKED_MESSAGE = "This account has been locked. Reason: too many requests. Please try again in five minutes."; @Autowired private AuthenticationDAO authDAO; @Autowired private AuthenticationReceiptTokenGenerator authenticationReceiptTokenGenerator; @Autowired private PasswordValidator passwordValidator; @Autowired private UserCredentialValidator userCredentialValidator; @Autowired private PrincipalAliasDAO principalAliasDAO; @Autowired private PasswordResetTokenGenerator passwordResetTokenGenerator; @Autowired private OIDCTokenHelper oidcTokenHelper; @Autowired private Clock clock; @Override @WriteTransaction public void setPassword(Long principalId, String password) { passwordValidator.validatePassword(password); String passHash = PBKDF2Utils.hashPassword(password, null); authDAO.changePassword(principalId, passHash); } @WriteTransaction public long changePassword(ChangePasswordInterface changePasswordInterface){ ValidateArgument.required(changePasswordInterface, "changePasswordInterface"); final long userId; if(changePasswordInterface instanceof ChangePasswordWithCurrentPassword){ userId = validateChangePassword((ChangePasswordWithCurrentPassword) changePasswordInterface); }else if (changePasswordInterface instanceof ChangePasswordWithToken){ userId = validateChangePassword((ChangePasswordWithToken) changePasswordInterface); }else{ throw new IllegalArgumentException("Unknown implementation of ChangePasswordInterface"); } setPassword(userId, changePasswordInterface.getNewPassword()); userCredentialValidator.forceResetLoginThrottle(userId); return userId; } /** * * @param changePasswordWithCurrentPassword * @return id of user for which password change occurred */ long validateChangePassword(ChangePasswordWithCurrentPassword changePasswordWithCurrentPassword) { ValidateArgument.required(changePasswordWithCurrentPassword.getUsername(), "changePasswordWithCurrentPassword.username"); ValidateArgument.required(changePasswordWithCurrentPassword.getCurrentPassword(), "changePasswordWithCurrentPassword.currentPassword"); final long userId = findUserIdForAuthentication(changePasswordWithCurrentPassword.getUsername()); //we can ignore the return value here because we are not generating a new authentication receipt on success validateAuthReceiptAndCheckPassword(userId, changePasswordWithCurrentPassword.getCurrentPassword(), changePasswordWithCurrentPassword.getAuthenticationReceipt()); return userId; } /** * * @param changePasswordWithToken * @return id of user for which password change occurred */ long validateChangePassword(ChangePasswordWithToken changePasswordWithToken){ ValidateArgument.required(changePasswordWithToken.getPasswordChangeToken(), "changePasswordWithToken.passwordChangeToken"); if(!passwordResetTokenGenerator.isValidToken(changePasswordWithToken.getPasswordChangeToken())){ throw new IllegalArgumentException("Password reset token is invalid"); } return Long.parseLong(changePasswordWithToken.getPasswordChangeToken().getUserId()); } @Override public String getSecretKey(Long principalId) throws NotFoundException { return authDAO.getSecretKey(principalId); } @Override @WriteTransaction public void changeSecretKey(Long principalId) { authDAO.changeSecretKey(principalId); } @Override public PasswordResetSignedToken createPasswordResetToken(long userId) throws NotFoundException { return passwordResetTokenGenerator.getToken(userId); } @Override public boolean hasUserAcceptedTermsOfUse(Long id) throws NotFoundException { return authDAO.hasUserAcceptedToU(id); } @Override @WriteTransaction public void setTermsOfUseAcceptance(Long principalId, Boolean acceptance) { if (acceptance == null) { throw new IllegalArgumentException("Cannot \"unsign\" the terms of use"); } authDAO.setTermsOfUseAcceptance(principalId, acceptance); } @Override public LoginResponse login(LoginRequest request, String tokenIssuer){ ValidateArgument.required(request, "loginRequest"); ValidateArgument.required(request.getUsername(), "LoginRequest.username"); ValidateArgument.required(request.getPassword(), "LoginRequest.password"); final long userId = findUserIdForAuthentication(request.getUsername()); final String password = request.getPassword(); final String authenticationReceipt = request.getAuthenticationReceipt(); validateAuthReceiptAndCheckPassword(userId, password, authenticationReceipt); return getLoginResponseAfterSuccessfulPasswordAuthentication(userId, tokenIssuer); } public AuthenticatedOn getAuthenticatedOn(UserInfo userInfo) { if (AuthorizationUtils.isUserAnonymous(userInfo)) { throw new UnauthenticatedException("Cannot retrieve authentication time stamp for anonymous user."); } // Note the date will be null if the user has not logged in Date authenticatedOn = authDAO.getAuthenticatedOn(userInfo.getId()); AuthenticatedOn result = new AuthenticatedOn(); result.setAuthenticatedOn(authenticatedOn); return result; } /** * Validate authenticationReceipt and then checks that the password is correct for the given principalId * @param userId id of the user * @param password password of the user * @param authenticationReceipt Can be null. When valid, does not throttle attempts on consecutive incorrect passwords. * @return authenticationReceipt if it is valid and password check passed. null, if the authenticationReceipt was invalid, but password check passed. * @throws UnauthenticatedException if password check failed */ void validateAuthReceiptAndCheckPassword(final long userId, final String password, final String authenticationReceipt) { boolean isAuthenticationReceiptValid = authenticationReceiptTokenGenerator.isReceiptValid(userId, authenticationReceipt); //callers that have previously logged in successfully are able to bypass lockout caused by failed attempts boolean correctCredentials = isAuthenticationReceiptValid ? userCredentialValidator.checkPassword(userId, password) : userCredentialValidator.checkPasswordWithThrottling(userId, password); if(!correctCredentials){ throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT); } // Now that the password has been verified, // ensure that if the current password is a weak password, only allow the user to reset via emailed token try{ passwordValidator.validatePassword(password); } catch (InvalidPasswordException e){ throw new PasswordResetViaEmailRequiredException("You must change your password via email reset."); } } @Override public LoginResponse loginWithNoPasswordCheck(long principalId, String issuer){ return getLoginResponseAfterSuccessfulPasswordAuthentication(principalId, issuer); } LoginResponse getLoginResponseAfterSuccessfulPasswordAuthentication(long principalId, String issuer) { String newAuthenticationReceipt = authenticationReceiptTokenGenerator.createNewAuthenticationReciept(principalId); String accessToken = oidcTokenHelper.createClientTotalAccessToken(principalId, issuer); boolean acceptsTermsOfUse = authDAO.hasUserAcceptedToU(principalId); authDAO.setAuthenticatedOn(principalId, clock.now()); return createLoginResponse(accessToken, acceptsTermsOfUse, newAuthenticationReceipt); } private static LoginResponse createLoginResponse(String accessToken, boolean acceptsTermsOfUse, String newReceipt) { LoginResponse response = new LoginResponse(); response.setAccessToken(accessToken); response.setAcceptsTermsOfUse(acceptsTermsOfUse); response.setAuthenticationReceipt(newReceipt); return response; } long findUserIdForAuthentication(final String usernameOrEmail){ PrincipalAlias principalAlias = principalAliasDAO.findPrincipalWithAlias(usernameOrEmail, AliasType.USER_EMAIL, AliasType.USER_NAME); if (principalAlias == null){ throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT); } return principalAlias.getPrincipalId(); } }
package cn.edu.nju.se.lawcase.entities; import java.io.Serializable; import java.util.List; public class Statute implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String statuteId; private String statuteName; private List<Chapter> chapters; public String getStatuteId() { return statuteId; } public void setStatuteId(String statuteId) { this.statuteId = statuteId; } public String getStatuteName() { return statuteName; } public void setStatuteName(String statuteName) { this.statuteName = statuteName; } public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } }
package com.fourstay.step_definitions; import org.junit.Assert; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.fourstay.pages.HomePage; import com.fourstay.utilities.ConfigurationReader; import com.fourstay.utilities.Driver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class LoginTestStepDefs { HomePage homePage=new HomePage(); @Given("^I am on the fourstay homepage$") public void i_am_on_the_fourstay_homepage() throws Throwable { Driver.getInstance(). get(ConfigurationReader.getProperty("url")); } @When("^I login as a host$") public void i_login_as_a_host() throws Throwable { homePage.loginLink.click(); Thread.sleep(2000); homePage.email.sendKeys(ConfigurationReader.getProperty("host.username")); Thread.sleep(2000); homePage.password.sendKeys(ConfigurationReader.getProperty("host.password")); homePage.loginBtn.click(); } @Then("^I should be able verify I am logged in$") public void i_should_be_able_verify_I_am_logged_in() throws Throwable { WebDriverWait wait=new WebDriverWait(Driver.getInstance(), 5000); wait.until(ExpectedConditions.urlContains("dashboard")); Assert.assertTrue(Driver.getInstance(). getCurrentUrl().contains("dashboard")); } @When("^I login as a guest$") public void i_login_as_a_guest() throws Throwable { homePage.loginLink.click(); Thread.sleep(2000); homePage.email.sendKeys(ConfigurationReader.getProperty("guest.username")); Thread.sleep(2000); homePage.password.sendKeys(ConfigurationReader.getProperty("guest.password")); homePage.loginBtn.click(); } }
package main; import java.io.IOException; import org.lwjgl.LWJGLException; import org.lwjgl.util.vector.Vector3f; public class Assets extends initialization { public void assets() throws IOException, LWJGLException, InterruptedException { CLOUD = handler.InitEntity("cloud", "cloud", 1, false, false); FERN = handler.InitEntity("fern", "fern", 2, false, true); TREE = handler.InitEntity("pine", "pine", 1, true, false); GRASS = handler.InitEntity("grassModel", "grasstest", 2, false, true); PLAYER = handler.InitPlayer("person", "playerTexture", new Vector3f(0, 1, 0), 0.6f); TERRAIN_1 = handler.InitTerrain("grassy", "mud", "grassFlowers", "path", "blendMap", 0, -1, "heightmap"); TERRAIN_2 = handler.InitTerrain("grassy", "mud", "grassFlowers", "path", "blendMap", 0, 0, "heightmap"); TERRAIN_3 = handler.InitTerrain("grassy", "mud", "grassFlowers", "path", "blendMap", -1, 0, "heightmap"); TERRAIN_4 = handler.InitTerrain("grassy", "mud", "grassFlowers", "path", "blendMap", -1, -1, "heightmap"); LIGHT_1 = handler.InitLight(new Vector3f(0, 1000, -7000), new Vector3f(0, 0, 0)); LAMP = handler.InitLamp(new Vector3f(100, -10, 100), new Vector3f(1,1,1), new Vector3f(1, 0.01f, 0.002f)); } }
package com.lxy.servlet; import java.io.IOException; import javax.servlet.GenericServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class ServletDemo2 extends GenericServlet { public void init() throws ServletException { } public void init(ServletConfig config) throws ServletException { System.out.println("init..."); } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } }
package com.swmansion.gesturehandler; import android.os.SystemClock; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; public class h extends b<h> { public boolean a; public boolean b; public h() { a(true); } private static boolean a(View paramView, MotionEvent paramMotionEvent) { return (paramView instanceof ViewGroup && ((ViewGroup)paramView).onInterceptTouchEvent(paramMotionEvent)); } protected final void a() { long l = SystemClock.uptimeMillis(); MotionEvent motionEvent = MotionEvent.obtain(l, l, 3, 0.0F, 0.0F, 0); motionEvent.setAction(3); this.f.onTouchEvent(motionEvent); } protected final void a(MotionEvent paramMotionEvent) { View view = this.f; int i = this.g; if (paramMotionEvent.getActionMasked() == 1) { view.onTouchEvent(paramMotionEvent); if ((i == 0 || i == 2) && view.isPressed()) e(); g(); return; } if (i == 0 || i == 2) { if (this.a) { a(view, paramMotionEvent); view.onTouchEvent(paramMotionEvent); e(); return; } if (a(view, paramMotionEvent)) { view.onTouchEvent(paramMotionEvent); e(); return; } if (i != 2) f(); return; } if (i == 4) { view.onTouchEvent(paramMotionEvent); return; } } public final boolean b(b paramb) { return super.b(paramb); } public final boolean d(b paramb) { if (paramb instanceof h) { h h1 = (h)paramb; if (h1.g == 4 && h1.b) return false; } int i = this.b ^ true; int j = this.g; int k = paramb.g; return (j == 4 && k == 4 && i != 0) ? false : ((j == 4 && i != 0)); } public final boolean e(b paramb) { return !this.b; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\swmansion\gesturehandler\h.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package net4game.ctx; import ctx.AbstractSession; import net4game.pojo.NetRegistrant; public class NetSession extends AbstractSession { private NetRegistrant r; public NetSession(String id, NetRegistrant r) { super(id); this.r = r; } public NetRegistrant getR() { return r; } public void setR(NetRegistrant r) { this.r = r; } }
package com.yida.design.prototype.demo; /** ********************* * @author yangke * @version 1.0 * @created 2018年5月11日 下午3:12:21 *********************** */ public class AdvTemplate { // 名称 private String advSubject = "XX银行国庆信用卡抽奖活动"; // 内容 private String advContext = "国庆抽奖活动通知:只要刷卡就送你一百万!..."; // 获取名称 public String getAdvSubject() { return advSubject; } // 获取内容 public String getAdvContext() { return advContext; } }
package com.theoffice.moneysaver.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.theoffice.moneysaver.R; import com.theoffice.moneysaver.data.model.Contribution; import java.util.ArrayList; public class ContributionRVAdapter extends RecyclerView.Adapter<ContributionRVAdapter.ContributionViewHolder> { private ArrayList<Contribution> contributions; public ContributionRVAdapter(ArrayList<Contribution> contributions){ this.contributions = contributions; } static class ContributionViewHolder extends RecyclerView.ViewHolder{ TextView tvContrValue; TextView tvContrDate; public ContributionViewHolder(@NonNull View itemView) { super(itemView); tvContrValue = itemView.findViewById(R.id.tv_contr_value); tvContrDate = itemView.findViewById(R.id.tv_contr_date); } } @NonNull @Override public ContributionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_contribution, parent, false); return new ContributionViewHolder(item); } @Override public void onBindViewHolder(@NonNull ContributionViewHolder holder, int position) { Contribution contribution = contributions.get(position); holder.tvContrValue.setText("$" + contribution.getContributionValue()); holder.tvContrDate.setText(contribution.getContributionDate()); } @Override public int getItemCount() { return contributions.size(); } }
/* * Copyright (C) 2001 - 2015 Marko Salmela, http://fuusio.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fuusio.api.rest; import com.android.volley.Request; /** * {@link HttpMethod} defines an enumerated type for representing HTTP methods. */ public enum HttpMethod { GET("GET", Request.Method.GET), POST("POST", Request.Method.POST), PUT("PUT", Request.Method.PUT), DELETE("DELETE", Request.Method.DELETE), HEAD("HEAD", Request.Method.HEAD), OPTIONS("OPTIONS", Request.Method.OPTIONS), TRACE("TRACE", Request.Method.TRACE); private final int mCode; private final String mName; HttpMethod(final String name, final int code) { mName = name; mCode = code; } public int getMethodCode() { return mCode; } public final String getName() { return mName; } public final String toString() { return mName; } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class mc extends b { public a bWF; public b bWG; public mc() { this((byte) 0); } private mc(byte b) { this.bWF = new a(); this.bWG = new b(); this.sFm = false; this.bJX = null; } }
package com.lera.vehicle.reservation.command.customer; import com.lera.vehicle.reservation.domain.customer.CreditCardType; import com.lera.vehicle.reservation.domain.customer.CustomerType; import org.junit.Test; import java.util.Calendar; import static org.junit.Assert.*; public class EditCustomerObjectTest { EditCustomerObject editCustomerObject = new EditCustomerObject(); @Test public void getFullName() { editCustomerObject.setFullName("Customer"); assertEquals("Customer", editCustomerObject.getFullName()); } @Test public void getDateOfBirth() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setDateOfBirth(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getDateOfBirth()); } @Test public void getAddress() { editCustomerObject.setAddress("Address"); assertEquals("Address", editCustomerObject.getAddress()); } @Test public void getMobilePhone() { editCustomerObject.setMobilePhone("1111"); assertEquals("1111", editCustomerObject.getMobilePhone()); } @Test public void getCompanyName() { editCustomerObject.setCompanyName("Company"); assertEquals("Company", editCustomerObject.getCompanyName()); } @Test public void getEmail() { editCustomerObject.setEmail("email@email"); assertEquals("email@email", editCustomerObject.getEmail()); } @Test public void getCustomerType() { editCustomerObject.setCustomerType(CustomerType.RETAIL); assertEquals(CustomerType.RETAIL, editCustomerObject.getCustomerType()); } @Test public void getLicenceNo() { editCustomerObject.setLicenceNo("licence"); assertEquals("licence", editCustomerObject.getLicenceNo()); } @Test public void getLicenceIssueDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setLicenceIssueDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getLicenceIssueDate()); } @Test public void getLicenceExpiryDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setLicenceExpiryDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getLicenceExpiryDate()); } @Test public void getPassportNo() { editCustomerObject.setPassportNo("passportNo"); assertEquals("passportNo", editCustomerObject.getPassportNo()); } @Test public void getPassportIssueDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setPassportIssueDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getPassportIssueDate()); } @Test public void getPassportExpiryDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setPassportExpiryDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getPassportExpiryDate()); } @Test public void getInsuranceCompany() { editCustomerObject.setInsuranceCompany("Company2"); assertEquals("Company2", editCustomerObject.getInsuranceCompany()); } @Test public void getInsurancePolicyNo() { editCustomerObject.setInsurancePolicyNo("policyNo"); assertEquals("policyNo", editCustomerObject.getInsurancePolicyNo()); } @Test public void getInsuranceExpiryDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setInsuranceExpiryDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getInsuranceExpiryDate()); } @Test public void getCreditCardType() { editCustomerObject.setCreditCardType(CreditCardType.VISA); assertEquals(CreditCardType.VISA, editCustomerObject.getCreditCardType()); } @Test public void getCreditCardNo() { editCustomerObject.setCreditCardNo(1111111); assertEquals(1111111, editCustomerObject.getCreditCardNo()); } @Test public void getNameOnCard() { editCustomerObject.setNameOnCard("NameOnCard"); assertEquals("NameOnCard", editCustomerObject.getNameOnCard()); } @Test public void getCreditCardExpiryDate() { Calendar calendar = Calendar.getInstance(); calendar.set(2000, Calendar.APRIL, 9); editCustomerObject.setCreditCardExpiryDate(calendar.getTime()); assertEquals(calendar.getTime(), editCustomerObject.getCreditCardExpiryDate()); } }
package com.tencent.mm.plugin.fav.ui; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.fav.a.aj; import com.tencent.mm.sdk.platformtools.x; class FavBaseUI$6 implements e { final /* synthetic */ FavBaseUI iYp; FavBaseUI$6(FavBaseUI favBaseUI) { this.iYp = favBaseUI; } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.FavoriteBaseUI", "on fav sync end"); if (((aj) lVar).iWW) { x.i("MicroMsg.FavoriteBaseUI", "need batch get return"); return; } x.i("MicroMsg.FavoriteBaseUI", "dismiss loading dialog"); if (FavBaseUI.c(this.iYp)) { FavBaseUI.d(this.iYp); } this.iYp.eP(false); this.iYp.aMg(); } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.client; import org.overlord.rtgov.activity.model.ActivityType; /** * This interface represents the capability for recording * activity information from an application. * */ public interface ActivityReporter { /** * This method can be used to report general information. * * @param info The information */ public void logInfo(String info); /** * This method can be used to report warning information. * * @param warning The warning description */ public void logWarning(String warning); /** * This method can be used to report error information. * * @param error The error description */ public void logError(String error); /** * This method can be used to report activity information. * * @param type The activity type * @param props The properties */ public void report(String type, java.util.Map<String,String> props); /** * This method reports the activity event to the * collector. * * @param actType The activity type */ public void report(ActivityType actType); }
package mg.egg.eggc.compiler.egg.java; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.compiler.libegg.base.*; import mg.egg.eggc.compiler.libegg.java.*; import mg.egg.eggc.compiler.libegg.egg.*; import mg.egg.eggc.compiler.libegg.mig.*; import mg.egg.eggc.compiler.libegg.latex.*; import mg.egg.eggc.compiler.libegg.type.*; import mg.egg.eggc.runtime.libjava.lex.*; import java.util.*; import mg.egg.eggc.runtime.libjava.lex.*; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.runtime.libjava.messages.*; import mg.egg.eggc.runtime.libjava.problem.IProblem; import java.util.Vector; import java.util.List; import java.util.ArrayList; public class S_ACTS_EGG implements IDstNode { LEX_EGG scanner; S_ACTS_EGG() { } S_ACTS_EGG(LEX_EGG scanner, boolean eval) { this.scanner = scanner; this.att_eval = eval; offset = 0; length = 0; this.att_scanner = scanner; } int [] sync= new int[0]; REGLE att_reg; boolean att_eval; TDS att_table; LEX_EGG att_scanner; IVisiteurEgg att_vis; ActREGLE glob_45_a; private void regle46() throws Exception { //declaration //appel if (att_eval) action_regle_46(); length = 0; offset = scanner.getPreviousOffset()+ scanner.getPreviousLength(); } private void regle45() throws Exception { //declaration S_GLOBALES_EGG x_2 = new S_GLOBALES_EGG(scanner,att_eval) ; T_EGG x_3 = new T_EGG(scanner ) ; T_EGG x_4 = new T_EGG(scanner ) ; LACTION x_6 = new LACTION(scanner.getReporter(), scanner.contexte); T_EGG x_7 = new T_EGG(scanner ) ; S_ACTS_EGG x_9 = new S_ACTS_EGG(scanner,att_eval) ; //appel if (att_eval) action_auto_inh_45(x_2, x_3, x_6, x_9); x_2.analyser() ; addChild(x_2); x_3.analyser(LEX_EGG.token_t_action); addChild(x_3); x_4.analyser(LEX_EGG.token_t_aco); addChild(x_4); if (att_eval) action_trans_45(x_2, x_3, x_6, x_9); x_6.scanner.setSource(scanner) ; x_6.set_eval(true) ; x_6.compile() ; scanner.setSource(x_6.scanner) ; addChild(x_6.getAxiom()); x_7.analyser(LEX_EGG.token_t_acf); addChild(x_7); if (att_eval) action_add_45(x_2, x_3, x_6, x_9); x_9.analyser() ; addChild(x_9); offset =x_2.getOffset(); length =x_9.getOffset() + x_9.getLength() - offset; } private void action_regle_46() throws Exception { try { // instructions TDS_ACTION loc_t; String loc_atts; LACT loc_lact; ActREGLE loc_a; LACTION loc_l; LEX_CONTEXTE loc_lc; LEX_LACTION loc_s; String loc_acts; if (((this.att_table).getAutoAtt()==true)){ loc_a=(this.att_reg).action("#auto_inh"); if ((loc_a!=null)){ loc_lact= new LACT((this.att_reg).getTable(), (loc_a).getPos()); (this.att_reg).autos(loc_lact); if (((loc_a).getCodeSrc()!=null)){ loc_lc= new LEX_CONTEXTE((loc_a).getCodeSrc()); loc_l= new LACTION((this.att_scanner).getReporter(), loc_lc); (loc_l).set_act(loc_lact); (loc_l).set_table(this.att_table); (loc_l).set_avis((this.att_vis).getVisAction()); loc_s=(loc_l).get_scanner(); (loc_s).setReader(loc_s); (loc_l).set_eval(true); (loc_l).compile(); (loc_a).setCode((loc_l).get_code()); (this.att_vis).nt_action(loc_a); } } } (this.att_vis).nt_regle(this.att_reg); if (((this.att_table).syntaxOnly()!=true)){ loc_t=(this.att_reg).getTable(); loc_atts=(loc_t).verifier_initialisations(); if ((loc_atts!=null)){ att_scanner._interrompre(IProblem.Semantic, att_scanner.getBeginLine(), IEGGMessages.id_EGG_attributes_non_initialized, EGGMessages.EGG_attributes_non_initialized,new Object[]{""+loc_atts, ""+(this.att_reg).toStringSyntaxAction()}); } loc_acts=(this.att_reg).verifierActions(); if ((loc_acts!=null)){ att_scanner._interrompre(IProblem.Semantic, att_scanner.getBeginLine(), IEGGMessages.id_EGG_undefined_actions, EGGMessages.EGG_undefined_actions,new Object[]{""+loc_acts, ""+(this.att_reg).toStringSyntaxAction()}); } } }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#regle","ACTS -> #regle ;"}); } } private void action_add_45(S_GLOBALES_EGG x_2, T_EGG x_3, LACTION x_6, S_ACTS_EGG x_9) throws Exception { try { // instructions if ((glob_45_a!=null)){ (glob_45_a).setCodeSrc(this.att_table, x_6.att_offset, x_6.att_length); (glob_45_a).setCode(x_6.att_code); (this.att_vis).nt_action(glob_45_a); } else { } }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#add","ACTS -> GLOBALES t_action t_aco #trans LACTION t_acf #add ACTS1 ;"}); } } private void action_trans_45(S_GLOBALES_EGG x_2, T_EGG x_3, LACTION x_6, S_ACTS_EGG x_9) throws Exception { try { // instructions String loc_c; LACT loc_lact; glob_45_a=(this.att_reg).action(x_3.att_txt); if ((glob_45_a!=null)){ loc_c=(glob_45_a).getCode(); if ((loc_c!=null)){ att_scanner._interrompre(IProblem.Semantic, att_scanner.getBeginLine(), IEGGMessages.id_EGG_action_yet_declared, EGGMessages.EGG_action_yet_declared,new Object[]{""+x_3.att_txt}); } else { loc_lact= new LACT((this.att_reg).getTable(), (glob_45_a).getPos()); x_6.att_act=loc_lact; x_6.att_table=this.att_table; x_6.att_avis=(this.att_vis).getVisAction(); } } else { att_scanner._interrompre(IProblem.Semantic, att_scanner.getBeginLine(), IEGGMessages.id_EGG_action_useless, EGGMessages.EGG_action_useless,new Object[]{""+x_3.att_txt, ""+(this.att_reg).toStringSyntaxAction()}); } }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#trans","ACTS -> GLOBALES t_action t_aco #trans LACTION t_acf #add ACTS1 ;"}); } } private void action_auto_inh_45(S_GLOBALES_EGG x_2, T_EGG x_3, LACTION x_6, S_ACTS_EGG x_9) throws Exception { try { // instructions x_2.att_table=this.att_table; x_9.att_table=this.att_table; x_2.att_reg=this.att_reg; x_6.att_reg=this.att_reg; x_9.att_reg=this.att_reg; x_2.att_vis=this.att_vis; x_9.att_vis=this.att_vis; }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#auto_inh","ACTS -> GLOBALES t_action t_aco #trans LACTION t_acf #add ACTS1 ;"}); } } public void analyser () throws Exception { scanner.lit ( 1 ) ; switch ( scanner.fenetre[0].code ) { case LEX_EGG.token_t_global : // 54 regle45 () ; break ; case LEX_EGG.token_t_action : // 60 regle45 () ; break ; case LEX_EGG.token_t_ident : // 61 regle46 () ; break ; case LEX_EGG.token_t_end : // 53 regle46 () ; break ; default : scanner._interrompre(IProblem.Syntax, scanner.getBeginLine(), IEGGMessages.id_EGG_unexpected_token,EGGMessages.EGG_unexpected_token,new String[]{scanner.fenetre[0].getNom()}); } } private IDstNode parent; public void setParent( IDstNode p){parent = p;} public IDstNode getParent(){return parent;} private List<IDstNode> children = null ; public void addChild(IDstNode node){ if (children == null) { children = new ArrayList<IDstNode>() ;} children.add(node); node.setParent(this); } public List<IDstNode> getChildren(){return children;} public boolean isLeaf(){return children == null;} public void accept(IDstVisitor visitor) { boolean visitChildren = visitor.visit(this); if (visitChildren && children != null){ for(IDstNode node : children){ node.accept(visitor); } } visitor.endVisit(this); } private int offset; private int length; public int getOffset(){return offset;} public void setOffset(int o){offset = o;} public int getLength(){return length;} public void setLength(int l){length = l;} private boolean malformed = false; public void setMalformed(){malformed = true;} public boolean isMalformed(){return malformed;} }
package org.codeshifts.spring.batch.reader.csv.person.constants; /** * Created by werner.diwischek on 07.05.17. */ public class PersonConstants { public static final String ATTRIBUTE_ID_FIRSTNAME = "möwe"; public static final String ATTRIBUTE_ID_LASTNAME = "anything goes"; public static final String ATTRIBUTE_NOT_PERSISTED1 = "4711"; public static final String ATTRIBUTE_NOT_PERSISTED2 = "0815"; }
package org.browsexml.timesheetjob.web; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.browsexml.timesheetjob.model.BaseObject; import org.browsexml.timesheetjob.model.Holiday; import org.browsexml.timesheetjob.model.Constants; import org.browsexml.timesheetjob.service.HolidayManager; import org.browsexml.timesheetjob.web.HolidayController.HolidayBacking; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; public class HolidayFormController extends SimpleFormController { private static Log log = LogFactory.getLog(HolidayFormController.class); private HolidayManager mgr = null; public HolidayFormController() { log.debug("LOADED " + this.getClass().getName()); } public void setHolidayManager(HolidayManager mgr) { this.mgr = mgr; } protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { SimpleDateFormat dayFormat = Constants.displayDate; dayFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dayFormat, true)); } @Override public Object formBackingObject(HttpServletRequest request) { HolidayFormBacking backing = new HolidayFormBacking(); String id = request.getParameter("id"); if (id != null && !id.trim().equals("")) { log.debug("id = '" + id + "'"); Holiday holiday = mgr.get(Integer.parseInt(id)); backing.setHoliday(holiday); } else { backing.setHoliday(new Holiday()); } return backing; } public ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { log.debug("entering 'processFormSubmission' for " + this.getClass().getName() + "..."); HolidayFormBacking backing = (HolidayFormBacking) command; if (request.getParameter("cancel") != null) { log.debug("CANCEL command = " + command); return getSuccess(backing); } return super.processFormSubmission(request, response, command, errors); } @Override public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) { if (log.isDebugEnabled()) { log.debug("entering 'onSubmit' for " + this.getClass().getName() + "..."); } HolidayFormBacking backing = (HolidayFormBacking) command; Boolean success = true; if (request.getParameter("delete") != null) { log.debug("ON SUBMIT delete " + backing.getHoliday().getId()); try { mgr.remove(backing.getHoliday().getId()); } catch (Exception e) { success = false; e.printStackTrace(); request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("holiday.notDeleted")); } if (success) request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("holiday.deleted")); } else { try { mgr.save(backing.getHoliday()); } catch (Exception e) { success = false; e.printStackTrace(); request.getSession().setAttribute("message", e.getMessage()); } if (success) request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("holiday.saved")); } return getSuccess(backing); } public ModelAndView getSuccess(HolidayFormBacking backing) { HolidayBacking parentBacking = new HolidayBacking(); return new ModelAndView(getSuccessView()) .addObject("holidayBacking", parentBacking); } public static class HolidayFormBacking extends BaseObject { /** * */ private static final long serialVersionUID = 1L; Holiday Holiday = new Holiday(); String save = ""; public Holiday getHoliday() { return Holiday; } public void setHoliday(Holiday Holiday) { if (Holiday == null) { log.debug("TRYING TO SET NULL"); new Exception().printStackTrace(); return; } this.Holiday = Holiday; } public String getSave() { return save; } public void setSave(String save) { this.save = save; } } public static class HolidayFormControllerValidator implements Validator { private static Log log = LogFactory.getLog(HolidayFormControllerValidator.class); private HolidayManager mgr = null; public void setHolidayManager(HolidayManager HolidayManager) { this.mgr = HolidayManager; } @Override public boolean supports(Class theClass) { return HolidayFormBacking.class.equals(theClass); } @Override public void validate(Object obj, Errors errors) { HolidayFormBacking HolidayBacking = (HolidayFormBacking) obj; Holiday Holiday = HolidayBacking.getHoliday(); // only validate on save if ("".equals(HolidayBacking.getSave())) return; } } }
package org.mytests.tests.UITests; import org.mytests.tests.TestsInit; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.epam.jdi.light.elements.composite.WebPage.back; import static com.epam.jdi.light.settings.WebSettings.logger; import static org.mytests.uiobjects.example.site.SitePolixis.*; public class DataComparisionUITests extends TestsInit { SoftAssert softAssert = new SoftAssert(); Map<String, ArrayList<String>> directors = new HashMap<>(); ArrayList<String> directorsTempList = new ArrayList<>(); Map<String, ArrayList<String>> auditors = new HashMap<>(); ArrayList<String> auditorsTempList = new ArrayList<>(); Map<String, ArrayList<String>> shareholders = new HashMap<>(); ArrayList<String> shareholdersTempList = new ArrayList<>(); @Test(description = "Open Web Application And Navigate To Financial Entities") public void testOpenSiteAndFinancialEntitiesPage(){ popUpWindow.closeButton.click(); popUpWindow.popUpWindowImage.assertThat().notVisible(); homePage.navigationMenu.select("Sistema Financiero"); homePage.entities.iCore().click(); financialEntitiesPage.checkOpened(); } @Test(description = "Get Directors, Auditors And Shareholders Names", dependsOnMethods = "testOpenSiteAndFinancialEntitiesPage") public void testDirectorsAuditorsShareholders(){ bcoForm.financialEntitiesList.show(); for(int i = 2; i<=25; i++){ // will be selected only 24 banks from list. For full list please change 25 to bcoForm.financialEntitiesList.size() bcoForm.financialEntitiesList.select(i); String bankName = bcoForm.financialEntitiesList.selected(); bcoForm.inputButton.click(); bcoForm.directorsLink.show(); bcoForm.directorsLink.click(); try { for (int j = 0; j <= directorsPage.directorsTable.count(); j++) { directorsTempList.add(directorsPage.directorsTable.getCell(2, j).getText()); } } catch (RuntimeException ignore){ logger.toLog("Directors List is missing "); } directors.put(bankName, directorsTempList); directorsPage.directorsTable.offCache(); back(); bcoForm.shareholderLink.show(); bcoForm.shareholderLink.click(); try { for (int j = 0; j <= shareholdersPage.shareholdersTable.count(); j++) { shareholdersTempList.add( shareholdersPage.shareholdersTable.getCell(1, j).getText()); } } catch (RuntimeException ignore){ logger.toLog("Shareholders List is missing "); } shareholders.put(bankName, shareholdersTempList); shareholdersPage.shareholdersTable.offCache(); back(); bcoForm.auditorsLink.show(); bcoForm.auditorsLink.click(); try { for (int j = 0; j <= auditorsPage.auditorsTable.count(); j++) { auditorsTempList.add( auditorsPage.auditorsTable.getCell(2, j).getText()); } } catch (RuntimeException ignore) { logger.toLog("Auditors List is missing"); } auditors.put(bankName, auditorsTempList); auditorsPage.auditorsTable.offCache(); back(); } } @Test(description = "Comparision Directors List With Auditors", dependsOnMethods = "testDirectorsAuditorsShareholders") public void testDirectorsAuditors() { int count=0; for (Map.Entry<String, ArrayList<String>> aud : auditors.entrySet()) { for (int i = 0; i < aud.getValue().size(); i++) { if (directors.entrySet().toString().contains(aud.getValue().get(i))) { logger.toLog(aud.getKey() + " = " + aud.getValue().get(i)); count++; } } } softAssert.assertTrue(count > 0, "Comparision Director With Auditors"); } @Test(description = "Comparision Directors List With Shareholders", dependsOnMethods = "testDirectorsAuditors") public void testDirectorsShareholders(){ int count=0; for (Map.Entry<String, ArrayList<String>> sh : shareholders.entrySet()) { for (int i = 0; i < sh.getValue().size(); i++) { if (directors.entrySet().toString().contains(sh.getValue().get(i))) { logger.toLog(sh.getKey() + " = " + sh.getValue().get(i)); count++; } } } softAssert.assertTrue(count > 0, "Comparision Director With Auditors"); } @Test(description = "Checking If There Are Entities Owned By The Same Shareholders", dependsOnMethods = "testDirectorsShareholders") public void testShareholdersChecking(){ HashMap<ArrayList<String>, List<String>> valueToKeyMapCounter = new HashMap<>(); for (Map.Entry<String, ArrayList<String>> entry : shareholders.entrySet()) { if (valueToKeyMapCounter.containsKey(entry.getValue())) { valueToKeyMapCounter.get(entry.getValue()).add(entry.getKey()); } else { List<String> keys = new ArrayList<>(); keys.add(entry.getKey()); valueToKeyMapCounter.put(entry.getValue(), keys); } } for (Map.Entry<ArrayList<String>, List<String>> counterEntry : valueToKeyMapCounter.entrySet()) { if (counterEntry.getValue().size() > 1) { logger.toLog("Duplicated Value:" + counterEntry.getKey() + " for Keys:" + counterEntry.getValue()); } } softAssert.assertTrue(!valueToKeyMapCounter.isEmpty(), "Shareholders duplicate records in the list"); softAssert.assertAll(); } }
package com.lr.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor public class SubjectType { private static final long serialVersionUID = -3558783123234905129L; private Integer subjectid; private String subjecttype; private Integer score; private String remark; private Integer readtype; }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import java.util.LinkedList; public final class pc extends a implements bnu { public int rfn; public int rto; public int rtp; public int rtq; public LinkedList<brg> rtr = new LinkedList(); public LinkedList<brg> rts = new LinkedList(); public LinkedList<brg> rtt = new LinkedList(); public int rtu; public int rtv; public int rtw; public amj rtx; public final int getRet() { return this.rfn; } protected final int a(int i, Object... objArr) { int fQ; byte[] bArr; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; aVar.fT(1, this.rfn); aVar.fT(2, this.rto); aVar.fT(3, this.rtp); aVar.fT(4, this.rtq); aVar.d(5, 8, this.rtr); aVar.d(6, 8, this.rts); aVar.d(7, 8, this.rtt); aVar.fT(8, this.rtu); aVar.fT(9, this.rtv); aVar.fT(10, this.rtw); if (this.rtx != null) { aVar.fV(11, this.rtx.boi()); this.rtx.a(aVar); } return 0; } else if (i == 1) { fQ = (((((((((f.a.a.a.fQ(1, this.rfn) + 0) + f.a.a.a.fQ(2, this.rto)) + f.a.a.a.fQ(3, this.rtp)) + f.a.a.a.fQ(4, this.rtq)) + f.a.a.a.c(5, 8, this.rtr)) + f.a.a.a.c(6, 8, this.rts)) + f.a.a.a.c(7, 8, this.rtt)) + f.a.a.a.fQ(8, this.rtu)) + f.a.a.a.fQ(9, this.rtv)) + f.a.a.a.fQ(10, this.rtw); if (this.rtx != null) { return fQ + f.a.a.a.fS(11, this.rtx.boi()); } return fQ; } else if (i == 2) { bArr = (byte[]) objArr[0]; this.rtr.clear(); this.rts.clear(); this.rtt.clear(); f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler); for (fQ = a.a(aVar2); fQ > 0; fQ = a.a(aVar2)) { if (!super.a(aVar2, this, fQ)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; pc pcVar = (pc) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; brg brg; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: pcVar.rfn = aVar3.vHC.rY(); return 0; case 2: pcVar.rto = aVar3.vHC.rY(); return 0; case 3: pcVar.rtp = aVar3.vHC.rY(); return 0; case 4: pcVar.rtq = aVar3.vHC.rY(); return 0; case 5: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); brg = new brg(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = brg.a(aVar4, brg, a.a(aVar4))) { } pcVar.rtr.add(brg); } return 0; case 6: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); brg = new brg(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = brg.a(aVar4, brg, a.a(aVar4))) { } pcVar.rts.add(brg); } return 0; case 7: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); brg = new brg(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = brg.a(aVar4, brg, a.a(aVar4))) { } pcVar.rtt.add(brg); } return 0; case 8: pcVar.rtu = aVar3.vHC.rY(); return 0; case 9: pcVar.rtv = aVar3.vHC.rY(); return 0; case 10: pcVar.rtw = aVar3.vHC.rY(); return 0; case 11: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); amj amj = new amj(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = amj.a(aVar4, amj, a.a(aVar4))) { } pcVar.rtx = amj; } return 0; default: return -1; } } } }
package by.epam.javaintro.classes.task01; import java.util.LinkedList; import java.util.Objects; public class District { private String name; private double square; private LinkedList<Town> townList; public District(String name, double square, LinkedList<Town> townList) { this.name = name; this.square = square; this.townList = new LinkedList<>(); setTownList(townList); } public District() { this.name = "Unnamed district"; this.square = 0.0; this.townList = new LinkedList<>(); } public void setName(String name) { this.name = name; } public void setSquare(double square) { this.square = square; } public void setTownList(LinkedList<Town> townList) { for (int i = 0; i < townList.size(); i++) { this.townList.add(townList.get(i)); } } public String getName() { return name; } public double getSquare() { return square; } public LinkedList<Town> getTownList() { return townList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; District district = (District) o; return Double.compare(district.square, square) == 0 && Objects.equals(name, district.name) && Objects.equals(townList, district.townList); } @Override public int hashCode() { return Objects.hash(name, square, townList); } @Override public String toString() { return "District{" + "name='" + name + '\'' + ", square=" + square + ", townList=" + townList + '}'; } }
package mobpartner.sampleappwithmobpartner; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.mopub.mobileads.MoPubErrorCode; import com.mopub.mobileads.MoPubInterstitial; import com.mopub.mobileads.MoPubView; public class MoPubWithHTML extends Activity implements MoPubInterstitial.InterstitialAdListener{ private MoPubView mMoPubView; private MoPubInterstitial mMoPubInterstitial; private Button bannerButton; private Button interstitialButtonLoad, interstitialButtonShow; final String BannerAdUnitId = "3bbfb17fb43b4079a723b966caa046e7"; final String InterstitalAdUnitId = "35a59eaf31694af7920328b1595157f6"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mopub_with_html); mMoPubView = (MoPubView) findViewById(R.id.banner_mopubview); bannerButton = (Button) findViewById(R.id.button_banner); interstitialButtonLoad = (Button) findViewById(R.id.button_interstitial_load); interstitialButtonShow = (Button) findViewById(R.id.button_interstitial_show); interstitialButtonShow.setEnabled(false); mMoPubInterstitial = new MoPubInterstitial(this, InterstitalAdUnitId); mMoPubInterstitial.setInterstitialAdListener(this); loadMoPubBannerAd(); bannerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadMoPubBannerAd(); } }); interstitialButtonLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mMoPubInterstitial.load(); } }); interstitialButtonShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mMoPubInterstitial.show(); } }); } private void loadMoPubBannerAd(){ mMoPubView.setAdUnitId(BannerAdUnitId); mMoPubView.setAutorefreshEnabled(true); mMoPubView.loadAd(); } @Override public void onInterstitialLoaded(MoPubInterstitial interstitial) { interstitialButtonShow.setEnabled(true); } @Override public void onInterstitialFailed(MoPubInterstitial interstitial, MoPubErrorCode errorCode) { } @Override public void onInterstitialShown(MoPubInterstitial interstitial) { interstitialButtonShow.setEnabled(false); } @Override public void onInterstitialClicked(MoPubInterstitial interstitial) { } @Override public void onInterstitialDismissed(MoPubInterstitial interstitial) { } @Override protected void onDestroy() { super.onDestroy(); mMoPubView.destroy(); if (mMoPubInterstitial != null) { mMoPubInterstitial.destroy(); mMoPubInterstitial = null; } } }
package br.com.diegomelo.cleanparse.model; import java.util.List; public class AttributeListPojo { private List<String> listValue; public List<String> getListValue() { return listValue; } public void setListValue(List<String> listValue) { this.listValue = listValue; } }
package ru.otus.dataset; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.io.Serializable; @Data @EqualsAndHashCode @Entity @Table(name = "user_groups") public class GroupEntity implements DataSet, Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private long id; @Basic @Column(name = "groupname") private String groupname; @Basic @Column(name = "login") private String login; @Override public String getName() { return getGroupname(); } @Override public void setName(String name) { setGroupname(name); } }
package net.sf.orassist; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ProcessMonitor { volatile private List<PipeMessage> messageQueue = new LinkedList<PipeMessage>(); synchronized public void put(PipeMessage message) { messageQueue.add(message); notify(); } synchronized public PipeMessage get() { while (messageQueue.size() == 0) { try { wait(); } catch (InterruptedException e) { // got notified } } return messageQueue.remove(0); } private InputStreamReader reader; private InputStreamReader errReader; private PrintWriter writer; private volatile boolean stopped = false; final private String prompt; public ProcessMonitor(InputStream inputStream, InputStream errorStream, OutputStream outputStream, String prompt, String encoding) throws UnsupportedEncodingException { this.reader = new InputStreamReader(inputStream, encoding); this.errReader = new InputStreamReader(errorStream, encoding); this.writer = new PrintWriter(new OutputStreamWriter(outputStream)); this.prompt = prompt; } public void start() { new Thread(new Runnable(){ private InputStreamReader threadReader = reader; public void run() { try { int ch; String s = ""; for (;!stopped && (ch = this.threadReader.read()) != -1;) { s += (char)ch; if ((char)ch == '\n' || s.matches(prompt)) { put(new PipeMessage(s, null, false)); s = ""; } } put(new PipeMessage(null, null, true)); } catch (IOException e) { new RuntimeException(e); } }}).start(); new Thread(new Runnable(){ private InputStreamReader threadReader = errReader; public void run() { try { int ch; String s = ""; for (;!stopped && (ch = this.threadReader.read()) != -1;) { s += (char)ch; if ((char)ch == '\n' || s.matches(prompt)) { put(new PipeMessage(s, null, false)); s = ""; } } put(new PipeMessage(null, null, true)); } catch (IOException e) { new RuntimeException(e); } }}).start(); } public void stop() { stopped = true; } public void write(CharSequence message) { writer.append(message); writer.flush(); } }
package com.immotor.bluetoothadvertiser.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import com.immotor.bluetoothadvertiser.App; import com.immotor.bluetoothadvertiser.Constants; import com.immotor.bluetoothadvertiser.R; import com.immotor.bluetoothadvertiser.service.GattService; import com.immotor.bluetoothadvertiser.service.WebService; import java.util.ArrayList; import java.util.List; /** * Created by ForestWang on 2016/4/1. */ public class AdvertiserActivity extends AppCompatActivity { private static final int MAX_LINES = 50; private List<String> mLogs; private TextView mTextViewLog; private Button mStartButton; private Button mStopButton; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { StringBuilder sb = new StringBuilder(); for (int index = mLogs.size() - 1; index >= 0; index--) { sb.append(String.format("%02d: ", index)); sb.append(mLogs.get(index)); sb.append("\n"); } mTextViewLog.setText(sb.toString()); } } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Constants.LOCAL_INTENT_ACTION_LOG.equals(intent.getAction())) { String log = intent.getStringExtra(Constants.EXTRA_LOG); if (mLogs.size() >= MAX_LINES) { mLogs.remove(0); } mLogs.add(log); mHandler.sendEmptyMessage(1); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_advertiser); mTextViewLog = (TextView) findViewById(R.id.textViewLog); mLogs = new ArrayList(); mStartButton = (Button) findViewById(R.id.buttonStart); mStopButton = (Button) findViewById(R.id.buttonStop); if (!App.DEBUG) { mStartButton.setVisibility(View.GONE); mStopButton.setVisibility(View.GONE); } else { mStartButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(AdvertiserActivity.this, GattService.class); startService(it); Intent webIT = new Intent(AdvertiserActivity.this, WebService.class); startService(webIT); mStartButton.setVisibility(View.GONE); mStopButton.setVisibility(View.VISIBLE); } }); mStopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(AdvertiserActivity.this, GattService.class); stopService(it); Intent webIT = new Intent(AdvertiserActivity.this, WebService.class); stopService(webIT); mStartButton.setVisibility(View.VISIBLE); mStopButton.setVisibility(View.GONE); } }); } } @Override protected void onResume() { super.onResume(); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(Constants.LOCAL_INTENT_ACTION_LOG)); } @Override protected void onPause() { super.onPause(); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } }
/******************************************************************************* * Copyright (c) 2017 Luke Collins and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the license * which accompanies this distribution * * Contributors: * Luke Collins *******************************************************************************/ package net.lukecollins.dev.cloudflare; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; public class CfConstantsTestUtil { @BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("ConstantsTest- Setup before class"); } @AfterClass public static void tearDownAfterClass() throws Exception { System.out.println("ConstantsTest - Teardown after class"); } @Before public void setUp() throws Exception { System.out.println("ConstantsTest - Setup"); } @After public void tearDown() throws Exception { System.out.println("ConstantsTest - Teardown"); } @org.junit.Test public void testUsernameValid() { assertTrue("<CloudFlare User Name>".equals(CfConstantsUtil.USERNAME)); } @org.junit.Test public void testApiKeyValid() { assertTrue("<CloudFlare API Key>".equals(CfConstantsUtil.APIKEY)); } @org.junit.Test public void testUrlValid() { assertTrue("https://api.cloudflare.com/client".equals(CfConstantsUtil.URL)); } @org.junit.Test public void testVersionValid() { assertTrue("v4".equals(CfConstantsUtil.VERSION)); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by SangEun on 2019-12-13. */ public class p5 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("What is the first number? "); String firstStr = br.readLine(); System.out.print("What is the second number? "); String secondStr = br.readLine(); int firstNum = ConvertUtil.parseStringToInt(firstStr); int secondNum = ConvertUtil.parseStringToInt(secondStr); if(firstNum < 0 || secondNum < 0) { throw new NumberFormatException(); } System.out.println(firstNum + " + " + secondNum + " = " + getPlus(firstNum, secondNum) + "\n" + firstNum + " - " + secondNum + " = " + getMinus(firstNum, secondNum) + "\n" + firstNum + " * " + secondNum + " = " + getMultiple(firstNum, secondNum) + "\n" + firstNum + " / " + secondNum + " = " + getDivision(firstNum, secondNum) + "\n"); } private static int getDivision(int firstNum, int secondNum) { return firstNum / secondNum; } private static int getMultiple(int firstNum, int secondNum) { return firstNum * secondNum; } private static int getMinus(int firstNum, int secondNum) { return firstNum - secondNum; } private static int getPlus(int firstNum, int secondNum) { return firstNum + secondNum; } }
package com.tencent.mm.model; import com.tencent.mm.bt.h.d; import com.tencent.mm.storage.n; class c$8 implements d { c$8() { } public final String[] xb() { return n.diD; } }
package com.hua.beautifulimage.ui.activity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.Point; import android.graphics.Rect; import android.support.design.widget.AppBarLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import com.hua.beautifulimage.R; import com.hua.beautifulimage.application.BApplication; import com.hua.beautifulimage.entity.Pictures; import com.hua.beautifulimage.ui.adapter.OnItemClickListener; import com.hua.beautifulimage.ui.adapter.ShowPictureAdapter; import com.hua.beautifulimage.ui.adapter.ShowPicturePagerAdapter; import com.hua.beautifulimage.ui.view.HackyViewPager; import com.hua.beautifulimage.utils.Constants; import com.hua.beautifulimage.utils.L; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import rx.Subscriber; public class ShowImageActivity extends AppCompatActivity { @Bind(R.id.show_tool_bar) Toolbar mToolbar; @Bind(R.id.show_recycler_view) RecyclerView mRecyclerView; @Bind(R.id.show_pager_layout) FrameLayout expandLayout; @Bind(R.id.show_hacky_view_pager) HackyViewPager hackyViewPager; @Bind(R.id.show_app_bar_layout) AppBarLayout appBarLayout; private List<Pictures.Picture> mList; private ShowPictureAdapter mAdapter; private Animator mAnimator; private int animTime = 300; private boolean isShowPager = false; private ImageView thumbPicture; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_image); ButterKnife.bind(this); init(); } private void init() { mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white)); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Toolbar上添加箭头 getSupportActionBar().setDisplayShowHomeEnabled(true); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); if(mList == null) { mList = new ArrayList<>(); } mAdapter = new ShowPictureAdapter(this, mList); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(View view, int position) { L.i("position = " + position); showPictureInViewPager((ImageView) view, mList, position); } }); Intent intent = getIntent(); int id = intent.getIntExtra(Constants.EXTRA_SHOW_PICTURE_ID, 1); getPictures(id); } private void showPictureInViewPager(ImageView thumbImage, List<Pictures.Picture> list, int position){ if(mAnimator != null) { mAnimator.cancel(); } thumbPicture = thumbImage; ShowPicturePagerAdapter pagerAdapter = new ShowPicturePagerAdapter(list); hackyViewPager.setAdapter(pagerAdapter); hackyViewPager.setCurrentItem(position); final Rect startBounds = new Rect(); final Rect finalBounds = new Rect(); Point globalOffset = new Point(); thumbImage.getGlobalVisibleRect(startBounds); expandLayout.getGlobalVisibleRect(finalBounds, globalOffset); startBounds.offset(-globalOffset.x, -globalOffset.y); finalBounds.offset(-globalOffset.x, -globalOffset.y); float scale; if(((float)finalBounds.width() / finalBounds.height()) > ((float)startBounds.width() / startBounds.height())) { scale = (float) startBounds.height() / finalBounds.height(); float startWidth = finalBounds.width() * scale; float deltaWidth = (startWidth - startBounds.width()) / 2; startBounds.left -= deltaWidth; startBounds.right += deltaWidth; }else { scale = (float) startBounds.width() / finalBounds.width(); float startHeight = finalBounds.height() * scale; float deltaHeight = (startHeight - startBounds.height()) / 2; startBounds.top -= deltaHeight; startBounds.bottom += deltaHeight; } expandLayout.setPivotX(0); expandLayout.setPivotY(0); thumbImage.setAlpha(0f); expandLayout.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.play(ObjectAnimator.ofFloat(expandLayout, View.X, startBounds.left, finalBounds.left)) .with(ObjectAnimator.ofFloat(expandLayout, View.Y, startBounds.top, finalBounds.top)) .with(ObjectAnimator.ofFloat(expandLayout, View.SCALE_X, scale, 1f)) .with(ObjectAnimator.ofFloat(expandLayout, View.SCALE_Y, scale, 1f)); set.setDuration(animTime); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); isShowPager = true; hideViews(); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mAnimator = null; } @Override public void onAnimationCancel(Animator animation) { super.onAnimationCancel(animation); mAnimator = null; } }); set.start(); mAnimator = set; } private void closePicturePager() { thumbPicture.setAlpha(1f); expandLayout.animate().alpha(0f).setInterpolator(new DecelerateInterpolator(2)).setDuration(200).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { expandLayout.setVisibility(View.GONE); expandLayout.setAlpha(1f); } }); isShowPager = false; showViews(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if (isShowPager) { closePicturePager(); return true; } } return super.onKeyDown(keyCode, event); } private void getPictures(int id) { BApplication.mHttpMethod.show(new Subscriber<Pictures>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Pictures pictures) { mToolbar.setTitle(pictures.getTitle()); mList.clear(); mList.addAll(pictures.getList()); mAdapter.notifyDataSetChanged(); } }, id); } private void hideViews() { appBarLayout.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2)); } private void showViews() { appBarLayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)); } }
package com.moon.utils; import org.apache.commons.lang.StringUtils; /** * 42位的时间前缀+10位的节点标识+12位的sequence避免并发的数字(12位不够用时强制得到新的时间前缀) * <p/> * <b>对系统时间的依赖性非常强,需要关闭ntp的时间同步功能,或者当检测到ntp时间调整后,拒绝分配id。 * * @author sumory.wu * @date 2012-2-26 下午6:40:28 */ public enum IdGenerator { ID_GENERATOR; private static final String WORK_ID_CONFIG_DATA="WORK_ID_DATA"; private final long workerId; private final long snsEpoch = 1330328109047L;// 起始标记点,作为基准 private long sequence = 0L;// 0,并发控制 private final long workerIdBits = 10L;// 只允许workid的范围为:0-1023 private final long sequenceBits = 12L;// sequence值控制在0-4095 private final long workerIdShift = this.sequenceBits;// 12 private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;// 22 private final long sequenceMask = -1L ^ -1L << this.sequenceBits;// 4095,111111111111,12位 private long lastTimestamp = -1L; IdGenerator() { String workIdStr ="12"; if(StringUtils.isBlank(workIdStr)){ workIdStr="0"; } workerId = new Long(workIdStr); } public synchronized long nextId() { long timestamp = this.timeGen(); // 如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环),下次再使用时sequence是新值 if (this.lastTimestamp == timestamp) { this.sequence = this.sequence + 1 & this.sequenceMask; if (this.sequence == 0) { timestamp = this.tilNextMillis(this.lastTimestamp);// 重新生成timestamp } } else { this.sequence = 0; } //这个情况出现概率小 可忽略 /*if (timestamp < this.lastTimestamp) { }*/ this.lastTimestamp = timestamp; // 生成的timestamp return timestamp - this.snsEpoch << this.timestampLeftShift | this.workerId << this.workerIdShift | this.sequence; } /** * 保证返回的毫秒数在参数之后 * * @param lastTimestamp * @return */ /** * @param lastTimestamp 最后一次时间毫秒数 * @return 返回的毫秒数 * @Description 保证返回的毫秒数在参数之后 * @Author xiongwenyou 2016/12/5 * @modify xiongwenyou 2016/12/5 * @see #timeGen() */ private long tilNextMillis(long lastTimestamp) { long timestamp = this.timeGen(); while (timestamp <= lastTimestamp) { timestamp = this.timeGen(); } return timestamp; } /** * @return 当前时间的毫秒数 * @Description 得到当前时间毫秒 * @Author xiongwenyou 2016/12/5 * @modify xiongwenyou 2016/12/5 * @see System#currentTimeMillis() */ private long timeGen() { return System.currentTimeMillis(); } }
package com.paisheng.instagme.base; import com.paisheng.lib.mvp.network.INetworkView; import com.paisheng.lib.mvp.network.NetworkPresenter; import com.paisheng.lib.network.IRequestManager; import com.paisheng.lib.network.RequestCall; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * @author: yuanbaining * @Filename: BaseIMPresenter * @Description: Presenter中间层,预留 * @Copyright: Copyright (c) 2017 Tuandai Inc. All rights reserved. * @date: 2018/1/25 16:02 */ public class BaseIMPresenter<T extends INetworkView> extends NetworkPresenter<T> { }
/* * 官网地站:http://www.ShareSDK.cn * 技术支持QQ: 4006852216 * 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复) * * Copyright (c) 2013年 ShareSDK.cn. All rights reserved. */ package cn.sharesdk.onekeyshare; import java.util.HashMap; import javax.crypto.Mac; import com.chuxin.family.R; import com.chuxin.family.utils.CxLog; import android.app.Activity; import android.os.Handler; import android.widget.Toast; import cn.sharesdk.framework.Platform; import cn.sharesdk.framework.PlatformActionListener; /** * OneKeyShareCallback是快捷分享功能的一个“外部回调”示例。 *演示了如何通过添加extra的方法,将快捷分享的分享结果回调到 *外面来做自定义处理。 */ public class OneKeyShareCallback implements PlatformActionListener { Activity mActivity; private OneKeyShareCallback(){}; public OneKeyShareCallback(Activity activity){ mActivity = activity; } private void showTip(final String str){ if (null == mActivity) { return; } new Handler(mActivity.getMainLooper()){ public void handleMessage(android.os.Message msg) { Toast.makeText(mActivity, str, Toast.LENGTH_SHORT).show(); }; }.sendEmptyMessage(0); } public void onComplete(Platform plat, int action, HashMap<String, Object> res) { System.out.println(res.toString()); // 在这里添加分享成功的处理代码 showTip(/*plat.getName()+*/mActivity.getString(R.string.share_completed)); } public void onError(Platform plat, int action, Throwable t) { t.printStackTrace(); // 在这里添加分享失败的处理代码 // CxLog.i("OneKeyShareCallback_men", plat.getName()+">>"+action); showTip(/*plat.getName()+*/mActivity.getString(R.string.share_failed)); } public void onCancel(Platform plat, int action) { // 在这里添加取消分享的处理代码 showTip(/*plat.getName()+*/mActivity.getString(R.string.share_canceled)); } }
package com.example.restauth.infrastructure; import java.util.HashMap; import org.springframework.stereotype.Service; import com.example.restauth.domain.User; import com.example.restauth.domain.UserAlreadyExistsException; import com.example.restauth.domain.UserRepository; /** * * In memory implementation of the UserRepository interface * */ @Service public class InMemoryUserRepository implements UserRepository { private HashMap<String, User> userStore; public InMemoryUserRepository() { this.userStore = new HashMap<String, User>(); } /** * Adds a user to the repository, throws UserAlreadyExistsException if the user already exists */ @Override public void storeUser(User user) throws UserAlreadyExistsException { if (this.userStore.containsKey(user.getUsername())) { throw new UserAlreadyExistsException(); } this.userStore.put(user.getUsername(), user); } /** * Retrieves the user with the specified username */ @Override public User findByUsername(String userName) { return this.userStore.get(userName); } }
package com.weboot.book.model; import javax.persistence.Entity; /** * @author Yaroslav Bondarchuk * Date: 02.01.2016 * Time: 17:52 */ public enum MasterType { BEAUTICIAN, HAIRDRESSER, MANICURE_MASTER }
package utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; public class AlternativeConsole { private PrintStream originalOut,originalErr; private ByteArrayOutputStream out,err; private boolean outClosed, errClosed; public AlternativeConsole() { // out this.originalOut = System.out; this.out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); this.outClosed = false; // err this.originalErr = System.err; this.err = new ByteArrayOutputStream(); System.setErr(new PrintStream(err)); this.errClosed = false; } public void reset() { try { out.flush(); out.close(); System.setOut(originalOut); this.outClosed = true; err.flush(); err.close(); System.setErr(originalErr); this.errClosed = true; } catch (IOException e) { e.printStackTrace(); } } public String getOutString() { if(outClosed) { throw new RuntimeException("Output print stream is already closed"); } return out.toString(); } public String getErrString() { if(errClosed) { throw new RuntimeException("Error print stream is already closed"); } return err.toString(); } }
package labs; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; public class HashSet<T> implements Set<T> { private ArrayList<LinkedList<T>> structure; private int size; public HashSet() { clear(); } @Override public void clear() { // Let the garbage collector to the actual work for us :-) structure = new ArrayList<LinkedList<T>>(); for (int i = 0; i < 13; i++) { structure.add(new LinkedList<T>()); } size = 0; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean add(T arg0) { // Hint: use arg0.hashCode(); // Hint: do proper bookkeeping on the size int hashcode=arg0.hashCode()%12; //hashes and stores the value of the hash of the value to be added to the set if(structure.get(hashcode).size()!=0){ if(structure.get(hashcode).contains(arg0)==false) //checking to make sure it isn't already in there! structure.get(hashcode).add(arg0); //grabs the existing linked list and throws the new value into it } else { LinkedList<T> node=new LinkedList<T>(); //will be used to store the list of values in the hash set node.add(arg0); //adds the value to the linked list structure.set(hashcode,node); //puts the linked list in the space assigned for it in hashing size++; } if(contains(arg0)==true) return true; else return false; } @Override public boolean contains(Object o) { int hashcode=o.hashCode()%12; //determines the hash for the value we're checking for if(structure.get(hashcode)==null) //checks to see if there even is a linked list at the hash value return false; else //if there is, it continues on! { if(structure.get(hashcode).contains(o)==true) //checks to see if the linked list at the hash value contains the value return true; else return false; } } @Override public boolean remove(Object o) { if(contains(o)==false) //checks to make sure that the value is in fact in the set in the first place return false; else{ int hashcode=o.hashCode()%12; //determines the hash code to make sure we get can delete the value if(structure.get(hashcode).remove(o)==true) //this removes the value and will check to make sure it was successful return true; else return false; } } @Override public Iterator<T> iterator() { return new Iterator<T>() { int i = 0; Iterator<T> iterator = structure.get(0).iterator(); { update(); } private void update() { if (i > 12) return; while(iterator.hasNext()) { i++; iterator = structure.get(i).iterator(); } } @Override public boolean hasNext() { update(); return iterator.hasNext(); } @Override public T next() { update(); return iterator.next(); } }; } // These are all pretty similar in terms of implementation @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public boolean addAll(Collection arg0) { int hashcode=arg0.hashCode()%12; if(structure.contains(hashcode)==false){ LinkedList<T> list=new LinkedList<T>(); list.addAll(arg0); structure.add(hashcode,list); size++; } else structure.get(hashcode).addAll(arg0); if(containsAll(arg0)==true) return true; else return false; } @SuppressWarnings("rawtypes") @Override public boolean containsAll(Collection arg0) { int hashcode=arg0.hashCode()%12; if(structure.get(hashcode)==null) return false; else{ if(structure.get(hashcode).contains(arg0)==true) return true; else return false; } } @SuppressWarnings("rawtypes") @Override public boolean removeAll(Collection arg0) { if(contains(arg0)==false) //checks to make sure that the value is in fact in the set in the first place return false; else{ int hashcode=arg0.hashCode()%12; //determines the hash code to make sure we get can delete the value if(structure.get(hashcode).removeAll(arg0)==true) //this removes the value and will check to make sure it was successful return true; else return false; } } @Override public Object[] toArray() { // TODO Auto-generated method stub Object[] result=new Object[size]; for(int i=0;i<structure.size();i++) //this should iterate through all of the hash values result[i]=structure.get(i).toArray(); //and this should push the linked lists into the array return result; } // Don't bother implementing, unless you want to do reflection. @Override public <T> T[] toArray(T[] a) { // TODO Auto-generated method stub return null; } // Don't bother implementing. @Override public boolean retainAll(Collection arg0) { // TODO Auto-generated method stub return false; } }
package day22_string_manipulation; public class DynamicSubstring { public static void main(String[] args) { String result = "result count:12345"; System.out.println(result.substring(13,18));// same System.out.println(result.substring(13)); System.out.println(result.indexOf(":")); int colonIndex = result.indexOf(":"); System.out.println(result.substring(colonIndex+1)); // now we can combine them in one line System.out.println("****************"); System.out.println(result.substring(result.indexOf(":")+1)); String today ="I learned [java] today"; int start = today.indexOf("["); int end = today.indexOf("]"); System.out.println(today.substring(start+1, end)); // System.out.println(today.substring(today.indexOf("["))); // System.out.println(today.substring(today.indexOf("]"))); System.out.println(today.substring(today.indexOf("[")+1,today.indexOf("]"))); } }
package com.example.dev.activity; import android.os.Bundle; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.base.adev.activity.BaseTabBottomActivity; import com.example.dev.R; import com.example.dev.fragment.DemoFragment; import com.example.dev.fragment.HomeFragment; import com.example.dev.fragment.MeFragment; public class MainActivity extends BaseTabBottomActivity { @Override protected void initContentView(Bundle bundle) { setContentView(R.layout.activity_base_tab_bottom); } @Override protected void initLogic() { addItem(new HomeFragment(), R.drawable.ic_tab_home_white_24dp, R.string.tab1, R.color.colorPrimary); addItem(new DemoFragment(), R.drawable.ic_tab_book_white_24dp, R.string.tab2, R.color.colorPrimaryDark); addItem(new MeFragment(), R.drawable.ic_tab_tv_white_24dp, R.string.tab_me, R.color.colorAccent); setNavBarStyle(BottomNavigationBar.MODE_FIXED, BottomNavigationBar.BACKGROUND_STYLE_STATIC); initialise(R.id.ll_content); } @Override protected void getBundleExtras(Bundle extras) { } @Override public void onTabSelected(int position) { super.onTabSelected(position); } }
package org.training.controller.commands.holder; import org.training.controller.commands.Command; import java.util.Map; /** * Created by nicko on 1/25/2017. */ public class CommandHolder { private Map<String, Command> getCommands; private Map<String, Command> postCommands; public CommandHolder(Map<String, Command> postCommands, Map<String, Command> getCommands) { this.postCommands = postCommands; this.getCommands = getCommands; } private Command getPostCommand(String url) { return postCommands.get(url); } private Command getGetCommand(String url) { return getCommands.get(url); } public Command getCommand(String method, String url) { Command command = null; if ("POST".equals(method)) { command = getPostCommand(url); } else if ("GET".equals(method)) { command = getGetCommand(url); } if (command != null) { return command; } else { return null; } } public Command getPageNotFoundCommand() { return null; } }
package org.example.snovaisg.myuploadFCT; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.text.SimpleDateFormat; /** * Created by Miguel-PC on 03/03/2018. */ public class UploadPageSopa extends AppCompatActivity { public DataHolder DH = new DataHolder().getInstance(); String fileToInternal = DH.fileToInternal(); String PrecoInvalido = DH.PrecoInvalido(); String restaurante = DH.getData(); public static String[] sopa = new String[8]; public static String[] preco = new String[8]; int[] ids; int[] ids_preco; // para fazer auto fill quando se volta à página public String[] backupPrato = new String[8]; public String[] backupPreco = new String[8]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_sopa); ids = new int[]{R.id.Sopa1, R.id.Sopa2, R.id.Sopa3, R.id.Sopa4, R.id.Sopa5, R.id.Sopa6, R.id.Sopa7, R.id.Sopa8}; ids_preco = new int[]{R.id.sopaPreco1, R.id.sopaPreco2, R.id.sopaPreco3, R.id.sopaPreco4, R.id.sopaPreco5, R.id.sopaPreco6, R.id.sopaPreco7, R.id.sopaPreco8}; Preencher(); try { Editar(); } catch (JSONException e) { e.printStackTrace(); } Button cancelar = (Button) findViewById(R.id.button4); cancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { DH.setEditar(false); if (getEstado()) { Intent intent = new Intent(UploadPageSopa.this, Atualizado.class); startActivity(intent); } else { Intent intent = new Intent(UploadPageSopa.this, PorAtualizar.class); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); } } }); Button seguinte = (Button) findViewById(R.id.button2); seguinte.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getAll(); Intent intent = new Intent(UploadPageSopa.this, UploadPageCarne.class); startActivity(intent); } }); } public void getAll(){ String prato; String temp_preco; String [] ans = new String[8]; int pos = 0; for (int i = 0; i<= 7;i++){ EditText tempPrato = (EditText) findViewById(ids[i]); prato = tempPrato.getText().toString(); Log.d("PRATO","<"+prato+">"); if (!prato.isEmpty() && prato.trim().length() > 0) { Log.d("Prato","im IN"); sopa[pos] = prato; EditText tempPreco = (EditText) findViewById(ids_preco[i]); temp_preco = tempPreco.getText().toString(); if (!temp_preco.isEmpty() && temp_preco.trim().length() > 0) preco[pos] = temp_preco; else preco[pos] = PrecoInvalido; } else{ Log.d("Prato","NOT IN"); sopa[pos]=null; preco[pos]=null; } pos++; } } public void Preencher() { if (!DH.getDenovo()) { if (sopa != null) { int e = sopa.length; for (int i = 0; i < e; i++) { if (sopa[i] != null) { //prato EditText temp = (EditText) findViewById(ids[i]); temp.setText(sopa[i]); //preco EditText temp2 = (EditText) findViewById(ids_preco[i]); if (preco[i] != PrecoInvalido || preco[i].isEmpty()) temp2.setText(preco[i]); } } } } } public void Editar() throws JSONException { if (DH.getEditar()){ Log.d("Editar","1"); JSONObject fullmenu = readJsonFromFile(fileToInternal); JSONObject menu = fullmenu.getJSONObject(restaurante); String [] carneV1 = toStringArray(menu.getJSONArray("sopa")); Log.d("Editar","2"); int pos = 0; for (int i = 0; i < carneV1.length; i = i + 2) { Log.d("Editar","3"); if (carneV1[i] != null && carneV1[i+1] != null) { Log.d("Editar","4"); //prato EditText temp = (EditText) findViewById(ids[pos]); temp.setText(carneV1[i]); //preco EditText temp2 = (EditText) findViewById(ids_preco[pos]); if (!carneV1[i+1].equals(PrecoInvalido) && !carneV1[i+1].isEmpty()) temp2.setText(carneV1[i+1]); pos++; } } } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); int pos = 0; if (sopa != null) { for (int i = 0; i < sopa.length; i++) { if (sopa[i] != null){ if (sopa[i].trim().length() >0){ savedInstanceState.putString(backupPrato[pos], sopa[i]); savedInstanceState.putString(backupPreco[pos],preco[i]); pos++; } } } } } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); int pos = 0; if (backupPrato != null){ for (int i = 0;i < backupPrato.length;i++){ sopa[i] = backupPrato[i]; preco[i] = backupPreco[i]; } } } public boolean getEstado() throws JSONException { JSONObject fullDic = readJsonFromFile(fileToInternal); String weekId = fullDic.getJSONObject(restaurante).getString("weekId"); String timeStamp = new SimpleDateFormat("dd-MM-yyyy").format(new java.util.Date()); Log.d("TESTE",weekId); Log.d("TESTE",timeStamp); return weekId.equals(timeStamp); } public JSONObject readJsonFromFile(String filename){ String JsonData =""; JSONObject myJson; try { FileInputStream fis = this.openFileInput(filename); int size = fis.available(); byte[] buffer = new byte[size]; fis.read(buffer); fis.close(); JsonData = new String(buffer); Log.d("Hallo",JsonData); myJson = new JSONObject(JsonData); int a = 1 + 2; return myJson; } catch (Exception e) { e.printStackTrace(); Log.d("MEH","Something went wrong"); return null; } } public static String[] toStringArray(JSONArray array) { if (array == null) return null; String[] arr = new String[array.length()]; for (int i = 0; i < arr.length; i++) { arr[i] = array.optString(i); } return arr; } }
/*Reorder List question: http://www.lintcode.com/en/problem/reorder-list/ Given a singly linked list L: L0ˇúL1ˇúˇ­ˇúLn-1ˇúLn, reorder it to: L0ˇúLnˇúL1ˇúLn-1ˇúL2ˇúLn-2ˇúˇ­ You must do this in-place without altering the nodes' values. Example For example, Given 1->2->3->4->null, reorder it to 1->4->2->3->null. */ package FastSlowPointers; import useDummyNodes.ListNode; /* 1) Find the middle node 2) Reverse the second part of the list 3) Merge the first and the second list*/ public class ReorderList { public static ListNode reorderlist(ListNode head){ if (head == null || head.next == null){ return head; } //1. get middle ListNode middle = findmiddle(head); //2. reverse the right part ListNode right = reverse(middle.next); middle.next = null; //3. merge the left part and the right part return merge(head, right); } private static ListNode findmiddle(ListNode head) { if (head == null || head.next == null){ return head; } ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } private static ListNode reverse(ListNode head) { if (head == null || head.next == null){ return head; } ListNode newhead = null; while (head != null){ ListNode temp = head.next; head.next = newhead; newhead = head; head = temp; } return newhead; } private static ListNode merge(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(0); ListNode tail = dummy; int index = 0; while (head1 != null && head2 != null){ if (index % 2 == 0){//0 % 2 == 0; 1 % 2 == 1; 2 % 2 == 0 tail.next = head1; head1 = head1.next; }else{ tail.next = head2; head2 = head2.next; } tail = tail.next; index++; } while (head1 != null){ tail.next = head1; } while (head2 != null){ tail.next = head2; } return dummy.next; } public static void main(String[] args) { // TODO Auto-generated method stub /*Given 1->2->3->4->null, reorder it to 1->4->2->3->null.*/ ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(4); ListNode n3 = new ListNode(2); ListNode n4 = new ListNode(3); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = null; System.out.println(reorderlist(n1).val); } }
package wrapper; import java.util.Scanner; public class ucgenincevresi { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Lutfen uc sayi giriniz"); int sayi1 = scan.nextInt(); int sayi2 = scan.nextInt(); int sayi3 = scan.nextInt(); System.out.println(sayi1 + sayi2 + sayi3); } }
package AbstractDemo; /** * The keyword 'abstract' is a non-access modifier. Abstract class working in a * similar way as the superclass, so the subclass should implement all methods * from abstract class or be abstract. Any class which has more than one * abstract method must be initialized as abstract. Abstract classes cannot be * used to create objects, so the instance of the not be received by using the * keyword 'new'. Abstract methods cannot be static and constructors cannot be * abstract. The difference with the interface, that abstract classes can have * abstract and regular methods together. Moreover, in the abstract can be * declared variables, in the interface they should be final. * * @author Bohdan Skrypnyk */ // create an abstract class abstract class Figure { double dim1; double dim2; Figure(double dim1, double dim2) { this.dim1 = dim1; this.dim2 = dim2; } abstract double area(); } class Rectangle extends Figure { public Rectangle(double dim1, double dim2) { super(dim1, dim2); } @Override double area() { System.out.println("Area of Rectangle"); return dim1 + dim2; } } class Triangle extends Figure { public Triangle(double dim1, double dim2) { super(dim1, dim2); } @Override double area() { System.out.println("Area of Triangle"); return dim1 + dim2 / 2; } } public class AbstractAreas { public static void main(String args[]) { // Abstract classes cannot be used to create objects, // so the instance of the not be received by using the keyword 'new'. //Figure figure = new Figure (12,2); // an abstract class can be accessed through the subclasses Rectangle rectangle = new Rectangle(9, 8); Triangle triangle = new Triangle(10, 5); Figure figure; // or via class reference figure = rectangle; System.out.println("Area equal = " + figure.area() + "\n"); figure = triangle; System.out.println("Area equal = " + figure.area()); } }
package com.tencent.tencentmap.mapsdk.a; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Rect; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import com.tencent.tencentmap.mapsdk.a.rv.a; import com.tencent.tencentmap.mapsdk.a.td.1; import com.tencent.tencentmap.mapsdk.a.tz.j; public final class sl implements a, se.a { public static int a = 0; public static int b = 0; public static int c = 0; public static int d = 0; public static int e = 0; public static int f = 0; public static int g = 0; public static int h = 0; private static volatile Context i; private static boolean x = true; private static volatile String z = re.a(re.b); private boolean A = false; private boolean B = false; private rr C; private rk D; private tw j; private sf k; private sh l; private sm m; private 1 n; private tq o; private sg p; private si q; private sf$1 r; private volatile tb s; private ta t; private int u = 1; private j v = null; private boolean w = false; private Rect y = null; public sl(tw twVar) { i = twVar.getContext().getApplicationContext(); te.a().a(i); sy.a().a(i); sk.a().a(i); sn.l(); this.j = twVar; this.r = new sf$1(this); this.s = new tb(this); this.p = new sg(this); this.q = new si(this); this.t = new ta(this); this.k = new sf(this); this.l = new sh(this); this.m = new sm(this); this.n = new 1(this); this.o = new tq(this); this.q.a(); LayoutParams layoutParams = new LayoutParams(-1, -1); twVar.addView(this.l, layoutParams); twVar.addView(this.t, layoutParams); twVar.addView(this.s, layoutParams); this.r.b(1); this.r.a(true); this.r.c(0); this.D = new rk(); this.D.a(); new rv(i, this).a(); new se(i, this).a(); } public static Context a() { return i; } public static void e(boolean z) { x = false; } public static void n() { } public static boolean p() { return x; } public static String q() { return z; } private rr s() { ru[] b = this.q.b(); ru b2 = this.l.b(); float c = this.q.d().c(); if (this.C == null) { this.C = new rr(b2, b, c); } else { this.C.a(b2, b, c); } return this.C; } public final void a(int i) { this.u = i; a(false, false); } public final void a(Bitmap bitmap) { if (this.s != null) { this.s.a(bitmap); this.s.invalidate(); } } public final void a(Bundle bundle) { if (bundle != null) { this.r.d(bundle.getBoolean("ANIMATION_ENABLED", true)); this.r.b(bundle.getBoolean("SCROLL_ENABLED", true)); this.r.c(bundle.getBoolean("ZOOM_ENABLED", true)); this.r.b(bundle.getInt("LOGO_POSITION", 0)); this.r.c(bundle.getInt("SCALEVIEW_POSITION", 0)); this.r.a(bundle.getBoolean("SCALE_CONTROLL_ENABLED", true)); this.l.b(bundle.getDouble("ZOOM", this.l.c()), false, null); Double valueOf = Double.valueOf(bundle.getDouble("CENTERX", Double.NaN)); Double valueOf2 = Double.valueOf(bundle.getDouble("CENTERY", Double.NaN)); if (!valueOf.isNaN() && !valueOf2.isNaN()) { this.l.a(new ru(valueOf.doubleValue(), valueOf2.doubleValue())); } } } public final void a(j jVar) { a(jVar, null); } public final void a(j jVar, Rect rect) { this.v = jVar; this.y = rect; sz.a(this.l, 1); if (this.w) { o(); return; } this.l.a(true); a(false, false); } public final void a(boolean z) { if (z) { a(false, false); } } public final void a(boolean z, boolean z2) { this.w = false; if (this.p != null) { this.p.a(s()); } this.n.a(z, z2); this.j.f(); this.j.postInvalidate(); } public final si b() { return this.q; } public final void b(int i) { if (this.s != null) { this.s.a(i); this.s.invalidate(); if (this.t.getVisibility() == 0) { this.t.invalidate(); } } } public final void b(Bitmap bitmap) { this.j.post(new 2(this, bitmap)); } public final void b(Bundle bundle) { bundle.putBoolean("ANIMATION_ENABLED", this.r.k()); bundle.putBoolean("SCROLL_ENABLED", this.r.h()); bundle.putBoolean("ZOOM_ENABLED", this.r.i()); bundle.putInt("LOGO_POSITION", this.r.j()); bundle.putInt("SCALEVIEW_POSITION", this.r.f()); bundle.putBoolean("SCALE_CONTROLL_ENABLED", this.r.g()); bundle.putDouble("ZOOM", this.l.c()); bundle.putDouble("CENTERX", this.l.b().b()); bundle.putDouble("CENTERY", this.l.b().a()); } public final void b(boolean z) { if (z) { this.p.a(); } sg.a(sn.j()); this.p.a(s()); a(false, false); } public final sh c() { return this.l; } public final void c(int i) { if (this.t != null && this.t.getVisibility() == 0) { this.t.a(i); this.t.invalidate(); } } public final void c(boolean z) { if (z) { this.t.setVisibility(0); this.t.d(); return; } ta.b(); ta.c(); this.t.setVisibility(8); } public final tw d() { return this.j; } protected final void d(boolean z) { this.w = z; } public final sf e() { return this.k; } public final sf$1 f() { return this.r; } protected final void f(boolean z) { this.A = z; } public final 1 g() { return this.n; } public final void g(boolean z) { if (z != this.B) { this.B = z; a(false, false); } } public final sm h() { return this.m; } public final tq i() { return this.o; } public final void j() { this.t.e(); } public final void k() { this.t.d(); } public final int l() { return this.u; } public final void m() { this.t.a(); this.s.a(); this.k.b(); this.j.g(); this.j.removeAllViews(); this.n.a(); this.p.b(); sk.a().b(); te.a().c(); new 1(this).start(); System.gc(); } protected final void o() { if (this.v != null) { this.j.setDrawingCacheEnabled(true); this.j.buildDrawingCache(); Bitmap createBitmap = this.y == null ? Bitmap.createBitmap(this.j.getDrawingCache()) : Bitmap.createBitmap(this.j.getDrawingCache(), this.y.left, this.y.top, this.y.width(), this.y.height()); this.j.destroyDrawingCache(); this.v.a(createBitmap); if (this.A) { sz.a(this.l, 2); } } } public final boolean r() { return this.B; } }
package br.eti.ns.nssuite.requisicoes.mdfe; import br.eti.ns.nssuite.requisicoes._genericos.CancelarReq; public class CancelarReqMDFe extends CancelarReq { public String chMDFe; }
package com.workorder.ticket.service; import java.util.List; import com.workorder.ticket.service.bo.deploy.ProjectBo; /** * 项目服务 * * @author wzdong * @Date 2019年3月26日 * @version 1.0 */ public interface ProjectService { public List<ProjectBo> queryProject(String projectName, Long parentId); }
package com.elvarg.net.login; import java.nio.channels.Channel; import com.elvarg.net.packet.Packet; import com.elvarg.net.security.IsaacRandom; import io.netty.channel.ChannelHandlerContext; /** * The {@link Packet} implementation that contains data used for the final * portion of the login protocol. * * @author lare96 <http://github.org/lare96> */ public final class LoginDetailsMessage { /** * The context to which this player is going through. */ private final ChannelHandlerContext context; /** * The username of the player. */ private final String username; /** * The password of the player. */ private final String password; /** * The player's host address */ private final String host; /** * The player's client version. */ private final int clientVersion; /** * The player's client uid. */ private final int uid; /** * The encrypting isaac */ private final IsaacRandom encryptor; /** * The decrypting isaac */ private final IsaacRandom decryptor; /** * Creates a new {@link LoginDetailsMessage}. * * @param ctx * the {@link ChannelHandlerContext} that holds our * {@link Channel} instance. * @param username * the username of the player. * @param password * the password of the player. * @param encryptor * the encryptor for encrypting messages. * @param decryptor * the decryptor for decrypting messages. */ public LoginDetailsMessage(ChannelHandlerContext context, String username, String password, String host, int clientVersion, int uid, IsaacRandom encryptor, IsaacRandom decryptor) { this.context = context; this.username = username; this.password = password; this.host = host; this.clientVersion = clientVersion; this.uid = uid; this.encryptor = encryptor; this.decryptor = decryptor; } public ChannelHandlerContext getContext() { return context; } public String getUsername() { return username; } public String getPassword() { return password; } public String getHost() { return host; } public int getClientVersion() { return clientVersion; } public int getUid() { return uid; } public IsaacRandom getEncryptor() { return encryptor; } public IsaacRandom getDecryptor() { return decryptor; } }
package com.tencent.mm.plugin.collect.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.collect.ui.CollectBillUI.1; import com.tencent.mm.protocal.c.cq; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.wallet_core.ui.e; class CollectBillUI$1$1 implements OnClickListener { final /* synthetic */ cq hXB; final /* synthetic */ 1 hXC; CollectBillUI$1$1(1 1, cq cqVar) { this.hXC = 1; this.hXB = cqVar; } public final void onClick(View view) { if (!bi.oW(this.hXB.url)) { e.l(this.hXC.hXA.mController.tml, this.hXB.url, true); } } }
package it.htm.entity; import javax.persistence.*; import java.util.List; @Entity @Table(name="project") public class Project { @Id @Column(name = "project_id") @GeneratedValue(strategy=GenerationType.AUTO) private int projectId; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "state") private String state; @Column(name = "budget") private double budget; @OneToMany(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn private List<Architecture> architectures; public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getState() { return state; } public void setState(String state) { this.state = state; } public double getBudget() { return budget; } public void setBudget(double budget) { this.budget = budget; } public List<Architecture> getArchitectures() { return architectures; } public void setArchitectures(List<Architecture> architectures) { this.architectures = architectures; } }
package umk.net.slafs.web; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import umk.net.slafs.domain.Faza; @Controller @RequestMapping("/test.html") public class FreemarkerIndexController { @RequestMapping(method = RequestMethod.GET) public String ftest(Model model) { String hello = "Hello Freemarker"; model.addAttribute("hello", hello); model.addAttribute("faza", new Faza()); return "ftest"; } @RequestMapping(method = RequestMethod.POST) public String submit(@ModelAttribute("faza") Faza faza, Model model) { System.out.println(faza.getName() + " -=-=-=-=-=-=-=\n\n\n\n "); String hello = "Hello Freemarker"; model.addAttribute("hello", hello); model.addAttribute("faza", new Faza()); return "ftest"; } }
/* * 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 com.jotaweb.entity; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Sermusa */ @Entity @Table(name = "pessoa") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Pessoa.findAll", query = "SELECT p FROM Pessoa p ORDER BY p.nome") , @NamedQuery(name = "Pessoa.findByCodigo", query = "SELECT p FROM Pessoa p WHERE p.id = :id") , @NamedQuery(name = "Pessoa.findByNome", query = "SELECT p FROM Pessoa p WHERE upper(p.nome) like :nome ORDER BY p.nome ASC")}) public class Pessoa implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(name = "nome", nullable = false) private String nome; @Column(name = "cpf", nullable = false) private String cpf; @Column(name = "id_ponto", nullable = true) private String id_ponto; public Pessoa() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getId_ponto() { return id_ponto; } public void setId_ponto(String id_ponto) { this.id_ponto = id_ponto; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pessoa other = (Pessoa) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } @Override public String toString() { return "com.jotaweb.entity.Pessoa[ codigo=" + id + " ]"; } }
package weather; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.streams.processor.TopologyBuilder; import org.apache.kafka.streams.processor.StateStoreSupplier; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.Stores; public class WeatherMinProcessor { public static void main(String[] args) { TopologyBuilder builder = new TopologyBuilder(); StreamsConfig streamsConfig = new StreamsConfig(getProperties()); // Define the 2 StateStore to keep current min-max values StateStoreSupplier minStore = Stores.create("Min") .withStringKeys() .withDoubleValues() .inMemory() .build(); StateStoreSupplier maxStore = Stores.create("Max") .withStringKeys() .withDoubleValues() .inMemory() .build(); // Build the topology builder that connects the input with the 2 processors and its corresponding "Sinks" builder.addSource("source", "weather-temp-input") .addProcessor("processMin", () -> new MinProcessor(), "source") .addProcessor("processMax", () -> new MaxProcessor(), "source") .addStateStore(minStore, "processMin") .addStateStore(maxStore, "processMax") .addSink("sink", "weather-temp-min", "processMin") .addSink("sink2", "weather-temp-max", "processMax"); // Setup the Kafka-Stream and start it KafkaStreams streams = new KafkaStreams(builder,streamsConfig); streams.start(); Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); } private static Properties getProperties() { Properties props = new Properties(); props.put("group.id", "weather-processor"); props.put(StreamsConfig.APPLICATION_ID_CONFIG, "weather-processor2"); props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 1); props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.Double().getClass()); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); return props; } /** * Class that implements Processor interface and figures out the current min value * @author marc * */ public static class MinProcessor implements Processor<String,Double> { private ProcessorContext context; private KeyValueStore<String, Double> kvStore; @Override public void init(ProcessorContext context) { this.context = context; this.context.schedule(1000); this.kvStore = (KeyValueStore<String,Double>) context.getStateStore("Min"); } @Override public void process(String key, Double value) { Double minValue = kvStore.get(key); System.out.printf("key: %s and min value %f \n", key, minValue); if (minValue == null || value < minValue) { this.kvStore.put(key, value); context.forward(key,value); context.commit(); } } @Override public void punctuate(long timestamp) {} @Override public void close() { this.kvStore.close(); } } /** * Class that implements Processor interface and figures out the current max value * @author marc * */ public static class MaxProcessor implements Processor<String,Double> { private ProcessorContext context; private KeyValueStore<String, Double> kvStore; @Override public void init(ProcessorContext context) { this.context = context; this.context.schedule(1000); this.kvStore = (KeyValueStore<String,Double>) context.getStateStore("Max"); } @Override public void process(String key, Double value) { Double maxValue = kvStore.get(key); System.out.printf("key: %s and max value %f \n", key, maxValue); if (maxValue == null || value > maxValue) { this.kvStore.put(key, value); context.forward(key,value); context.commit(); } } @Override public void punctuate(long timestamp) {} @Override public void close() { this.kvStore.close(); } } }
package com.steven.base.impl; /** * @user steven * @createDate 2019/6/26 15:05 * @description 连续点击事件监听器 可以用作双击事件 */ public interface OnMultiTouchListener { void onMultiTouch(float x, float y); }
import java.util.Stack; import java.util.HashMap; import java.util.Map; interface Key{ public void operateOn(Stack<Integer> stack); } enum DigitKey implements Key{ DIGIT0, DIGIT1, DIGIT2, DIGIT3, DIGIT4, DIGIT5, DIGIT6, DIGIT7, DIGIT8, DIGIT9; public void operateOn(Stack<Integer> stack){ stack.push(stack.pop() * 10 + ordinal()); } } enum OperationKey implements Key{ ADD, SUBTRACT, MULTIPLY, DIVIDE, EQUAL, CLEAR; public void operateOn(Stack<Integer> stack){ if(this == EQUAL || this==CLEAR){ return ; } int val2 = stack.pop(); int val1 = stack.pop(); stack.push(calculate(val1, val2)); } private int calculate(int val1, int val2){ switch(this){ case ADD: return val1 + val2; case SUBTRACT: return val1 - val2; case MULTIPLY: return val1 * val2; case DIVIDE: return val1 / val2; default : throw new AssertionError(toString()); } } } class Calculator{ private final Stack<Integer> stack = new Stack<Integer>(); private Key pendingKey; public Calculator(){ stack.push(0); } public void onKeyPressed(Key key){ System.out.println(key); if (key instanceof DigitKey){ if (pendingKey == OperationKey.EQUAL) { reset(); } key.operateOn(stack); System.out.println(stack.peek()); } else if (key == OperationKey.CLEAR) { reset(); System.out.println(stack.peek()); } else { try { if (pendingKey != null) { pendingKey.operateOn(stack); } System.out.println(stack.peek()); pendingKey = key; if (key != OperationKey.EQUAL) { stack.push(0); } } catch (ArithmeticException e){ System.out.println("Error"); reset(); } } } private void reset() { stack.clear(); stack.push(0); pendingKey = null; } } public class H28Autumn_11{ // command java H28Autumn_11 -> " " -> // (1) 2*6/3=, (2) -2=, (3) 2*4==, (4) 2*4C2=, (5) 8/2/= public static void main(String[] args){ Map<Character, Key> map = new HashMap<Character, Key>(); for (OperationKey key : OperationKey.values()) map.put("+-*/=C".charAt(key.ordinal()), key); for(DigitKey key : DigitKey.values()) map.put("0123456789".charAt(key.ordinal()), key); Calculator calc = new Calculator(); String chars = args[0]; for(int i = 0; i < chars.length(); i++){ calc.onKeyPressed(map.get(chars.charAt(i))); } } }
package com.cleo.ringto; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; /** * Created by terrin on 4/25/15. */ public class ChatListThreadAdapter extends BaseAdapter { private LayoutInflater mInflater = null; private List<Message> recentMessages = null; private Context context = null; public ChatListThreadAdapter(Context context, List<Message> recentMessages) { mInflater = LayoutInflater.from(context); this.recentMessages = recentMessages; this.context = context; } @Override public int getCount() { return recentMessages.size(); } @Override public Object getItem(int position) { return recentMessages.get(position); } @Override public long getItemId(int position) { return recentMessages.get(position).getId(); } public long getItemPosition(int position) { return position; } public void addMessageThread(Message thread) { recentMessages.add(thread); } public void addMessageThreads(ArrayList<Message> threads) { recentMessages.addAll(threads); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = new ViewHolder(); Message recent_message = recentMessages.get(position); holder.message = recent_message; if(convertView == null) { convertView = mInflater.inflate(R.layout.chat_thread_row_layout, parent, false); holder.avatar = (ImageView)convertView.findViewById(R.id.avatar); holder.name = (TextView)convertView.findViewById(R.id.name); holder.latestMessage = (TextView)convertView.findViewById(R.id.latest_message); holder.date = (TextView)convertView.findViewById(R.id.date); holder.view = (RelativeLayout)convertView.findViewById(R.id.chat_item); convertView.setTag(holder); holder.view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String to_number = ""; String from_number = ""; ViewHolder temp = (ViewHolder) v.getTag(); Log.d("Item position", Integer.toString(temp.position)); if(temp.message.getLeft()) { to_number = temp.message.getFromNumber(); from_number = temp.message.getToNumber(); } else { to_number = temp.message.getToNumber(); from_number = temp.message.getFromNumber(); } Intent intent = new Intent(context, RingToChatScreen.class); intent.putExtra("to_number", to_number); intent.putExtra("from_number", from_number); Log.d("To Number:", temp.message.getToNumber()); Log.d("From Number:", temp.message.getFromNumber()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); } else { holder = (ViewHolder)convertView.getTag(); } holder.avatar.setImageDrawable(context.getResources().getDrawable(R.mipmap.default_user)); holder.name.setText(recent_message.getFromNumber()); holder.latestMessage.setText(recent_message.getText()); holder.message = recent_message; if(recent_message.getDate() != null) { Calendar c = Calendar.getInstance(); String[] dates = recent_message.getDate().split(" "); // String[] dates = recent_message.getDate().split("T"); // String[] time = dates[1].split(":"); // String[] dates1 = dates[0].split("-"); // String final_date = dates1[1] + "/" + dates1[2] + "/" + dates1[0]; SimpleDateFormat df3 = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a"); String date2 = df3.format(c.getTime()); String[] date2_split = date2.split(" "); Log.d("Current Date", date2); Log.d("Other dates", dates[0]); // Same date if( date2.contains(dates[0]) ) { // int hour = 0; // String midday = "am"; // // if( (Double.parseDouble(time[0]) / 12) > 1) // { // hour = (int) Double.parseDouble(time[0]) - 12; // midday = "pm"; // } // // else // { // hour = Integer.parseInt(time[0]); // } // // String final_time = Integer.toString(hour) + ":" + time[1] + ":" + time[2].split("\\.")[0] + " " + midday; //// holder.date.setText(dates[1] + "" + dates[2]); holder.date.setText(dates[1] + " " + dates[2]); } // Yesterday and previous days else { // GregorianCalendar c1 = new GregorianCalendar(); // GregorianCalendar c2 = new GregorianCalendar(); // String[] temp1a = date2.split(" "); // String[] temp1 = temp1a[0].split("/"); // String[] temp2 = dates[0].split("/"); // Log.d("Date1", temp1[0] + temp1[1] + temp1[2]); // Log.d("Date2", temp2[0] + temp2[1] + temp2[2]); // c2.set(Integer.parseInt("20" + temp1[2]), Integer.parseInt(temp1[0]), Integer.parseInt(temp1[1])); // c1.set(Integer.parseInt("20" + temp2[2]), Integer.parseInt(temp2[0]), Integer.parseInt(temp2[1])); // long span = c2.getTimeInMillis() - c1.getTimeInMillis(); // GregorianCalendar c3 = new GregorianCalendar(); // c3.setTimeInMillis(span); // long numberOfMSInADay = 1000*60*60*24; // long ms = c3.getTimeInMillis() / numberOfMSInADay; // Log.d("MS", Long.toString(ms)); //3653 // // // if(ms >= 1) // { // holder.date.setText("Yesterday"); // } // else // { //String[] temp = recent_message.getDate().split(" "); holder.date.setText(dates[0]); // holder.date.setText(temp[0]); // } } } // holder.view.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // ViewHolder temp = (ViewHolder) v.getTag(); // Log.d("Item position", Integer.toString(temp.position)); // Intent intent = new Intent(context, RingToChatScreen.class); // intent.putExtra("to_number", temp.message.getToNumber()); // intent.putExtra("from_number", temp.message.getFromNumber()); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(intent); // } // }); convertView.setTag(holder); return convertView; } private class ViewHolder { public ImageView avatar; public TextView name, latestMessage, date; public Message message = null; public int position = 0; public View view = null; } }
package webprotocol; import com.google.gson.annotations.SerializedName; import lombok.*; @Builder @AllArgsConstructor @Getter @Setter @ToString public class Address { @SerializedName("street") private String street; @SerializedName("suite") private String apartment; @SerializedName("city") private String city; @SerializedName("zipcode") private String zipcode; @SerializedName("geo") private Geo geo; }
package dao; import entity.*; import db.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; public class PayBillDao { /** * 添加订单信息的方法 * @param payBill * @return */ public int addPayBill(PayBill payBill){ String sql="insert into paybill(t_deskno,v_name,v_count,v_price) values(?,?,?,?)"; List<Object> parmars=new ArrayList<Object>(); parmars.add(payBill.getT_deskno()); parmars.add(payBill.getV_name()); parmars.add(payBill.getV_count()); parmars.add(payBill.getV_price()); return Dbutil.executeUpdata(sql, parmars); } /** * 获取订单信息的方法 * @param payBill * @return */ public ArrayList<PayBill> getPayBill(PayBill payBill){ StringBuffer sql=new StringBuffer("select * from paybill where 1=1"); ArrayList<PayBill> payBillList=new ArrayList<PayBill>(); List<Object> parmars=new ArrayList<Object>(); if(payBill.getT_deskno()!=null){ sql.append(" and t_deskno=?"); parmars.add(payBill.getT_deskno()); } if(payBill.getV_name()!=null){ sql.append(" and v_name=?"); parmars.add(payBill.getV_name()); } if(payBill.getV_count()!=null){ sql.append(" and v_count=?"); parmars.add(payBill.getV_count()); } if(payBill.getV_price()!=0){ sql.append(" and v_price=?"); parmars.add(payBill.getV_price()); } ResultSet resultSet= Dbutil.executeQuery(sql.toString(), parmars); try { while(resultSet.next()){ PayBill _pPayBill=new PayBill(); _pPayBill.setT_deskno(resultSet.getString("t_deskno")); _pPayBill.setV_name(resultSet.getString("v_name")); _pPayBill.setV_count(resultSet.getString("v_count")); _pPayBill.setV_price(resultSet.getDouble("v_price")); payBillList.add(_pPayBill); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return payBillList; } public int deletePayBill(PayBill payBill){ StringBuffer sql=new StringBuffer("delete from paybill where 1=1"); List<Object> parmars=new ArrayList<Object>(); if(payBill.getT_deskno()!=null){ sql.append(" and t_deskno=?"); parmars.add(payBill.getT_deskno()); } if(payBill.getV_name()!=null){ sql.append(" and v_name=?"); parmars.add(payBill.getV_name()); } if(payBill.getV_count()!=null){ sql.append(" and v_count=?"); parmars.add(payBill.getV_count()); } if(payBill.getV_price()!=0){ sql.append(" and v_price=?"); parmars.add(payBill.getV_price()); } return Dbutil.executeUpdata(sql.toString(), parmars); } }
/* * 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 gerenciador.funcionario; import gerenciador.alunos.CadastroAlunoGUI; import gerenciador.endereco.CidadeGUI; import gerenciador.endereco.BairroGUI; import gerenciador.endereco.Cidade; import gerenciador.conexaoBD.EnderecoDao; import gerenciador.conexaoBD.FuncionarioDao; import gerenciador.telas.ultilidades.Data; import java.sql.SQLException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.text.MaskFormatter; /** * * @author Raiane */ public class CadastroFuncionarioGUI extends javax.swing.JFrame { private Turno turno; private Funcao funcao; private char sexo; private EnderecoDao conEndereco; private FuncionarioDao conFuncionario; private String formatohora = "HH:mm:ss"; private SimpleDateFormat horaformatada = new SimpleDateFormat(formatohora); private Data data = new Data(); private Funcionario funcionario; private Cidade cidade = new Cidade(""); private Iterator iteratorEstado = null; private MaskFormatter formatoCpf, formatoCtps, formatoRg, formatoCep, formatoFone, formatoCel, formatoData; private int nivel; public CadastroFuncionarioGUI() { this.setExtendedState(MAXIMIZED_BOTH); this.setUndecorated(true); initComponents(); tmrHora.setDelay(1000); tmrHora.start(); lblData.setText(Data.mostraData()); gerenciador.telas.ultilidades.FuncoesJanelas.setIncone(this); pnlCadastrar.setVisible(false); conEndereco = new EnderecoDao(); conFuncionario = new FuncionarioDao(); edtCep.setEditable(false); } private void cadastra() throws SQLException { if (gerenciador.pessoa.ValidaCpf.validador(edtCpf.getText())) { if ((new String(pwfSenha.getPassword())).equals(new String(pwfConfirmaSenha.getPassword()))) { funcionario = new Funcionario(gerenciador.telas.ultilidades.FormataCampo.formataDocumentosBanco(edtCpf.getText()), gerenciador.telas.ultilidades.FormataCampo.formataDocumentosBanco(edtIdentidade.getText()), edtNome.getText(), gerenciador.telas.ultilidades.FormataCampo.formataDataBanco(edtDataNascimento.getText()), edtEmail.getText(), sexo, edtCtps.getText(), (Float.parseFloat(edtSalario.getText().replace(",", ".")))); funcionario.setFoneCelular(edtFoneCel.getText()); funcionario.setFoneResidencial(edtTelRes.getText()); funcionario.setObservacao(edtObservacoes.getText()); funcionario.setDataEntrada(gerenciador.telas.ultilidades.FormataCampo.formataDataBanco(edtDataEntrada.getText())); funcionario.setSituacao((cmbSituacaoFuncionario.getSelectedIndex() + 1)); funcionario.getEndereco().setCEP(Integer.parseInt(edtCep.getText().replace("-", ""))); funcionario.getEndereco().setRua((String) cmbEndereco.getSelectedItem()); funcionario.getEndereco().setComplemento(edtComplemento.getText()); funcionario.getEndereco().setNumero(edtNumero.getText()); funcionario.getEstadoCivil().setDescricao((String) cmbEstadoCivil.getSelectedItem()); funcionario.getEstadoCivil().setId((cmbEstadoCivil.getSelectedIndex() + 1)); funcionario.getTurno().setNome((String) cmbTurno.getSelectedItem()); funcionario.getTurno().setId((cmbTurno.getSelectedIndex() + 1)); funcionario.getFuncao().setNome((String) cmbFuncao.getSelectedItem()); funcionario.getFuncao().setId((cmbFuncao.getSelectedIndex() + 1)); funcionario.setSituacao((cmbSituacaoFuncionario.getSelectedIndex() + 1)); if (chbCadastrarUsuario.isSelected() == true) { funcionario.setUsuarioAutorizado(true); funcionario.getUsario().setLogin(edtUsuLogin.getText()); funcionario.getUsario().setSenha(new String(pwfSenha.getPassword())); funcionario.getUsario().setNivel(nivel); } else { funcionario.setUsuarioAutorizado(false); funcionario.getUsario().setLogin(""); funcionario.getUsario().setSenha(""); funcionario.getUsario().setNivel(0); } conFuncionario.insertFuncionario(funcionario); } else { JOptionPane.showMessageDialog(null, "As senhas não são iguais"); } } } private void setCbmFuncao() throws SQLException { try { cmbFuncao.removeAllItems(); Iterator iteratorFuncao = conFuncionario.getArrayFuncao().iterator(); while (iteratorFuncao.hasNext()) { cmbFuncao.addItem(String.valueOf(iteratorFuncao.next())); } } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } } private void setCbmTurno() throws SQLException { try { cmbTurno.removeAllItems(); Iterator iteratorTurno = conFuncionario.getArrayTurno().iterator(); while (iteratorTurno.hasNext()) { cmbTurno.addItem(String.valueOf(iteratorTurno.next())); } } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } } private void setCbmEstadoCivil() throws SQLException { try { cmbEstadoCivil.removeAllItems(); Iterator iteratorEstadoCivil = conFuncionario.getArrayEstadoCivil().iterator(); while (iteratorEstadoCivil.hasNext()) { cmbEstadoCivil.addItem(String.valueOf(iteratorEstadoCivil.next())); } } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } } private void setCbmEndereco() throws SQLException { cmbEndereco.removeAllItems(); try { Iterator iteratorEndereco = conEndereco.getArrayRua((String) cmbBairro.getSelectedItem()).iterator(); while (iteratorEndereco.hasNext()) { cmbEndereco.addItem(String.valueOf(iteratorEndereco.next())); } } catch (SQLException ex) { Logger.getLogger(BairroGUI.class.getName()).log(Level.SEVERE, null, ex); } } private void setCbmCidade() throws SQLException { cmbCidade.removeAllItems(); cmbBairro.removeAllItems(); cmbEndereco.removeAllItems(); Iterator iteratorCidade = null; try { iteratorCidade = conEndereco.getArrayCidade((String) cmbEstado.getSelectedItem()).iterator(); } catch (SQLException ex) { Logger.getLogger(CadastroAlunoGUI.class.getName()).log(Level.SEVERE, null, ex); } while (iteratorCidade.hasNext()) { cmbCidade.addItem(String.valueOf(iteratorCidade.next())); } if (conEndereco.getArrayCidade((String) cmbEstado.getSelectedItem()).contains("Guarapari")) { cmbCidade.setSelectedItem("Guarapari"); } setCbmBairro(); } private void setCbmBairro() throws SQLException { cmbBairro.removeAllItems(); cmbEndereco.removeAllItems(); Iterator iteratorBairro; try { iteratorBairro = conEndereco.getArrayBairro((String) cmbCidade.getSelectedItem()).iterator(); if (iteratorBairro.hasNext()) { while (iteratorBairro.hasNext()) { cmbBairro.addItem(String.valueOf(iteratorBairro.next())); } } } catch (SQLException e) { Logger.getLogger(CadastroAlunoGUI.class.getName()).log(Level.SEVERE, null, e); } setCbmEndereco(); } private void setCbmEstado() throws SQLException { cmbEstado.removeAllItems(); cmbCidade.removeAllItems(); cmbBairro.removeAllItems(); cmbEndereco.removeAllItems(); try { iteratorEstado = conEndereco.getArrayEstados().iterator(); } catch (SQLException ex) { Logger.getLogger(BairroGUI.class.getName()).log(Level.SEVERE, null, ex); } while (iteratorEstado.hasNext()) { cmbEstado.addItem(String.valueOf(iteratorEstado.next())); } if (conEndereco.getArrayEstados().contains("Espírito Santo")) { cmbEstado.setSelectedItem("Espírito Santo"); } setCbmCidade(); } private void atualizaCbmEstado() throws SQLException { cmbCidade.removeAllItems(); cmbBairro.removeAllItems(); cmbEndereco.removeAllItems(); setCbmCidade(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { grupoNivelAcesso = new javax.swing.ButtonGroup(); tmrHora = new org.netbeans.examples.lib.timerbean.Timer(); lblVoltar = new javax.swing.JLabel(); lblData = new javax.swing.JLabel(); lblHora = new javax.swing.JLabel(); pnlPrincipal = new javax.swing.JTabbedPane(); pnlDados = new javax.swing.JPanel(); pnlEndereco = new javax.swing.JPanel(); try { formatoCep = new MaskFormatter("#####-###"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para cpf, "+erro); } edtCep = new JFormattedTextField(formatoCep); lblCep = new javax.swing.JLabel(); lblBairro = new javax.swing.JLabel(); cmbBairro = new javax.swing.JComboBox(); jLabel5 = new javax.swing.JLabel(); cmbEstado = new javax.swing.JComboBox(); cmbCidade = new javax.swing.JComboBox(); lblCidade = new javax.swing.JLabel(); btnNovaCidade = new javax.swing.JButton(); btnNovaBairro = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); edtNumero = new javax.swing.JTextField(); pnlInformacoes = new javax.swing.JPanel(); try { formatoFone = new MaskFormatter("(0xx##)####-####"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para cpf, "+erro); } edtTelRes = new JFormattedTextField(formatoFone); edtNome = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); try { formatoRg = new MaskFormatter("#####.###-#"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para RG, "+erro); } edtIdentidade = new JFormattedTextField(formatoRg); jLabel1 = new javax.swing.JLabel(); lblFoneRes = new javax.swing.JLabel(); lblCpf = new javax.swing.JLabel(); try { formatoCpf = new MaskFormatter("###.###.###-##"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para cpf, "+erro); } edtCpf = new JFormattedTextField(formatoCpf); try { formatoCel = new MaskFormatter("(0xx##)#####-####"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para cpf, "+erro); } edtFoneCel = new JFormattedTextField(formatoCel); edtEmail = new javax.swing.JTextField(); lblEmail = new javax.swing.JLabel(); lblDataNasc = new javax.swing.JLabel(); try { formatoData = new MaskFormatter("##/##/####"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para data, "+erro); } edtDataNascimento = new JFormattedTextField(formatoData); lblEstadoCivil = new javax.swing.JLabel(); cmbEstadoCivil = new javax.swing.JComboBox(); lblFoneCel = new javax.swing.JLabel(); cmbEndereco = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); edtComplemento = new javax.swing.JTextField(); pnlSexo = new javax.swing.JPanel(); jLabel21 = new javax.swing.JLabel(); sexo_masc = new javax.swing.JRadioButton(); sexo_fem = new javax.swing.JRadioButton(); paInfAdicionais = new javax.swing.JPanel(); pnlDadosCadastrais = new javax.swing.JPanel(); lblFuncao = new javax.swing.JLabel(); try { formatoData = new MaskFormatter("##/##/####"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para data, "+erro); } edtDataEntrada = new JFormattedTextField(formatoData); llblAvaliacao = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); edtObservacoes = new javax.swing.JTextArea(); lblObservacoes = new javax.swing.JLabel(); lblTurno = new javax.swing.JLabel(); cmbTurno = new javax.swing.JComboBox(); lblCtps = new javax.swing.JLabel(); try { formatoCtps= new MaskFormatter ("#######/#####-UU"); } catch(Exception erro) { JOptionPane.showMessageDialog(null,"Não foi possivel setar a mascara para ctps, "+erro); } edtCtps = new JFormattedTextField(formatoCtps); cmbFuncao = new javax.swing.JComboBox(); lblSalario = new javax.swing.JLabel(); edtSalario = new javax.swing.JTextField(); lblSituacoaFuncionario = new javax.swing.JLabel(); cmbSituacaoFuncionario = new javax.swing.JComboBox(); btnNovaFuncao = new javax.swing.JButton(); pnlBorda = new javax.swing.JPanel(); pnlCadastrar = new javax.swing.JPanel(); edtUsuLogin = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); lblSenha = new javax.swing.JLabel(); pwfSenha = new javax.swing.JPasswordField(); pwfConfirmaSenha = new javax.swing.JPasswordField(); lblConfirmarSenha = new javax.swing.JLabel(); lblNivelAcesso = new javax.swing.JLabel(); rdbAdministrador = new javax.swing.JRadioButton(); rdbUsuario = new javax.swing.JRadioButton(); chbCadastrarUsuario = new javax.swing.JCheckBox(); lblCadastra = new javax.swing.JLabel(); lblFundo = new javax.swing.JLabel(); tmrHora.addTimerListener(new org.netbeans.examples.lib.timerbean.TimerListener() { public void onTime(java.awt.event.ActionEvent evt) { tmrHoraOnTime(evt); } }); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentShown(java.awt.event.ComponentEvent evt) { formComponentShown(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); lblVoltar.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblVoltarMouseClicked(evt); } }); getContentPane().add(lblVoltar, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 660, 120, 40)); lblData.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 18)); // NOI18N lblData.setForeground(new java.awt.Color(255, 255, 255)); lblData.setText("..."); getContentPane().add(lblData, new org.netbeans.lib.awtextra.AbsoluteConstraints(860, 736, 320, 20)); lblHora.setFont(new java.awt.Font("Copperplate Gothic Bold", 1, 18)); // NOI18N lblHora.setForeground(new java.awt.Color(255, 255, 255)); lblHora.setText("..."); getContentPane().add(lblHora, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 736, 140, 20)); pnlPrincipal.setBackground(new java.awt.Color(153, 255, 153)); pnlDados.setBackground(new java.awt.Color(255, 255, 255)); pnlDados.setPreferredSize(new java.awt.Dimension(800, 600)); pnlEndereco.setBackground(new java.awt.Color(255, 255, 255)); edtCep.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtCepActionPerformed(evt); } }); lblCep.setText("CEP"); lblBairro.setText("Bairro"); cmbBairro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione ...", "Item 2", "Item 3", "Item 4" })); cmbBairro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbBairroActionPerformed(evt); } }); jLabel5.setText("Estado"); cmbEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 1", "Item 2", "Selecione...", "Item 4" })); cmbEstado.setSelectedIndex(6); cmbEstado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbEstadoActionPerformed(evt); } }); cmbCidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione ...", "Item 2", "Item 3", "Item 4" })); cmbCidade.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbCidadeActionPerformed(evt); } }); lblCidade.setText("Cidade"); btnNovaCidade.setBackground(new java.awt.Color(0, 153, 0)); btnNovaCidade.setForeground(new java.awt.Color(255, 255, 255)); btnNovaCidade.setText("Novo"); btnNovaCidade.setActionCommand(""); btnNovaCidade.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnNovaCidadeMouseClicked(evt); } }); btnNovaBairro.setBackground(new java.awt.Color(0, 153, 0)); btnNovaBairro.setForeground(new java.awt.Color(255, 255, 255)); btnNovaBairro.setText("Novo"); btnNovaBairro.setActionCommand(""); btnNovaBairro.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnNovaBairroMouseClicked(evt); } }); jLabel4.setText("Numero"); edtNumero.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtNumeroActionPerformed(evt); } }); javax.swing.GroupLayout pnlEnderecoLayout = new javax.swing.GroupLayout(pnlEndereco); pnlEndereco.setLayout(pnlEnderecoLayout); pnlEnderecoLayout.setHorizontalGroup( pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlEnderecoLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlEnderecoLayout.createSequentialGroup() .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(cmbEstado, javax.swing.GroupLayout.Alignment.LEADING, 0, 144, Short.MAX_VALUE) .addComponent(cmbCidade, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnNovaCidade) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(pnlEnderecoLayout.createSequentialGroup() .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(edtCep, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(cmbBairro, javax.swing.GroupLayout.Alignment.LEADING, 0, 146, Short.MAX_VALUE) .addComponent(lblBairro, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblCidade, javax.swing.GroupLayout.Alignment.LEADING))) .addComponent(lblCep)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnNovaBairro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addComponent(edtNumero)) .addContainerGap(16, Short.MAX_VALUE)))) ); pnlEnderecoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnNovaBairro, btnNovaCidade}); pnlEnderecoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cmbBairro, cmbCidade, cmbEstado}); pnlEnderecoLayout.setVerticalGroup( pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlEnderecoLayout.createSequentialGroup() .addComponent(jLabel5) .addGap(11, 11, 11) .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblCidade) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnNovaCidade)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlEnderecoLayout.createSequentialGroup() .addComponent(lblBairro) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnNovaBairro)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlEnderecoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblCep) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(edtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(26, Short.MAX_VALUE)) ); pnlEnderecoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnNovaBairro, btnNovaCidade}); pnlInformacoes.setBackground(new java.awt.Color(255, 255, 255)); edtTelRes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtTelResActionPerformed(evt); } }); edtNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtNomeActionPerformed(evt); } }); jLabel2.setText("Endereço"); jLabel18.setText("Identidade"); jLabel1.setText("Nome"); lblFoneRes.setText("Fone Res.:"); lblCpf.setText("CPF"); lblEmail.setText("Email"); lblDataNasc.setText("Data Nascimento"); edtDataNascimento.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtDataNascimentoActionPerformed(evt); } }); lblEstadoCivil.setText(" Estado Civil"); cmbEstadoCivil.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione ...", "F", "M" })); lblFoneCel.setText("Fone Cel.:"); cmbEndereco.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione ...", "Item 2", "Item 3", "Item 4" })); cmbEndereco.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { cmbEnderecoFocusGained(evt); } }); cmbEndereco.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbEnderecoActionPerformed(evt); } }); jLabel3.setText("Complemento"); javax.swing.GroupLayout pnlInformacoesLayout = new javax.swing.GroupLayout(pnlInformacoes); pnlInformacoes.setLayout(pnlInformacoesLayout); pnlInformacoesLayout.setHorizontalGroup( pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addContainerGap() .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbEndereco, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlInformacoesLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDataNasc) .addComponent(lblEmail) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(edtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel18) .addComponent(edtIdentidade, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addComponent(edtDataNascimento)) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(lblCpf)) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(edtCpf) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cmbEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))))) .addComponent(edtEmail) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(edtTelRes, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblFoneRes)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(edtFoneCel, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblFoneCel))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlInformacoesLayout.createSequentialGroup() .addComponent(jLabel3) .addGap(308, 308, 308)))) .addComponent(edtComplemento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); pnlInformacoesLayout.setVerticalGroup( pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addComponent(edtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtIdentidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(edtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addComponent(lblCpf) .addGap(26, 26, 26))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblDataNasc) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(pnlInformacoesLayout.createSequentialGroup() .addComponent(lblEstadoCivil) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmbEstadoCivil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblEmail) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(edtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblFoneRes) .addComponent(lblFoneCel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlInformacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(edtTelRes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(edtFoneCel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmbEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addComponent(edtComplemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pnlSexo.setBackground(new java.awt.Color(255, 255, 255)); jLabel21.setText("sexo"); sexo_masc.setBackground(new java.awt.Color(255, 255, 255)); sexo_masc.setSelected(true); sexo_masc.setText("Masculino"); sexo_masc.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); sexo_masc.setMargin(new java.awt.Insets(0, 0, 0, 0)); sexo_masc.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sexo_mascMouseClicked(evt); } }); sexo_masc.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sexo_mascActionPerformed(evt); } }); sexo_fem.setBackground(new java.awt.Color(255, 255, 255)); sexo_fem.setText("Feminino"); sexo_fem.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); sexo_fem.setMargin(new java.awt.Insets(0, 0, 0, 0)); sexo_fem.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { sexo_femMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { sexo_femMouseEntered(evt); } }); sexo_fem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sexo_femActionPerformed(evt); } }); javax.swing.GroupLayout pnlSexoLayout = new javax.swing.GroupLayout(pnlSexo); pnlSexo.setLayout(pnlSexoLayout); pnlSexoLayout.setHorizontalGroup( pnlSexoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlSexoLayout.createSequentialGroup() .addContainerGap(17, Short.MAX_VALUE) .addGroup(pnlSexoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel21) .addGroup(pnlSexoLayout.createSequentialGroup() .addComponent(sexo_masc) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sexo_fem))) .addGap(18, 18, 18)) ); pnlSexoLayout.setVerticalGroup( pnlSexoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlSexoLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlSexoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(sexo_fem) .addComponent(sexo_masc)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout pnlDadosLayout = new javax.swing.GroupLayout(pnlDados); pnlDados.setLayout(pnlDadosLayout); pnlDadosLayout.setHorizontalGroup( pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDadosLayout.createSequentialGroup() .addContainerGap() .addComponent(pnlInformacoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlSexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pnlEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(151, Short.MAX_VALUE)) ); pnlDadosLayout.setVerticalGroup( pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDadosLayout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(pnlInformacoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnlDadosLayout.createSequentialGroup() .addComponent(pnlSexo, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(pnlEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49))) .addContainerGap(179, Short.MAX_VALUE)) ); pnlPrincipal.addTab("Dados Cadastrais", pnlDados); paInfAdicionais.setBackground(new java.awt.Color(255, 255, 255)); pnlDadosCadastrais.setBackground(new java.awt.Color(255, 255, 255)); lblFuncao.setText("Função"); llblAvaliacao.setText("Data de entrada"); edtObservacoes.setColumns(20); edtObservacoes.setRows(5); jScrollPane3.setViewportView(edtObservacoes); lblObservacoes.setText("Observações"); lblTurno.setText("Turno"); cmbTurno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); lblCtps.setText("CTPS"); cmbFuncao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); lblSalario.setText("Salário"); edtSalario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { edtSalarioMouseClicked(evt); } }); edtSalario.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtSalarioActionPerformed(evt); } }); lblSituacoaFuncionario.setText("Situação do funcionário"); cmbSituacaoFuncionario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ativo", "Inativo" })); cmbSituacaoFuncionario.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbSituacaoFuncionarioActionPerformed(evt); } }); btnNovaFuncao.setBackground(new java.awt.Color(0, 153, 0)); btnNovaFuncao.setForeground(new java.awt.Color(255, 255, 255)); btnNovaFuncao.setText("Novo"); btnNovaFuncao.setActionCommand(""); btnNovaFuncao.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnNovaFuncaoMouseClicked(evt); } }); javax.swing.GroupLayout pnlDadosCadastraisLayout = new javax.swing.GroupLayout(pnlDadosCadastrais); pnlDadosCadastrais.setLayout(pnlDadosCadastraisLayout); pnlDadosCadastraisLayout.setHorizontalGroup( pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDadosCadastraisLayout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblSalario) .addComponent(edtSalario, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblFuncao, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(pnlDadosCadastraisLayout.createSequentialGroup() .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(cmbFuncao, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(edtCtps, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cmbTurno, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblCtps, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTurno, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnNovaFuncao))) .addGap(82, 82, 82) .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(llblAvaliacao) .addComponent(lblObservacoes) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(edtDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblSituacoaFuncionario) .addComponent(cmbSituacaoFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pnlDadosCadastraisLayout.setVerticalGroup( pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDadosCadastraisLayout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblFuncao) .addComponent(llblAvaliacao)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbFuncao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(edtDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnNovaFuncao)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlDadosCadastraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlDadosCadastraisLayout.createSequentialGroup() .addComponent(lblSituacoaFuncionario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmbSituacaoFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lblObservacoes) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(pnlDadosCadastraisLayout.createSequentialGroup() .addComponent(lblTurno) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmbTurno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lblCtps) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(edtCtps, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lblSalario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(edtSalario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(26, Short.MAX_VALUE)) ); pnlBorda.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout pnlBordaLayout = new javax.swing.GroupLayout(pnlBorda); pnlBorda.setLayout(pnlBordaLayout); pnlBordaLayout.setHorizontalGroup( pnlBordaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 711, Short.MAX_VALUE) ); pnlBordaLayout.setVerticalGroup( pnlBordaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 162, Short.MAX_VALUE) ); pnlCadastrar.setBackground(new java.awt.Color(255, 255, 255)); edtUsuLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { edtUsuLoginActionPerformed(evt); } }); jLabel13.setText("Login"); lblSenha.setText("Senha"); lblConfirmarSenha.setText("Confirmar Senha"); lblNivelAcesso.setText("Nivél de acesso"); rdbAdministrador.setBackground(new java.awt.Color(255, 255, 255)); grupoNivelAcesso.add(rdbAdministrador); rdbAdministrador.setText("Administrador"); rdbAdministrador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rdbAdministradorActionPerformed(evt); } }); rdbUsuario.setBackground(new java.awt.Color(255, 255, 255)); grupoNivelAcesso.add(rdbUsuario); rdbUsuario.setText("Usuário"); javax.swing.GroupLayout pnlCadastrarLayout = new javax.swing.GroupLayout(pnlCadastrar); pnlCadastrar.setLayout(pnlCadastrarLayout); pnlCadastrarLayout.setHorizontalGroup( pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlCadastrarLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(edtUsuLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblNivelAcesso) .addComponent(rdbUsuario) .addComponent(rdbAdministrador) .addComponent(jLabel13)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblSenha) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(pwfConfirmaSenha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE) .addComponent(pwfSenha, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblConfirmarSenha))) .addGap(35, 35, 35)) ); pnlCadastrarLayout.setVerticalGroup( pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pnlCadastrarLayout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel13) .addComponent(lblSenha)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(edtUsuLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pwfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNivelAcesso) .addComponent(lblConfirmarSenha)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE) .addGroup(pnlCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rdbAdministrador) .addComponent(pwfConfirmaSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rdbUsuario) .addContainerGap()) ); chbCadastrarUsuario.setBackground(new java.awt.Color(255, 255, 255)); chbCadastrarUsuario.setText("Cadastrar Usuário"); chbCadastrarUsuario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { chbCadastrarUsuarioMouseClicked(evt); } }); chbCadastrarUsuario.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chbCadastrarUsuarioActionPerformed(evt); } }); javax.swing.GroupLayout paInfAdicionaisLayout = new javax.swing.GroupLayout(paInfAdicionais); paInfAdicionais.setLayout(paInfAdicionaisLayout); paInfAdicionaisLayout.setHorizontalGroup( paInfAdicionaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(paInfAdicionaisLayout.createSequentialGroup() .addGroup(paInfAdicionaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(paInfAdicionaisLayout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(pnlDadosCadastrais, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(paInfAdicionaisLayout.createSequentialGroup() .addGap(171, 171, 171) .addComponent(chbCadastrarUsuario) .addGap(70, 70, 70) .addComponent(pnlCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pnlBorda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); paInfAdicionaisLayout.setVerticalGroup( paInfAdicionaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, paInfAdicionaisLayout.createSequentialGroup() .addComponent(pnlDadosCadastrais, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(paInfAdicionaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(paInfAdicionaisLayout.createSequentialGroup() .addGap(89, 89, 89) .addComponent(pnlBorda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(paInfAdicionaisLayout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(paInfAdicionaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pnlCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chbCadastrarUsuario)))) .addContainerGap(58, Short.MAX_VALUE)) ); pnlPrincipal.addTab("Informações Adicionais", paInfAdicionais); getContentPane().add(pnlPrincipal, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 30, 830, 600)); lblCadastra.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblCadastraMouseClicked(evt); } }); getContentPane().add(lblCadastra, new org.netbeans.lib.awtextra.AbsoluteConstraints(472, 655, 120, 50)); lblFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Telas Fundo/BackgroudCadastroFuncionario.jpg"))); // NOI18N getContentPane().add(lblFundo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 790)); pack(); }// </editor-fold>//GEN-END:initComponents private void edtCepActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtCepActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtCepActionPerformed private void edtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtNomeActionPerformed private void edtDataNascimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtDataNascimentoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtDataNascimentoActionPerformed private void sexo_mascActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sexo_mascActionPerformed String sexo = "M"; }//GEN-LAST:event_sexo_mascActionPerformed private void sexo_femActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sexo_femActionPerformed String sexo = "F"; }//GEN-LAST:event_sexo_femActionPerformed private void lblVoltarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblVoltarMouseClicked this.dispose(); }//GEN-LAST:event_lblVoltarMouseClicked private void btnNovaCidadeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovaCidadeMouseClicked CidadeGUI cidade = new CidadeGUI(); cidade.setEstado((String) cmbEstado.getSelectedItem()); cidade.setVisible(true); }//GEN-LAST:event_btnNovaCidadeMouseClicked private void btnNovaBairroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovaBairroMouseClicked BairroGUI bairro = new BairroGUI(); bairro.setEstado((String) cmbEstado.getSelectedItem()); bairro.setVisible(true); }//GEN-LAST:event_btnNovaBairroMouseClicked private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown try { setCbmFuncao(); setCbmEstado(); setCbmTurno(); setCbmEstadoCivil(); } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_formComponentShown private void edtUsuLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtUsuLoginActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtUsuLoginActionPerformed private void chbCadastrarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbCadastrarUsuarioActionPerformed // TODO add your handling code here: }//GEN-LAST:event_chbCadastrarUsuarioActionPerformed private void chbCadastrarUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_chbCadastrarUsuarioMouseClicked if (chbCadastrarUsuario.isSelected() == true) { pnlCadastrar.setVisible(true); } else { pnlCadastrar.setVisible(false); } }//GEN-LAST:event_chbCadastrarUsuarioMouseClicked private void edtTelResActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtTelResActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtTelResActionPerformed private void lblCadastraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblCadastraMouseClicked try { cadastra(); } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_lblCadastraMouseClicked private void sexo_mascMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sexo_mascMouseClicked sexo = ('M'); }//GEN-LAST:event_sexo_mascMouseClicked private void sexo_femMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sexo_femMouseEntered // TODO add your handling code here: }//GEN-LAST:event_sexo_femMouseEntered private void sexo_femMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_sexo_femMouseClicked sexo = ('F'); }//GEN-LAST:event_sexo_femMouseClicked private void btnNovaFuncaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNovaFuncaoMouseClicked new FuncaoGUI().setVisible(true); }//GEN-LAST:event_btnNovaFuncaoMouseClicked private void cmbEnderecoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cmbEnderecoFocusGained try { setCbmEndereco(); } catch (SQLException ex) { Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_cmbEnderecoFocusGained private void tmrHoraOnTime(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tmrHoraOnTime Date le_hora = new Date(); lblHora.setText(horaformatada.format(le_hora)); }//GEN-LAST:event_tmrHoraOnTime private void cmbCidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCidadeActionPerformed try { setCbmBairro(); } catch (SQLException ex) { Logger.getLogger(CadastroAlunoGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_cmbCidadeActionPerformed private void cmbBairroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbBairroActionPerformed try { setCbmEndereco(); } catch (SQLException ex) { Logger.getLogger(CadastroAlunoGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_cmbBairroActionPerformed private void cmbEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbEstadoActionPerformed try { setCbmCidade(); } catch (SQLException ex) { Logger.getLogger(CadastroAlunoGUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_cmbEstadoActionPerformed private void cmbEnderecoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbEnderecoActionPerformed try { if (cmbEndereco.getSelectedIndex() >= 0) { edtCep.setText((String) conEndereco.getCep().get(cmbEndereco.getSelectedIndex())); } } catch (NullPointerException e) { } }//GEN-LAST:event_cmbEnderecoActionPerformed private void edtNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtNumeroActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtNumeroActionPerformed private void rdbAdministradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdbAdministradorActionPerformed if (rdbAdministrador.isSelected()) { this.nivel = 1; } else { this.nivel = 2; } }//GEN-LAST:event_rdbAdministradorActionPerformed private void cmbSituacaoFuncionarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbSituacaoFuncionarioActionPerformed }//GEN-LAST:event_cmbSituacaoFuncionarioActionPerformed private void edtSalarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtSalarioActionPerformed // TODO add your handling code here: }//GEN-LAST:event_edtSalarioActionPerformed private void edtSalarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_edtSalarioMouseClicked // TODO add your handling code here: }//GEN-LAST:event_edtSalarioMouseClicked public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastroFuncionarioGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CadastroFuncionarioGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnNovaBairro; private javax.swing.JButton btnNovaCidade; private javax.swing.JButton btnNovaFuncao; private javax.swing.JCheckBox chbCadastrarUsuario; private javax.swing.JComboBox cmbBairro; private javax.swing.JComboBox cmbCidade; private javax.swing.JComboBox cmbEndereco; private javax.swing.JComboBox cmbEstado; private javax.swing.JComboBox cmbEstadoCivil; private javax.swing.JComboBox cmbFuncao; private javax.swing.JComboBox cmbSituacaoFuncionario; private javax.swing.JComboBox cmbTurno; private javax.swing.JFormattedTextField edtCep; private javax.swing.JTextField edtComplemento; private javax.swing.JTextField edtCpf; private javax.swing.JTextField edtCtps; private javax.swing.JTextField edtDataEntrada; private javax.swing.JFormattedTextField edtDataNascimento; private javax.swing.JTextField edtEmail; private javax.swing.JTextField edtFoneCel; private javax.swing.JTextField edtIdentidade; private javax.swing.JTextField edtNome; private javax.swing.JTextField edtNumero; private javax.swing.JTextArea edtObservacoes; private javax.swing.JTextField edtSalario; private javax.swing.JTextField edtTelRes; private javax.swing.JTextField edtUsuLogin; private javax.swing.ButtonGroup grupoNivelAcesso; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JLabel lblBairro; private javax.swing.JLabel lblCadastra; private javax.swing.JLabel lblCep; private javax.swing.JLabel lblCidade; private javax.swing.JLabel lblConfirmarSenha; private javax.swing.JLabel lblCpf; private javax.swing.JLabel lblCtps; private javax.swing.JLabel lblData; private javax.swing.JLabel lblDataNasc; private javax.swing.JLabel lblEmail; private javax.swing.JLabel lblEstadoCivil; private javax.swing.JLabel lblFoneCel; private javax.swing.JLabel lblFoneRes; private javax.swing.JLabel lblFuncao; private javax.swing.JLabel lblFundo; private javax.swing.JLabel lblHora; private javax.swing.JLabel lblNivelAcesso; private javax.swing.JLabel lblObservacoes; private javax.swing.JLabel lblSalario; private javax.swing.JLabel lblSenha; private javax.swing.JLabel lblSituacoaFuncionario; private javax.swing.JLabel lblTurno; private javax.swing.JLabel lblVoltar; private javax.swing.JLabel llblAvaliacao; private javax.swing.JPanel paInfAdicionais; private javax.swing.JPanel pnlBorda; private javax.swing.JPanel pnlCadastrar; private javax.swing.JPanel pnlDados; private javax.swing.JPanel pnlDadosCadastrais; private javax.swing.JPanel pnlEndereco; private javax.swing.JPanel pnlInformacoes; private javax.swing.JTabbedPane pnlPrincipal; private javax.swing.JPanel pnlSexo; private javax.swing.JPasswordField pwfConfirmaSenha; private javax.swing.JPasswordField pwfSenha; private javax.swing.JRadioButton rdbAdministrador; private javax.swing.JRadioButton rdbUsuario; private javax.swing.JRadioButton sexo_fem; private javax.swing.JRadioButton sexo_masc; private org.netbeans.examples.lib.timerbean.Timer tmrHora; // End of variables declaration//GEN-END:variables }
package com.github.wx.gadget.dbo; import lombok.Data; import java.util.Date; @Data public class User { private Integer id; private String name; private String password; private Boolean starred; private Date createTime; private Long version; private String subscribe; private String openid; private String nickname; private String sex; private String city; private String country; private String province; private String language; private String headimgurl; private String subscribeTime; private String unionid; private String remark; private String groupid; }
package com.lec.ex4_Object; public class Card { private char kind; // Character은 객체(data,method), char는 기초타입 private int num; public Card(char kind, int num) { this.kind = kind; this.num = num; }// public @Override public String toString() { return "카드 모양은" + kind + " " + num; }// public @Override // !!중요!! public boolean equals(Object obj) { // Card yours = new Card('♣',8); // Card card = new Card('♣',8); // yours.equals(card) -> this는yours, obj는card // this.kind와 obj.kind가 같고 this.num과 obj.num이 같으면 true if (obj != null && obj instanceof Card) { boolean kindChk = this.kind == ((Card) obj).kind; boolean numChk = num == ((Card) obj).num; return kindChk && numChk; } return false; } }// class
package com.google.android.gms.common.api; import android.content.Context; import android.os.Bundle; import android.support.v4.content.c; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.c.b; import java.io.FileDescriptor; import java.io.PrintWriter; class v$a extends c<ConnectionResult> implements b, c.c { public final c aLT; boolean aLY; private ConnectionResult aLZ; public v$a(Context context, c cVar) { super(context); this.aLT = cVar; } private void g(ConnectionResult connectionResult) { this.aLZ = connectionResult; if (this.mg && !this.qY) { deliverResult(connectionResult); } } public final void a(ConnectionResult connectionResult) { this.aLY = true; g(connectionResult); } public final void dm(int i) { } public final void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) { super.dump(str, fileDescriptor, printWriter, strArr); this.aLT.a(str, printWriter); } public final void e(Bundle bundle) { this.aLY = false; g(ConnectionResult.aJB); } protected final void onReset() { this.aLZ = null; this.aLY = false; this.aLT.b(this); this.aLT.b(this); this.aLT.disconnect(); } protected final void onStartLoading() { super.onStartLoading(); this.aLT.a(this); this.aLT.a(this); if (this.aLZ != null) { deliverResult(this.aLZ); } if (!this.aLT.isConnected() && !this.aLT.isConnecting() && !this.aLY) { this.aLT.connect(); } } protected final void onStopLoading() { this.aLT.disconnect(); } }
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.aws.s3; import static org.springframework.integration.aws.core.AWSCommonUtils.decodeBase64; import static org.springframework.integration.aws.core.AWSCommonUtils.encodeHex; import static org.springframework.integration.aws.core.AWSCommonUtils.getContentsMD5AsBytes; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.integration.aws.s3.core.AmazonS3Object; import org.springframework.integration.aws.s3.core.AmazonS3Operations; import org.springframework.integration.aws.s3.core.PaginatedObjectsView; import org.springframework.integration.aws.s3.core.S3ObjectSummary; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * The implementation for {@link InboundFileSynchronizer}, this implementation will use * the {@link AmazonS3Operations} to list the objects in the remote bucket on invocation of * the {@link #synchronizeToLocalDirectory(File, String, String)}. The listed objects will then * be checked against the * * @author Amol Nayak * * @since 0.5 * */ public class InboundFileSynchronizationImpl implements InboundFileSynchronizer,InitializingBean { private final Log logger = LogFactory.getLog(getClass()); public static final String CONTENT_MD5 = "Content-MD5"; private final AmazonS3Operations client; private volatile int maxObjectsPerBatch = 100; //default private final InboundLocalFileOperations fileOperations; private volatile FileNameFilter filter; private volatile String fileWildcard; private volatile String fileNameRegex; private final Lock lock = new ReentrantLock(); private volatile boolean acceptSubFolders; /** * * @param client */ public InboundFileSynchronizationImpl(AmazonS3Operations client, InboundLocalFileOperations fileOperations) { Assert.notNull(client,"AmazonS3Client should be non null"); Assert.notNull(fileOperations,"fileOperations should be non null"); this.client = client; this.fileOperations = fileOperations; } public void afterPropertiesSet() throws Exception { Assert.isTrue(!(StringUtils.hasText(fileWildcard) && StringUtils.hasText(fileNameRegex)), "Only one of the file name wildcard string or file name regex can be specified"); if(StringUtils.hasText(fileWildcard)) { filter = new WildcardFileNameFilter(fileWildcard); } else if(StringUtils.hasText(fileNameRegex)) { filter = new RegexFileNameFilter(fileNameRegex); } else { filter = new AlwaysTrueFileNamefilter(); //Match all } if(acceptSubFolders) { ((AbstractFileNameFilter)filter).setAcceptSubFolders(true); fileOperations.setCreateDirectoriesIfRequired(true); } } /* (non-Javadoc) * @see org.springframework.integration.aws.s3.InboundFileSynchronizer#synchronizeToLocalDirectory(java.io.File, java.lang.String, java.lang.String) */ public void synchronizeToLocalDirectory(File localDirectory, String bucketName, String remoteFolder) { if(!lock.tryLock()) { if(logger.isInfoEnabled()) { logger.info("Sync already in progess"); } //Prevent concurrent synchronization requests return; } if(logger.isInfoEnabled()) { logger.info("Starting sync with local directory"); } //Below sync can take long, above lock ensures only one thread is synchronizing try { if(remoteFolder != null && "/".equals(remoteFolder)) { remoteFolder = null; } //Set the remote folder for the filter if(filter instanceof AbstractFileNameFilter) { ((AbstractFileNameFilter)filter).setFolderName(remoteFolder); } String nextMarker = null; do { PaginatedObjectsView paginatedView = client.listObjects(bucketName, remoteFolder,nextMarker,maxObjectsPerBatch); if(paginatedView == null) break; //No files to sync nextMarker = paginatedView.getNextMarker(); List<S3ObjectSummary> summaries = paginatedView.getObjectSummary(); for(S3ObjectSummary summary:summaries) { String key = summary.getKey(); if(key.endsWith("/")) { continue; } if(!filter.accept(key)) continue; //The folder is the root as the key is relative to bucket AmazonS3Object s3Object = client.getObject(bucketName, "/", key); synchronizeObjectWithFile(localDirectory,summary,s3Object); } } while(nextMarker != null); } finally { lock.unlock(); if(logger.isInfoEnabled()) { logger.info("Sync completed"); } } } /** * Synchronizes the Object with the File on the local file system * @param localDirectory * @param summary */ private void synchronizeObjectWithFile(File localDirectory,S3ObjectSummary summary, AmazonS3Object s3Object) { //Get the complete object data String key = summary.getKey(); if(key.endsWith("/")) { return; } int lastIndex = key.lastIndexOf("/"); String fileName = key.substring(lastIndex + 1); String filePath = localDirectory.getAbsolutePath(); if(!filePath.endsWith(File.separator)) { filePath += File.separator; } File baseDirectory; if(lastIndex > 0) { //there could very well be previous '/' and thus nested sub folders String prefixKey = key.substring(0, lastIndex); String[] folders = prefixKey.split("/"); if(folders.length > 0) { for(String folder:folders) { filePath = filePath + folder + File.separator; } //create the directory structure baseDirectory = new File(filePath); baseDirectory.mkdirs(); } else { baseDirectory = localDirectory; } } else { baseDirectory = localDirectory; } File file = new File(filePath + fileName); if(!file.exists()) { //File doesnt exist, write the contents to it try { fileOperations.writeToFile(baseDirectory, fileName,s3Object.getInputStream()); } catch (IOException e) { logger.error("Caught Exception while writing to file " + file.getAbsolutePath()); //continue with next file. } } else { //Synchronize a file that exists if(!file.isFile()) { if(logger.isWarnEnabled()) { logger.warn("The file " + file.getAbsolutePath() + " is not a regular file, probably a directory, "); } return; } String eTag = summary.getETag(); String md5Hex = null; if(isEtagMD5Hash(eTag)) { //Single thread upload try { md5Hex = encodeHex(getContentsMD5AsBytes(file)); } catch (UnsupportedEncodingException e) { logger.error("Exception encountered while generating the MD5 hash for the file " + file.getAbsolutePath(), e); } if(!eTag.equals(md5Hex)) { //The local file is different than the one on S3, could be latest but we will still //sync this with the copy on S3 try { fileOperations.writeToFile(baseDirectory, fileName, s3Object.getInputStream()); } catch (IOException e) { logger.error("Caught Exception while writing to file " + file.getAbsolutePath()); } } } else { //Multi part upload //Get the MD5 hash from the headers Map<String, String> userMetaData = s3Object.getUserMetaData(); String b64MD5 = userMetaData.get(CONTENT_MD5); if(b64MD5 != null) { //Need to convert to Hex from Base64 try { md5Hex = encodeHex(getContentsMD5AsBytes(file)); } catch (UnsupportedEncodingException e) { logger.error("Exception encountered while generating the MD5 hash for the file " + file.getAbsolutePath(), e); } try { String remoteHexMD5 = new String( encodeHex( decodeBase64(b64MD5.getBytes("UTF-8")))); if(!md5Hex.equals(remoteHexMD5)) { //Update only if the local file is not same as remote file try { fileOperations.writeToFile(baseDirectory, fileName, s3Object.getInputStream()); } catch (IOException e) { logger.error("Caught Exception while writing to file " + file.getAbsolutePath()); } } } catch (UnsupportedEncodingException e) { //Should never get this, suppress } } else { //Forcefully update the file try { fileOperations.writeToFile(baseDirectory, fileName, s3Object.getInputStream()); } catch (IOException e) { logger.error("Caught Exception while writing to file " + file.getAbsolutePath()); } } } } } /** * Checks if the given eTag is a MD5 hash as hex, the hash is 128 bit and hence * has to be 32 characters in length, also it should contain only hex characters * In case of multi uploads, it is observed that the eTag contains a "-", * and hence this method will return false. * * @param eTag */ private boolean isEtagMD5Hash(String eTag) { if (eTag == null || eTag.length() != 32) { return false; } return eTag.replaceAll("[a-f0-9A-F]", "").length() == 0; } /* (non-Javadoc) * @see org.springframework.integration.aws.s3.InboundFileSynchronizer#setSynchronizingBatchSize(int) */ public void setSynchronizingBatchSize(int batchSize) { if(batchSize > 0) this.maxObjectsPerBatch = batchSize; } /* (non-Javadoc) * @see org.springframework.integration.aws.s3.InboundFileSynchronizer#setFileNamePattern(java.lang.String) */ public void setFileNamePattern(String fileNameRegex) { this.fileNameRegex = fileNameRegex; } /* (non-Javadoc) * @see org.springframework.integration.aws.s3.InboundFileSynchronizer#setFileWildcard(java.lang.String) */ public void setFileWildcard(String fileWildcard) { this.fileWildcard = fileWildcard; } @Override public void setAcceptSubFolders(boolean acceptSubFolders) { this.acceptSubFolders = acceptSubFolders; } }
package com.tencent.mm.plugin.nfc.ui; import android.view.View; import android.view.View.OnClickListener; class HceTestUI$1 implements OnClickListener { final /* synthetic */ HceTestUI lFq; HceTestUI$1(HceTestUI hceTestUI) { this.lFq = hceTestUI; } public final void onClick(View view) { HceTestUI.a(this.lFq); } }
package ru.nikozavr.auto.instruments.database.ModelInfo.ModelGener; import android.os.AsyncTask; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import ru.nikozavr.auto.AutoEncyclopedia; import ru.nikozavr.auto.instruments.database.JSONParser; import ru.nikozavr.auto.model.Generation; import ru.nikozavr.auto.model.ImageItem; import ru.nikozavr.auto.model.Model; public class GetModelGeners extends AsyncTask<Model, Void, Model> { public AsyncModelGeners delegate = null; private String Url; JSONParser jsonParser = new JSONParser(); public GetModelGeners(AsyncModelGeners del, String url){ super(); delegate = del; Url = url; } @Override protected Model doInBackground(Model... par) { int success; try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(AutoEncyclopedia.TAG_ID_MODEL, par[0].getIdModel().toString())); JSONObject json = jsonParser.makeHttpRequest(Url, "POST", params); success = json.getInt(AutoEncyclopedia.TAG_SUCCESS); if (success == 1) { int count = json.getInt(AutoEncyclopedia.TAG_COUNT); JSONArray arr = json.getJSONArray(AutoEncyclopedia.TAG_GENERS); JSONObject temp; par[0].resetGenerations(); for (int i = 0; i < count; i++) { URL url; temp = arr.getJSONObject(i); try { url = new URL(temp.getString(AutoEncyclopedia.TAG_PIC_URL)); } catch (MalformedURLException e) { continue; } par[0].addGeneration(new Generation(temp.getInt(AutoEncyclopedia.TAG_ID_GENER), temp.getString(AutoEncyclopedia.TAG_NAME), temp.getString(AutoEncyclopedia.TAG_PROD_DATE), temp.getString(AutoEncyclopedia.TAG_OUT_DATE), new ImageItem(temp.getInt(AutoEncyclopedia.TAG_ID_PIC_AUTO), url, temp.getString(AutoEncyclopedia.TAG_NAME)))); } } else return null; } catch (JSONException e) { e.printStackTrace(); return null; } catch (NullPointerException e) { e.printStackTrace(); return null; } return par[0]; } @Override protected void onPostExecute(Model result) { delegate.getGenerFinish(result); } }
package com.cimcssc.chaojilanling; import android.app.Application; import com.cimcssc.chaojilanling.util.Config; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; /** * Created by cimcitech on 2017/3/16. */ public class AppApplication extends Application { public static ImageLoader imageLoader = ImageLoader.getInstance(); @Override public void onCreate() { Config.CONTEXT = getApplicationContext(); super.onCreate(); // 图片缓存配置 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).discCacheFileCount(100) .tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging().build(); imageLoader.init(config); } }
package com.youyiwen.Mapper; import com.youyiwen.Bean.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; /** * @Author: zhaoyang * @Date: 2021/03/04 */ @Mapper public interface UserMapper { @Select("select password from user where userName = #{userName} ") public String searchPasswordByName(String userName); @Select("select role from user where userName = #{userName}") public String searchRole(String userName); @Select("select * from user where userName = #{userName} ") public User searchUserByName(String userName); @Insert("insert into user (`userName`,`password`,`fullName`,`telephone`,`city`,`job`,`gender`,`Email`,`role`) " + "values (#{userName},#{password},#{fullName},#{telephone},#{city},#{job},#{gender},#{Email},#{role})") public int insertUser(User user); }
package com.tencent.mm.g.a; import android.graphics.Bitmap; public final class on$a { public int bZs = 0; public String bZt; public Bitmap bZu; public String cardType; }
package com.figureshop.springmvc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FigurineShopApplication { public static void main(String[] args) { SpringApplication.run(FigurineShopApplication.class, args); } }
package unclassified; import java.util.PriorityQueue; /** * As seen in Ctci page 54 and EPI page 156. * * Numbers are generated randomly and stored in an expanding array. * How would you keep track of the median? */ public class FindMedian { /** * Uses one maxheap. Solves the problem for fixed array. * Space: O(n/2), time: O(n logn/2) * * Notes: * This solution can be adapted for streaming ints/consequent runs. * Similar to the topK algo in EPI page 150, where k=n/2. * It can be solved with a min heap too and reverting the if statement to insert a new head. * * Optimal solution uses 2 heaps, O(logn) time, found in EPI. For streaming ints you need O(n) space for the consequent runs. * Sorting first and then peeking the medium would be slightly worse O(nlogn) */ public static double median(int[] A) { PriorityQueue<Integer> maxHeap = new PriorityQueue<>(A.length / 2 + 1, (a, b) -> Integer.compare(b, a)); for (int i = 0; i < A.length / 2 + 1; i++) { maxHeap.add(A[i]); } for (int i = A.length / 2 + 1; i < A.length; i++) { // can be written as a single loop if (A[i] < maxHeap.peek()) { maxHeap.add(A[i]); maxHeap.poll(); } } return A.length % 2 == 0 ? (maxHeap.poll() + maxHeap.poll()) * 0.5 : maxHeap.poll(); } public static void main(String[] args) { System.out.println(median(new int[]{2, 0, 3, 1})); } }
package com.bricenangue.nextgeneration.ebuycamer; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import org.json.JSONObject; import java.math.BigDecimal; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; /** * Created by bricenangue on 02/08/16. */ public class RecyclerViewAdapterPosts extends RecyclerView .Adapter<RecyclerViewAdapterPosts .PublicationViewHolders> { private static String LOG_TAG = "RecyclerViewAdapterPost"; private ArrayList<Publication> mDataset; private MyRecyclerAdaptaterPostClickListener myClickListener; private Context context; private String [] currencyArray; public static class PublicationViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{ ImageView postPicture,imageViewLocation; TextView titel, time, price, mylocation,isnegotiable; private View view; private MyRecyclerAdaptaterPostClickListener clickListener; public PublicationViewHolders(View itemView, MyRecyclerAdaptaterPostClickListener clickListener) { super(itemView); view=itemView; this.clickListener=clickListener; postPicture=(ImageView) itemView.findViewById(R.id.imageView_publicationFirstphoto); imageViewLocation=(ImageView) itemView.findViewById(R.id.imageView_publicationLocation); isnegotiable=(TextView)itemView.findViewById(R.id.textView_publication_is_negotiable); titel=(TextView) itemView.findViewById(R.id.textView_publication_title); time=(TextView) itemView.findViewById(R.id.textView_publication_time); price=(TextView) itemView.findViewById(R.id.textView_publication_price); mylocation=(TextView) itemView.findViewById(R.id.textView_publication_locatiomn); view.setOnClickListener(this); } @Override public void onClick(View view) { clickListener.onItemClick(getAdapterPosition(),view); } } public void setOnPostClickListener(MyRecyclerAdaptaterPostClickListener myClickListener) { this.myClickListener = myClickListener; } public RecyclerViewAdapterPosts(Context context, ArrayList<Publication> myDataset , MyRecyclerAdaptaterPostClickListener myClickListener) { this.context=context; mDataset = myDataset; this.myClickListener=myClickListener; currencyArray=context.getResources().getStringArray(R.array.currency); } @Override public PublicationViewHolders onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_publication, parent, false); PublicationViewHolders dataObjectHolder = new PublicationViewHolders(view,myClickListener); return dataObjectHolder; } @Override public void onBindViewHolder(final PublicationViewHolders viewHolder, final int position) { final Publication model=mDataset.get(position); if(model.getPrivateContent().isNegotiable()){ viewHolder.isnegotiable.setText(context.getString(R.string.text_is_not_negotiable)); }else { viewHolder.isnegotiable.setText(""); } viewHolder.titel.setText(model.getPrivateContent().getTitle()); viewHolder.mylocation.setText(model.getPrivateContent().getLocation().getName()); if(model.getPrivateContent().getFirstPicture()!=null){ byte[] decodedString = Base64.decode(model.getPrivateContent().getFirstPicture(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); viewHolder.postPicture.setImageBitmap(decodedByte); }else { if(model.getPrivateContent().getPublictionPhotos()!=null){ Picasso.with(context).load(model.getPrivateContent().getPublictionPhotos().get(0).getUri()) .networkPolicy(NetworkPolicy.OFFLINE) .fit().centerInside() .into(viewHolder.postPicture, new Callback() { @Override public void onSuccess() { } @Override public void onError() { Picasso.with(context).load(model.getPrivateContent() .getPublictionPhotos().get(0).getUri()) .fit().centerInside().into(viewHolder.postPicture); } }); }else { viewHolder.postPicture.setImageDrawable(context.getResources().getDrawable(R.mipmap.ic_launcher)); } } DecimalFormat decFmt = new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(Locale.GERMAN)); decFmt.setMaximumFractionDigits(2); decFmt.setMinimumFractionDigits(2); String p=model.getPrivateContent().getPrice(); BigDecimal amt = new BigDecimal(p); String preValue = decFmt.format(amt); if(p.equals("0")){ viewHolder.price.setText(context.getString(R.string.check_box_create_post_hint_is_for_free)); }else { if(currencyArray!=null){ viewHolder.price.setText(preValue + " " + currencyArray[getCurrencyPosition(model.getPrivateContent().getCurrency())]); }else { viewHolder.price.setText(preValue + " " + model.getPrivateContent().getCurrency()); } } Date date = new Date(model.getPrivateContent().getTimeofCreation()); DateFormat formatter = new SimpleDateFormat("HH:mm"); String dateFormatted = formatter.format(date); CheckTimeStamp checkTimeStamp= new CheckTimeStamp(context,model.getPrivateContent().getTimeofCreation()); viewHolder.time.setText(checkTimeStamp.checktime()); } @Override public int getItemCount() { return mDataset.size(); } public interface MyRecyclerAdaptaterPostClickListener { public void onItemClick(int position, View v); public void onLongClick(int position, View v); } private int getCurrencyPosition(String currency){ if(currency.equals(context.getString(R.string.currency_xaf)) || currency.equals("F CFA") || currency.equals("XAF")){ return 0; } return 0; } }
package com.itfdms.common.util; import com.itfdms.common.constant.CommonConstant; import com.itfdms.common.util.exception.CheckedException; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.codec.Base64; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * @author lxr * @Title: AuthUtils * @ProjectName itfdms_blog * @Description: 认证授权相关工具类 * @date 2018-07-1116:32 */ @Slf4j public class AuthUtils { private static final String BASIC_ = "Basic"; /** *   * @Description: 从header 请求中的clientId/clientsecect *   * @param header header中的参数 *   * @return ${return_type} *   * @throws *   * @author lxr *   * @date 2018-07-11 16:34 */ public static String[] extractAndDecodeHeader(String header) throws IOException { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (Exception e) { throw new CheckedException("Failed to decode basic authentication token"); } String token = new String(decoded,CommonConstant.UTF8); int delim = token.indexOf(":"); if (delim == -1) { throw new CheckedException("Invalid basic authentication token"); } return new String[] {token.substring(0,delim),token.substring(delim + 1)}; } /** * 从header请求中的clientId/clientsecect * @param request * @return */ public static String[] extractAndDecodeHeader(HttpServletRequest request) throws IOException{ String header = request.getHeader("Authorization"); if (header == null || !header.startsWith(BASIC_)) { throw new CheckedException("请求头中client信息为空"); } byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (Exception e) { throw new CheckedException("Failed to decode basic authentication token"); } String token = new String(decoded,CommonConstant.UTF8); int delim = token.indexOf(":"); if (delim == -1) { throw new CheckedException("Invalid basic authentication token"); } return new String[] {token.substring(0,delim),token.substring(delim + 1)}; } }
package com.tencent.mm.ui.conversation; import android.content.Context; import android.content.res.ColorStateList; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.format.Time; import android.text.style.ForegroundColorSpan; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.model.au; import com.tencent.mm.model.s; import com.tencent.mm.modelvoice.n; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.sdk.e.l; import com.tencent.mm.sdk.e.m; import com.tencent.mm.sdk.e.m.b; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.al; import com.tencent.mm.sdk.platformtools.w; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.ai; import com.tencent.mm.ui.base.MMSlideDelView; import com.tencent.mm.ui.base.MMSlideDelView.c; import com.tencent.mm.ui.base.MMSlideDelView.d; import com.tencent.mm.ui.base.MMSlideDelView.f; import com.tencent.mm.ui.base.MMSlideDelView.g; import com.tencent.mm.ui.base.NoMeasuredTextView; import com.tencent.mm.ui.r; import java.util.HashMap; import java.util.Map.Entry; public final class h extends r<ai> implements b { private static long uoj = 2000; private String bVX; protected g hkN; protected c hkO; protected f hkP; protected d hkQ = MMSlideDelView.getItemStatusCallBack(); private float tEh = -1.0f; private float tEi = -1.0f; private float tEj = -1.0f; HashMap<String, a> tEl; private boolean unX = false; private boolean unY = false; public String uoe = ""; private final int uog; private final int uoh; private boolean uok = false; al uol = new al(au.Em().lnJ.getLooper(), new 1(this), false); private ColorStateList[] uqm = new ColorStateList[5]; private class a { public int hER; public CharSequence nickName; public boolean qBs; public boolean tEm; public int uoA; public CharSequence uop; public CharSequence uoq; public int uor; public int uos; public boolean uov; public boolean uox; public boolean uoz; public boolean uqo; private a() { } /* synthetic */ a(h hVar, byte b) { this(); } } public h(Context context, String str, com.tencent.mm.ui.r.a aVar) { super(context, new ai()); this.tlG = aVar; this.bVX = str; this.tEl = new HashMap(); this.uqm[0] = com.tencent.mm.bp.a.ac(context, R.e.hint_text_color); this.uqm[1] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_unread); this.uqm[3] = com.tencent.mm.bp.a.ac(context, R.e.normal_text_color); this.uqm[2] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_three); this.uqm[2] = com.tencent.mm.bp.a.ac(context, R.e.mm_list_textcolor_three); this.uqm[4] = com.tencent.mm.bp.a.ac(context, R.e.light_text_color); if (com.tencent.mm.bp.a.fi(context)) { this.uoh = context.getResources().getDimensionPixelSize(R.f.ConversationTimeBiggerWidth); this.uog = context.getResources().getDimensionPixelSize(R.f.ConversationTimeSmallWidth); } else { this.uoh = context.getResources().getDimensionPixelSize(R.f.ConversationTimeBigWidth); this.uog = context.getResources().getDimensionPixelSize(R.f.ConversationTimeSmallerWidth); } this.tEh = (float) com.tencent.mm.bp.a.ad(context, R.f.NormalTextSize); this.tEi = (float) com.tencent.mm.bp.a.ad(context, R.f.HintTextSize); this.tEj = (float) com.tencent.mm.bp.a.ad(context, R.f.SmallestTextSize); au.HU(); com.tencent.mm.model.c.FW().a(this); } public final void setPerformItemClickListener(g gVar) { this.hkN = gVar; } public final void a(f fVar) { this.hkP = fVar; } public final void setGetViewPositionCallback(c cVar) { this.hkO = cVar; } public final void onPause() { if (this.hkQ != null) { this.hkQ.aYl(); } this.unX = false; } public final void onResume() { boolean z = true; this.unX = true; Time time = new Time(); time.setToNow(); String charSequence = com.tencent.mm.pluginsdk.f.g.a("MM/dd", time).toString(); if (this.uoe.equals(charSequence)) { z = false; } this.uoe = charSequence; if (z) { cyH(); } if (this.unY) { super.a(null, null); this.unY = false; } } protected final void WS() { WT(); } public final void WT() { aYc(); au.HU(); setCursor(com.tencent.mm.model.c.FW().b(s.dAN, null, this.bVX)); if (this.tlG != null) { this.tlG.Xb(); } super.notifyDataSetChanged(); } public final View getView(int i, View view, ViewGroup viewGroup) { b bVar; View inflate; int i2; a aVar; ai aiVar = (ai) getItem(i); String str = aiVar.field_username; b bVar2 = null; if (view != null) { bVar2 = (b) view.getTag(); } if (view == null || bVar2 == null) { bVar = new b(); if (com.tencent.mm.bp.a.fi(this.context)) { inflate = View.inflate(this.context, R.i.conversation_item_large, null); } else { inflate = View.inflate(this.context, R.i.conversation_item, null); } bVar.eCl = (ImageView) inflate.findViewById(R.h.avatar_iv); bVar.uqp = (NoMeasuredTextView) inflate.findViewById(R.h.nickname_tv); bVar.uqp.setTextSize(0, this.tEh); bVar.uqp.setTextColor(this.uqm[3]); bVar.uqp.setShouldEllipsize(true); bVar.uqq = (NoMeasuredTextView) inflate.findViewById(R.h.update_time_tv); bVar.uqq.setTextSize(0, this.tEj); bVar.uqq.setTextColor(this.uqm[4]); bVar.uqq.setShouldEllipsize(false); bVar.uqq.setGravity(5); bVar.uqr = (NoMeasuredTextView) inflate.findViewById(R.h.last_msg_tv); bVar.uqr.setTextSize(0, this.tEi); bVar.uqr.setTextColor(this.uqm[0]); bVar.uqr.setShouldEllipsize(true); bVar.uqs = (TextView) inflate.findViewById(R.h.tipcnt_tv); bVar.uqs.setBackgroundResource(com.tencent.mm.ui.tools.r.hd(this.context)); bVar.tEs = (ImageView) inflate.findViewById(R.h.image_mute); bVar.tEu = inflate.findViewById(R.h.avatar_prospect_iv); inflate.findViewById(R.h.talkroom_iv).setVisibility(8); inflate.findViewById(R.h.location_share_iv).setVisibility(8); inflate.setTag(bVar); } else { bVar = bVar2; inflate = view; } a aVar2 = (a) this.tEl.get(str); au.HU(); ab Yg = com.tencent.mm.model.c.FR().Yg(str); if (aVar2 == null) { a aVar3 = new a(this, (byte) 0); if (Yg != null) { aVar3.uos = (int) Yg.dhP; } else { aVar3.uos = -1; } aVar3.uox = Yg != null; boolean z = Yg != null && Yg.BE(); aVar3.uoz = z; z = Yg != null && Yg.BD(); aVar3.uov = z; aVar3.uqo = aiVar.field_unReadCount > 0; aVar3.hER = 0; if (j(aiVar) == 34 && aiVar.field_isSend == 0 && !com.tencent.mm.platformtools.ai.oW(aiVar.field_content) && !new n(aiVar.field_content).enG) { aVar3.hER = 1; } aVar3.nickName = j.a(this.context, com.tencent.mm.model.r.a(Yg, str, false), bVar.uqp.getTextSize()); aVar3.uop = h(aiVar); int textSize = (int) bVar.uqr.getTextSize(); z = aVar3.uov && aVar3.uqo; aVar3.uoq = c(aiVar, textSize, z); aVar3.uoA = aiVar.field_attrflag; switch (aiVar.field_status) { case 0: i2 = -1; break; case 1: i2 = R.k.msg_state_sending; break; case 2: i2 = -1; break; case 5: i2 = R.k.msg_state_failed; break; default: i2 = -1; break; } aVar3.uor = i2; au.HU(); aVar3.tEm = com.tencent.mm.model.c.FW().g(aiVar); aVar3.qBs = w.chL(); this.tEl.put(str, aVar3); aVar = aVar3; } else { aVar = aVar2; } if (aVar.uop == null) { aVar.uop = h(aiVar); } if (aVar.uov && aVar.uqo) { bVar.uqr.setTextColor(this.uqm[0]); } else { bVar.uqr.setTextColor(this.uqm[aVar.hER]); } com.tencent.mm.booter.notification.a.h.fz(bVar.uqr.getWidth()); com.tencent.mm.booter.notification.a.h.fA((int) bVar.uqr.getTextSize()); com.tencent.mm.booter.notification.a.h.a(bVar.uqr.getPaint()); if (aVar.uor != -1) { bVar.uqr.setCompoundLeftDrawablesWithIntrinsicBounds(aVar.uor); bVar.uqr.setDrawLeftDrawable(true); } else { bVar.uqr.setDrawLeftDrawable(false); } bVar.uqr.setText(aVar.uoq); bVar.uqp.setDrawRightDrawable(false); bVar.uqp.setText(aVar.nickName); LayoutParams layoutParams = bVar.uqq.getLayoutParams(); if (aVar.uop.length() > 9) { if (layoutParams.width != this.uoh) { layoutParams.width = this.uoh; bVar.uqq.setLayoutParams(layoutParams); } } else if (layoutParams.width != this.uog) { layoutParams.width = this.uog; bVar.uqq.setLayoutParams(layoutParams); } bVar.uqq.setText(aVar.uop); if (aVar.uov) { bVar.tEs.setVisibility(0); } else { bVar.tEs.setVisibility(8); } com.tencent.mm.pluginsdk.ui.a.b.a(bVar.eCl, str); bVar.uqs.setVisibility(4); bVar.tEu.setVisibility(4); if (aVar.uox && aVar.uos != 0) { i2 = aiVar.field_unReadCount; if (aVar.uov) { View view2 = bVar.tEu; if (i2 > 0) { i2 = 0; } else { i2 = 4; } view2.setVisibility(i2); } else if (i2 > 99) { bVar.uqs.setText(R.l.unread_count_overt_100); bVar.uqs.setVisibility(0); } else if (i2 > 0) { bVar.uqs.setText(String.valueOf(i2)); bVar.uqs.setVisibility(0); } } if (!aVar.tEm || aiVar.field_conversationTime == -1) { inflate.findViewById(R.h.conversation_item_ll).setBackgroundResource(R.g.comm_list_item_selector); } else { inflate.findViewById(R.h.conversation_item_ll).setBackgroundResource(R.g.comm_item_highlight_selector); } com.tencent.mm.ui.a.a.a.cqX().a(inflate, String.valueOf(aVar.nickName), aiVar.field_unReadCount, String.valueOf(aVar.uop), String.valueOf(aVar.uoq)); return inflate; } private static int j(ai aiVar) { int i = 1; String str = aiVar.field_msgType; if (str == null || str.length() <= 0) { return i; } try { return Integer.valueOf(str).intValue(); } catch (NumberFormatException e) { return i; } } private CharSequence c(ai aiVar, int i, boolean z) { CharSequence replace; if (com.tencent.mm.platformtools.ai.oW(aiVar.field_editingMsg) || (aiVar.field_atCount > 0 && aiVar.field_unReadCount > 0)) { CharSequence charSequence = aiVar.field_digest; if (charSequence != null && charSequence.startsWith("<img src=\"original_label.png\"/> ")) { return new SpannableString(j.c(this.context, charSequence, (float) i)); } String str; if (j(aiVar) == 47 || j(aiVar) == 1048625) { String aaf = aaf(aiVar.field_digest); str = ""; if (aaf != null) { return "[" + aaf + "]"; } if (aiVar.field_digest != null && aiVar.field_digest.contains(":")) { str = aiVar.field_digest.substring(0, aiVar.field_digest.indexOf(":")); aaf = aaf(aiVar.field_digest.substring(aiVar.field_digest.indexOf(":") + 1).replace(" ", "")); if (aaf != null) { aaf = "[" + aaf + "]"; return com.tencent.mm.platformtools.ai.oW(str) ? aaf : str + ": " + aaf; } } aaf = this.context.getString(R.l.app_emoji); aiVar.ed(com.tencent.mm.platformtools.ai.oW(str) ? aaf : str + ": " + aaf); } if (!com.tencent.mm.platformtools.ai.oW(aiVar.field_digest)) { if (com.tencent.mm.platformtools.ai.oW(aiVar.field_digestUser)) { str = aiVar.field_digest; } else { str = (aiVar.field_isSend == 0 && s.fq(aiVar.field_username)) ? com.tencent.mm.model.r.getDisplayName(aiVar.field_digestUser, aiVar.field_username) : com.tencent.mm.model.r.gT(aiVar.field_digestUser); try { str = String.format(aiVar.field_digest, new Object[]{str}); } catch (Exception e) { } } replace = str.replace(10, ' '); if (aiVar.field_atCount > 0 || aiVar.field_unReadCount <= 0) { if (z && aiVar.field_unReadCount > 1) { replace = this.context.getString(R.l.main_conversation_chatroom_unread_digest, new Object[]{Integer.valueOf(aiVar.field_unReadCount), replace}); } return j.a(this.context, replace, i); } SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(this.context.getString(R.l.main_conversation_chatroom_at_hint)); spannableStringBuilder.setSpan(new ForegroundColorSpan(-5569532), 0, spannableStringBuilder.length(), 33); spannableStringBuilder.append(" ").append(j.a(this.context, replace, i)); return spannableStringBuilder; } str = com.tencent.mm.booter.notification.a.h.a(aiVar.field_isSend, aiVar.field_username, aiVar.field_content, j(aiVar), this.context); replace = str.replace(10, ' '); if (aiVar.field_atCount > 0) { } replace = this.context.getString(R.l.main_conversation_chatroom_unread_digest, new Object[]{Integer.valueOf(aiVar.field_unReadCount), replace}); return j.a(this.context, replace, i); } replace = new SpannableStringBuilder(this.context.getString(R.l.main_conversation_last_editing_msg_prefix)); replace.setSpan(new ForegroundColorSpan(-5569532), 0, replace.length(), 33); replace.append(" ").append(j.a(this.context, aiVar.field_editingMsg, i)); return replace; } private static String aaf(String str) { if (str == null || str.length() != 32) { return null; } return ((com.tencent.mm.plugin.emoji.b.c) com.tencent.mm.kernel.g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zf(str); } private CharSequence h(ai aiVar) { if (aiVar.field_status == 1) { return this.context.getString(R.l.main_sending); } return aiVar.field_conversationTime == Long.MAX_VALUE ? "" : com.tencent.mm.pluginsdk.f.h.c(this.context, aiVar.field_conversationTime, true); } private void cyH() { if (this.tEl != null) { for (Entry value : this.tEl.entrySet()) { ((a) value.getValue()).uop = null; } } } public final void a(int i, m mVar, Object obj) { if (obj == null || !(obj instanceof String)) { x.e("MicroMsg.EnterpriseConversationAdapter", "onNotifyChange obj not String event:%d stg:%s obj:%s", new Object[]{Integer.valueOf(i), mVar, obj}); return; } a((String) obj, null); } public final void a(String str, l lVar) { x.i("MicroMsg.EnterpriseConversationAdapter", "dkpno onNotifyChange mIsFront:%b mChangedBackground:%b event:%s", new Object[]{Boolean.valueOf(this.unX), Boolean.valueOf(this.unY), str}); if (!(com.tencent.mm.platformtools.ai.oW(str) || this.tEl == null)) { this.tEl.remove(str); } if (this.unX) { x.d("MicroMsg.EnterpriseConversationAdapter", "dkpno postTryNotify needNotify:%b timerStopped:%b", new Object[]{Boolean.valueOf(this.uok), Boolean.valueOf(this.uol.ciq())}); this.uok = true; if (this.uol.ciq()) { cyI(); return; } return; } this.unY = true; } private void cyI() { ah.A(new 2(this)); } }
package pl.ark.chr.buginator.security.oauth2; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.provider.ClientDetailsService; @Configuration @ImportAutoConfiguration(OAuth2DetailsServiceConfig.class) public class OAuth2ResourceFilterConfig { @Bean public FilterRegistrationBean oauth2ClientFilter(ClientDetailsService oauth2ClientDetailsService) { FilterRegistrationBean bean = new FilterRegistrationBean<>(new OAuth2ClientFilter(oauth2ClientDetailsService)); bean.setOrder(2); return bean; } }
package navi.common.connector; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; public class TestDatagramClient { public static void main(String[] args) throws IOException { InetAddress address = InetAddress.getByName("127.0.0.1"); int port = 1234; DatagramSocket socket = new DatagramSocket(); socket.connect(new InetSocketAddress(address, port)); DatagramConnector client = new DatagramConnector(socket, address, port); client.setListener(new DatagramClientListener()); client.start(); client.send(new byte[]{0x0, 0x1, 0x2}); client.interrupt(); } }
package com.ar.cmsistemas.dao; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.ar.cmsistemas.db.DataSource; import com.ar.cmsistemas.domain.Ciudad; import com.ar.cmsistemas.domain.TipoDeOperacion; import oracle.jdbc.OracleTypes; public class TipoDeOperacionDao { public List<TipoDeOperacion> getTiposDeOperaciones() { Connection connection = null; CallableStatement cs = null; ResultSet rs = null; List<TipoDeOperacion> lista = new ArrayList<TipoDeOperacion>(); try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.consultas_inmobiliaria.get_tipo_de_operaciones(?)}"; cs = connection.prepareCall(call); cs.registerOutParameter(1, OracleTypes.CURSOR); cs.execute(); rs = (ResultSet)cs.getObject(1); while (rs.next()) { TipoDeOperacion op = new TipoDeOperacion(); op.setId(rs.getInt("tipo_de_oracion_id")); op.setDescripcion(rs.getString("descripcion")); lista.add(op); } } catch (SQLException s) { System.out.println("Error: "); s.printStackTrace(); } catch (Exception e) { System.out.println("Error: "); e.printStackTrace(); }finally { if (rs != null) try { rs.close(); } catch (SQLException e) {e.printStackTrace();} if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } return lista; } public TipoDeOperacion getTipoDeOperacionById(Integer id) { Connection connection = null; CallableStatement cs = null; ResultSet rs = null; TipoDeOperacion op = new TipoDeOperacion(); try { connection = DataSource.getInstance().getConnection(); String call = "{call tp_dba.consultas_inmobiliaria.get_tipo_de_op_by_id(?,?)}"; cs = connection.prepareCall(call); cs.setInt(1,id); cs.registerOutParameter(2, OracleTypes.CURSOR); cs.execute(); rs = (ResultSet)cs.getObject(2); while (rs.next()) { op.setId(rs.getInt("tipo_de_oracion_id")); op.setDescripcion(rs.getString("descripcion")); } } catch (SQLException s) { System.out.println("Error: "); s.printStackTrace(); } catch (Exception e) { System.out.println("Error: "); e.printStackTrace(); }finally { if (rs != null) try { rs.close(); } catch (SQLException e) {e.printStackTrace();} if (cs != null) try { cs.close(); } catch (SQLException e) {e.printStackTrace();} if (connection != null) try { connection.close(); } catch (SQLException e) {e.printStackTrace();} } return op; } }
package net.minecraft.network.play.server; import java.io.IOException; import net.minecraft.entity.Entity; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; public class SPacketEntityStatus implements Packet<INetHandlerPlayClient> { private int entityId; private byte logicOpcode; public SPacketEntityStatus() {} public SPacketEntityStatus(Entity entityIn, byte opcodeIn) { this.entityId = entityIn.getEntityId(); this.logicOpcode = opcodeIn; } public void readPacketData(PacketBuffer buf) throws IOException { this.entityId = buf.readInt(); this.logicOpcode = buf.readByte(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeInt(this.entityId); buf.writeByte(this.logicOpcode); } public void processPacket(INetHandlerPlayClient handler) { handler.handleEntityStatus(this); } public Entity getEntity(World worldIn) { return worldIn.getEntityByID(this.entityId); } public byte getOpCode() { return this.logicOpcode; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketEntityStatus.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * UniTime 3.4 - 3.5 (University Timetabling Application) * Copyright (C) 2012 - 2013, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable.onlinesectioning.updates; import java.util.Set; import org.unitime.timetable.model.StudentSectioningStatus; import org.unitime.timetable.onlinesectioning.OnlineSectioningAction; import org.unitime.timetable.onlinesectioning.OnlineSectioningHelper; import org.unitime.timetable.onlinesectioning.OnlineSectioningServer; import org.unitime.timetable.onlinesectioning.model.XCourseRequest; import org.unitime.timetable.onlinesectioning.model.XStudent; /** * @author Tomas Muller */ public abstract class WaitlistedOnlineSectioningAction<T> implements OnlineSectioningAction<T> { private static final long serialVersionUID = 1L; private Set<String> iWaitlistStatuses = null; public boolean isWaitListed(XStudent student, XCourseRequest request, OnlineSectioningServer server, OnlineSectioningHelper helper) { // Check wait-list toggle first if (request == null || !request.isWaitlist()) return false; // Check student status String status = student.getStatus(); if (status == null) status = server.getAcademicSession().getDefaultSectioningStatus(); if (status != null) { if (iWaitlistStatuses == null) iWaitlistStatuses = StudentSectioningStatus.getMatchingStatuses(StudentSectioningStatus.Option.waitlist); if (!iWaitlistStatuses.contains(status)) return false; } return true; } }
package support.yz.data.mvc.service.impl; import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import support.yz.data.entity.neo4j.Technology; import support.yz.data.entity.node.Group; import support.yz.data.entity.node.News; import support.yz.data.entity.node.TechnologyChain; import support.yz.data.entity.node.TechnologyChain2; import support.yz.data.mvc.mapper.*; import support.yz.data.mvc.service.inter.QueryNeo4jService; @Service public class QueryNeo4jServiceImpl implements QueryNeo4jService { //技术关键字、技术关键字关系 @Autowired RTechnologyTechnologyRepository rTechnologyTechnologyRepository; //技术关键字、企业关系 @Autowired RTechnoCompanyRepository rTechnoCompanyRepository; //企业、技术关键字关系 @Autowired RCompanyTechnoRepository rCompanyTechnoRepository; //企业、新闻关系 @Autowired RGroupNewsRepository rGroupNewsRepository; //企业、企业关系 @Autowired RGroupGroupRepository rGroupGroupRepository; @Autowired NodeRepository nodeRepository; @Override public List<Technology> findTechnologyChildrens(String technology) throws Exception { return rTechnologyTechnologyRepository.findChildrens(technology); } @Override public List<Group> findCompanyByTechnology(String technology) throws Exception { return rTechnoCompanyRepository.findByTechnology(technology); } @Override public List<Technology> findTechnologyByCompany(String company) throws Exception { return rCompanyTechnoRepository.findByGroup(company); } @Override public List<News> findNewsByCompany(String com_name) throws Exception { return rGroupNewsRepository.findByGroup(com_name); } @Override public List<Group> findCompanyByCompany(String com_name) throws Exception { List<Group> list = new ArrayList<Group>(); List<Group> list1 = rGroupGroupRepository.findByGroup(com_name); List<Group> list2 = rGroupGroupRepository.findByGroup2(com_name); if (list1 != null) list.addAll(list1); if (list2 != null) list.addAll(list2); return list; } @Override public TechnologyChain findTechnologyChain() throws Exception { TechnologyChain result = new TechnologyChain(); result.setName("人工智能"); Set<String> set = new HashSet<String>(); set.add("人工智能"); Queue<TechnologyChain> q = new LinkedList<TechnologyChain>(); q.add(result); while (q.isEmpty() == false) { TechnologyChain tc = q.poll(); List<Technology> childrens= rTechnologyTechnologyRepository.findChildrens(tc.getName()); for (Technology t : childrens) { //判断是否回环,回环表示当前技术关键词已经出现过,不处理会造成死循环 if (set.contains(t.getName())) continue; else set.add(t.getName()); TechnologyChain temp = new TechnologyChain(); temp.setName(t.getName()); tc.getChildren().add(temp);//加入当前节点的子节点 q.add(temp);//当前节点的子节点入队列 } } // TODO Auto-generated method stub return result; } @Override public Set<String> findTechnologyChildren(String technology_name) throws Exception { TechnologyChain result = new TechnologyChain(); Set<String> result2 = new HashSet<String>(); result.setName(technology_name); Set<String> set = new HashSet<String>(); set.add(technology_name); Queue<TechnologyChain> q = new LinkedList<TechnologyChain>(); q.add(result); result2.add(result.getName()); while (q.isEmpty() == false) { TechnologyChain tc = q.poll(); List<Technology> childrens= rTechnologyTechnologyRepository.findChildrens(tc.getName()); for (Technology t : childrens) { //判断是否回环,回环表示当前技术关键词已经出现过,不处理会造成死循环 if (set.contains(t.getName())) continue; else set.add(t.getName()); TechnologyChain temp = new TechnologyChain(); temp.setName(t.getName()); tc.getChildren().add(temp);//加入当前节点的子节点 q.add(temp);//当前节点的子节点入队列 result2.add(temp.getName()); } } return result2; } @Override public Set<News> findNewsByTechnology(String s) throws Exception { Set<News> result = new HashSet<News>(); List<Group> coms = rTechnoCompanyRepository.findByTechnology(s); for(Group g : coms) { List<News> news = rGroupNewsRepository.findByGroup(g.getName()); for(News n : news) { result.add(n); } } return result; } @Override public TechnologyChain findComByTechInTChain(String technology_name) throws Exception { TechnologyChain result = new TechnologyChain(); TechnologyChain Layered = new TechnologyChain(); result.setName("人工智能"); Layered.setName("Layered"); Set<String> set = new HashSet<String>(); set.add("人工智能"); Queue<TechnologyChain> q = new LinkedList<TechnologyChain>(); q.add(result); q.add(Layered); boolean finded = false; boolean findInChilded = false; boolean lastLayered = false; while (q.isEmpty() == false) { if(technology_name.equals("人工智能")) { finded = true; } TechnologyChain tc = q.poll(); //判断在目标是不是当前节点的孩子节点 if( findInChilded == false) { for(Technology te : rTechnologyTechnologyRepository.findChildrens(tc.getName())) { if(te.getName().equals(technology_name)) { findInChilded =true; break; } } } if(tc.getName().equals("Layered")) { q.add(Layered); if(findInChilded == true) { finded = true; } if(lastLayered == true) { break; }else { lastLayered = true; } }else { lastLayered = false; } if(finded == false) { List<Technology> childrens= rTechnologyTechnologyRepository.findChildrens(tc.getName()); for (Technology t : childrens) { //判断是否回环,回环表示当前技术关键词已经出现过,不处理会造成死循环 if (set.contains(t.getName())) continue; else set.add(t.getName()); TechnologyChain temp = new TechnologyChain(); temp.setName(t.getName()); tc.getChildren().add(temp);//加入当前节点的子节点 q.add(temp);//当前节点的子节点入队列 } }else { if(tc.getName().equals(technology_name)) { Set<String> techs = findTechnologyChildren(technology_name); for(String t : techs) { List<Group> tech = rTechnoCompanyRepository.findByTechnology(t); Set<String> sete = new HashSet<String>(); for(Group g : tech) { TechnologyChain temp = new TechnologyChain(); if(sete.contains(g.getName()) == false) { if(g.getName().equals("北京蓦然认知科技有限公司上海圣尧智能科技有限公司")) { temp.setName("北京蓦然认知科技有限公司"); }else { temp.setName(g.getName()); } sete.add(g.getName()); tc.getChildren().add(temp); } } } break; }else { continue; } } } return result; } @Override public Map<Long,String> findTechnologyChildren2(Long id,String name) throws Exception { Map<Long,String> result2 = new HashMap<Long,String>(); List<Technology> childrens= rTechnologyTechnologyRepository.findChildrens2(id); for (Technology t : childrens) { result2.put(t.getId(),t.getName()); } return result2; } }
package ro.redeul.google.go.inspection; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.QuickFix; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import ro.redeul.google.go.FileDataBasedTest; import ro.redeul.google.go.lang.psi.GoFile; public class UnusedImportInspectionTest extends FileDataBasedTest { public void testSimple() throws Exception{ doTest(); } public void testOnlyOneImport() throws Exception{ doTest(); } public void testBlankImport() throws Exception{ doTest(); } @Override protected void invoke(Project project, Editor myEditor, GoFile file) { InspectionManager im = InspectionManager.getInstance(project); for (ProblemDescriptor pd : new UnusedImportInspection().doCheckFile(file, im)) { QuickFix[] fixes = pd.getFixes(); assertEquals(1, fixes.length); fixes[0].applyFix(project, pd); } } @Override protected String getTestDataRelativePath() { return "inspection/unusedImport/"; } }
package poc.ignite.repos; import org.apache.ignite.springdata.repository.IgniteRepository; import org.apache.ignite.springdata.repository.config.RepositoryConfig; import org.springframework.stereotype.Repository; import poc.ignite.domain.Person; @RepositoryConfig(cacheName = "person-cache") @Repository public interface PersonRepository extends IgniteRepository<Person, Integer> { }
package com.example.rockroku.somkiatbankmobilebanking; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import com.example.rockroku.somkiatbankmobilebanking.common.BaseActivity; public class TransferActivity extends BaseActivity implements View.OnClickListener { private Button mBtTransfer; private Spinner mSpinnerAccountName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transfer); bindView(); setViewListener(); //initAccountNameSpiner(); } private void bindView() { mBtTransfer = (Button) findViewById(R.id.bt_transfer_transfer_activity); // Spinner spinner = (Spinner) findViewById(R.id.spinner_account_name); } private void setViewListener() { mBtTransfer.setOnClickListener(this); } private void initAccountNameSpiner() { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.account_name_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner mSpinnerAccountName.setAdapter(adapter); } @Override public void onClick(View view) { if (view == mBtTransfer) { // open confirm page openActivity(ConfirmActivity.class); } } }
/** * AboutPanel.java * * Skarpetis Dimitris 2016, all rights reserved. */ package dskarpetis.elibrary.ui.about; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Panel; import dskarpetis.elibrary.ui.authentication.LoginPage; /** * Class that defines AboutPanel * * @author dskarpetis */ public class AboutPanel extends Panel { private static final long serialVersionUID = 1L; /** * @param id */ public AboutPanel(String id) { super(id); add(new Label( "about-text", "The target of this thesis is the structure, philosophy and functions that related to the web framework Apache Wicket, to be known by the reader. " + "In the first chapter there is an attempt of a brief presentation of the most popular web frameworks on the Market. " + "In the next two chapters there is an extensive analysis of the architecture and features of Apache Wicket, through " + "short and simple code examples used in the construction of the electronic library application. Then reference is made to " + "other technologies used in the implementation of the application, such as Hibernate, BootStrap and postgreSQL. In the last chapter, " + "all the functions of the Web framework that can be realized from the registered users and the administrator are presented.")); Link<Void> home = new Link<Void>("home") { private static final long serialVersionUID = 1L; @Override public void onClick() { setResponsePage(LoginPage.class); } }; queue(home); } }
package com.eres.waiter.waiter.viewpager.model; import android.arch.lifecycle.LiveData; import android.content.Context; import com.eres.waiter.waiter.app.App; import java.util.ArrayList; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; public class HallLiveData extends LiveData<ArrayList<Hall>> { public Disposable disposable; private Context context; private static HallLiveData instance; public static HallLiveData getInstance(Context context){ if (instance==null){ instance = new HallLiveData(context.getApplicationContext()); } return instance; } private HallLiveData(Context context) { this.context = context; } private void getData() { // disposable = // App.getApp().getAllTables() // .subscribe(new Consumer<ArrayList<Hall>>() { // @Override // public void accept(ArrayList<Hall> _halls) throws Exception { // // setValue(_halls); // } // }); } @Override protected void onActive() { getData(); } @Override protected void onInactive() { if(disposable!=null) disposable.dispose(); } }
package lesson29.Ex2; public class Truck extends Automobile { private float tonnage; //trọng tải private String uses; //mục đích sử dụng private String shippedGoods; //số hàng hóa đã vận chuyển public Truck(float tonnage, String uses, String shippedGoods) { this.tonnage = tonnage; this.uses = uses; this.shippedGoods = shippedGoods; } public Truck(int numberOfWheel, String typeOfEngine, String name, String color, Owner owner, float tonnage, String uses, String shippedGoods) { super(numberOfWheel, typeOfEngine, name, color, owner); this.tonnage = tonnage; this.uses = uses; this.shippedGoods = shippedGoods; } public final float getTonnage() { return tonnage; } public final void setTonnage(float tonnage) { this.tonnage = tonnage; } public final String getUses() { return uses; } public final void setUses(String uses) { this.uses = uses; } public final String getShippedGoods() { return shippedGoods; } public final void setShippedGoods(String shippedGoods) { this.shippedGoods = shippedGoods; } }
package com.example.administrator.localmusicplayerdemo.service; import android.content.Intent; import android.media.session.MediaSession; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaBrowserServiceCompat; import android.support.v4.media.session.MediaSessionCompat; import com.example.administrator.localmusicplayerdemo.Actions; import java.util.List; import model.Song; /** * Created by Administrator on 2018-01-23. */ public class MusicService extends MediaBrowserServiceCompat { private PlaybackManager playbackManager; private MediaSessionCompat mediaSession; private int currentTime; private int duration; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == 1) { if(playbackManager != null) { currentTime = playbackManager.getPosition(); duration = playbackManager.getDuration(); Intent intent = new Intent(); intent.setAction("CURRENT_TIME"); intent.putExtra("currentTime", currentTime); intent.putExtra("duration",duration); sendBroadcast(intent); int remainingMillis = 1000 - currentTime % 1000; int delayMillis = Math.max(remainingMillis,20); handler.sendEmptyMessageDelayed(1, delayMillis); } } } }; @Override public void onCreate() { super.onCreate(); playbackManager = new PlaybackManager(this); setupMediaSession(); handler.sendEmptyMessage(1); } private void setupMediaSession() { // ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class); if (mediaSession != null) { mediaSession = new MediaSessionCompat(this, "MusicService"); mediaSession.setCallback(playbackManager.getCallBack()); mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS); setSessionToken(mediaSession.getSessionToken()); mediaSession.setActive(true); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { String action = intent.getAction(); switch (action){ case Actions.action_play_song: if (intent.hasExtra("songs")){ List<Song> songs = intent.getParcelableArrayListExtra("songs"); int index = intent.getIntExtra("index",-1); intent.removeExtra("songs"); intent.removeExtra("index"); playbackManager.playSongs(songs,index); } break; case Actions.action_seek: if (intent.hasExtra("progress")){ int progress = intent.getIntExtra("progress",0); playbackManager.seekTo(progress); intent.removeExtra("progress"); } } return START_NOT_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Nullable @Override public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) { return new BrowserRoot("root", null); } @Override public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) { } @Override public void onDestroy() { super.onDestroy(); } public boolean isPlaying() { return playbackManager.isPlaying(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.ntp; /** * Common NtpUtils Helper class. */ public final class NtpUtils { /** * Returns 32-bit integer address to IPv4 address string "%d.%d.%d.%d" format. * * @param address the 32-bit address * @return the raw IP address in a string format. */ public static String getHostAddress(final int address) { return ((address >>> 24) & 0xFF) + "." + ((address >>> 16) & 0xFF) + "." + ((address >>> 8) & 0xFF) + "." + ((address >>> 0) & 0xFF); } /** * Return human-readable name of message mode type (RFC 1305). * * @param mode the mode type * @return mode name */ public static String getModeName(final int mode) { switch (mode) { case NtpV3Packet.MODE_RESERVED: return "Reserved"; case NtpV3Packet.MODE_SYMMETRIC_ACTIVE: return "Symmetric Active"; case NtpV3Packet.MODE_SYMMETRIC_PASSIVE: return "Symmetric Passive"; case NtpV3Packet.MODE_CLIENT: return "Client"; case NtpV3Packet.MODE_SERVER: return "Server"; case NtpV3Packet.MODE_BROADCAST: return "Broadcast"; case NtpV3Packet.MODE_CONTROL_MESSAGE: return "Control"; case NtpV3Packet.MODE_PRIVATE: return "Private"; default: return "Unknown"; } } /** * Returns NTP packet reference identifier as IP address. * * @param packet NTP packet * @return the packet reference id (as IP address) in "%d.%d.%d.%d" format. */ public static String getRefAddress(final NtpV3Packet packet) { final int address = (packet == null) ? 0 : packet.getReferenceId(); return getHostAddress(address); } /** * Get refId as reference clock string (e.g. GPS, WWV, LCL). If string is invalid (non-ASCII character) then returns empty string "". For details refer to * the <A HREF="http://www.eecis.udel.edu/~mills/ntp/html/refclock.html#list">Comprehensive List of Clock Drivers</A>. * * @param message the message to check * @return reference clock string if primary NTP server */ public static String getReferenceClock(final NtpV3Packet message) { if (message == null) { return ""; } final int refId = message.getReferenceId(); if (refId == 0) { return ""; } final StringBuilder buf = new StringBuilder(4); // start at highest-order byte (0x4c434c00 -> LCL) for (int shiftBits = 24; shiftBits >= 0; shiftBits -= 8) { final char c = (char) ((refId >>> shiftBits) & 0xff); if (c == 0) { // 0-terminated ASCII string break; } if (!Character.isLetterOrDigit(c)) { return ""; } buf.append(c); } return buf.toString(); } }
public interface RunnerDAO extends RunnerReader, RunnerWriter, RunnerConstants { // all methods from the RunnerReader and RunnerWriter interfaces // all static constants from the RunnerConstants interface }
package disc; import java.util.HashMap; import java.util.Map; import util.HttpUtil; public class ContextualElement { private String entityId = null; private String dataType = null; private Standard standard = null; private String attr = null; private String result = null; public ContextualElement(String entityId, String dataType, Standard standard) { this.entityId = entityId; this.dataType = dataType; this.standard = standard; } public ContextualElement(String entityId, String attr){ this.entityId = entityId; this.attr = attr; } public void requestRawResult(){ Map<String, String> params = new HashMap<String, String>(); params.put("id", entityId); params.put("data_type", dataType); params.put("standard", standard.toJSON()); this.result = HttpUtil.getResponseFromGET("http", "localhost:9000", "entityrawcontext", params); } public void requestResult(){ Map<String, String> params = new HashMap<String, String>(); params.put("id", entityId); params.put("attr", attr); this.result = HttpUtil.getResponseFromGET("http", "localhost:9000", "entitycontext", params); } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public Standard getStandard() { return standard; } public void setStandard(Standard standard) { this.standard = standard; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
package com.codegym.controller; import com.codegym.model.Blog; import com.codegym.service.BlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class BlogController { @Autowired BlogService blogService; @GetMapping("/") public String index(Model model) { model.addAttribute("blogs", blogService.findAll()); return "index"; } @GetMapping("/blog/create") public String create(Model model) { model.addAttribute("blog", new Blog()); return "create"; } @PostMapping("/blog/save") public String save(Blog blog, RedirectAttributes redirect) { blogService.save(blog); redirect.addFlashAttribute("success", "Saved blog successfully!"); return "redirect:/"; } @GetMapping("/blog/edit/{id}") public String edit(@PathVariable int id, Model model) { model.addAttribute("blog", blogService.findById(id)); return "edit"; } @PostMapping("/blog/update") public String update(Blog blog, RedirectAttributes redirect) { blogService.save(blog); redirect.addFlashAttribute("success", "Modified blog successfully!"); return "redirect:/"; } @GetMapping("/blog/delete/{id}") public String delete(@PathVariable int id, Model model) { model.addAttribute("blog", blogService.findById(id)); return "delete"; } @PostMapping("/blog/delete") public String delete(Blog blog, RedirectAttributes redirect) { blogService.remove(blog.getId()); redirect.addFlashAttribute("success", "Removed blog successfully!"); return "redirect:/"; } @GetMapping("/blog/view/{id}") public String view(@PathVariable int id, Model model) { model.addAttribute("blog", blogService.findById(id)); return "view"; } }
package com.smxknife.java2.thread.executorservice.demo09; import java.util.concurrent.*; /** * @author smxknife * 2021/5/19 */ public class _Demo09 { public static void main(String[] args) throws InterruptedException { /** * ArrayBlockingQueue 只能有届 * 此时 * - core:2 * - max:4 * - timeout: * - queue:2 * ----------------- * - 1。当线程数未达到core时,池中2个线程,一直存在,来线程就会直接运行 * - 2。当超过core时,还没有达到max,(这时候会卡,估计在创建线程),最大容忍4个线程同时运行 * - 3。当超过max,线程就会进入queue,而queue只有2个空间,所以只能接收两个,等待池中线程执行结束,再执行 * - 4。池中最大能容纳的线程数:max+queue。size = 4+2=6,所以,当存在6个时,其他的再进来就跟拒绝策略相关来 * - 5。当max生效时,那么timeout肯定也会生效 */ //core2Max4T10ArrayQueue2(); /** * LinkedBlockingQueue 带容量,这与ArrayQueue一样了 */ //core2Max4T10LinkedQueue2(); /** * LinkedBlockingQueue不带容量(隐含Integer.MAX_VALUE) * 此时 * - max失效,顺带着timeout也失效,只有core * - 超过core后进入queue * - 只要没有达到Integer.MAX_VALUE,永不会拒绝 */ // core2Max4T10LinkedQueue(); /** * SyncQueue 不带容量,所以最大只能是是max * 超过max就执行拒绝策略 */ core2Max4T10SyncQueue(); } private static void core2Max4T10SyncQueue() throws InterruptedException { final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.AbortPolicy()); Object lock = new Object(); for (int i = 0; i < 10; i++) { synchronized (lock) { int j = i; executor.execute(() -> { System.out.println("th_" + j + " | " + executor.getActiveCount() + " | " + executor.getTaskCount() + " | " + executor.getPoolSize() + " | " + executor.getQueue().size()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } TimeUnit.SECONDS.sleep(20); System.out.println(executor.getActiveCount()); } private static void core2Max4T10LinkedQueue() throws InterruptedException { final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy()); Object lock = new Object(); for (int i = 0; i < 10; i++) { synchronized (lock) { int j = i; executor.execute(() -> { System.out.println("th_" + j + " | " + executor.getActiveCount() + " | " + executor.getTaskCount() + " | " + executor.getPoolSize() + " | " + executor.getQueue().size()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } TimeUnit.SECONDS.sleep(20); System.out.println(executor.getActiveCount()); } private static void core2Max4T10LinkedQueue2() throws InterruptedException { final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2), new ThreadPoolExecutor.AbortPolicy()); Object lock = new Object(); for (int i = 0; i < 10; i++) { synchronized (lock) { int j = i; executor.execute(() -> { System.out.println("th_" + j + " | " + executor.getActiveCount() + " | " + executor.getTaskCount() + " | " + executor.getPoolSize() + " | " + executor.getQueue().size()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } TimeUnit.SECONDS.sleep(20); System.out.println(executor.getActiveCount()); } private static void core2Max4T10ArrayQueue2() throws InterruptedException { final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(2), new ThreadPoolExecutor.AbortPolicy()); Object lock = new Object(); for (int i = 0; i < 10; i++) { synchronized (lock) { int j = i; executor.execute(() -> { System.out.println("th_" + j + " | " + executor.getActiveCount() + " | " + executor.getTaskCount() + " | " + executor.getPoolSize() + " | " + executor.getQueue().size()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } TimeUnit.SECONDS.sleep(20); System.out.println(executor.getActiveCount()); } }
package com.eberlebill; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; public class PercolationSlow { private boolean[][] grid; private int openSiteCount; private static int N; /** * create N-by-N grid, with all sites blocked * * @param n */ public PercolationSlow(int n) { N = n; grid = new boolean[n][n]; openSiteCount = 0; // all values closed by default for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { grid[i][j] = false; } } } public int runPercolation() { // open sites randomly until grid percolates while (!percolates() && openSiteCount < (N*N)) { // pick spot at random int indexI = randInt(0,N-1); int indexJ = randInt(0,N-1); // if closed, open it if (! isOpen(indexI,indexJ) ) { open(indexI,indexJ); openSiteCount++; } } return openSiteCount; } public static int randInt(int min, int max) { Random rand = new Random(); int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } /** * open site (row i, column j) if it is not open already * * @param i * @param j */ public void open(int i, int j) { // TODO: Throw a java.lang.IndexOutOfBoundsException if any argument to open(), isOpen(), or isFull() is outside its prescribed range. grid[i][j] = true; } /** * is site (row i, column j) open? * * @param i * @param j * @return */ public boolean isOpen(int i, int j) { // TODO: Throw a java.lang.IndexOutOfBoundsException if any argument to open(), isOpen(), or isFull() is outside its prescribed range. return grid[i][j]; } /** * is site (row i, column j) full (can be connected to the top)? * * @param i * @param j * @return */ public boolean isFull(int i, int j) { // TODO: Throw a java.lang.IndexOutOfBoundsException if any argument to open(), isOpen(), or isFull() is outside its prescribed range. if (! isOpen(i, j)) return false; if (i == 0) return true; // find all connected sites for this site ArrayList<SiteCoordinates> connectedSites = getConnected(i, j); while (! connectedSites.isEmpty() ) { connectedSites = getConnected(connectedSites); for (SiteCoordinates siteIndex : connectedSites) { if (siteIndex.getIndexI() == 0) { return true; } } } return false; } /** * Find all the sites that are * 1. open * 2. not visited before in this search * * @param findConnected * @return */ public ArrayList<SiteCoordinates> getConnected(List<SiteCoordinates> findConnected) { ArrayList<SiteCoordinates> connectedSites = new ArrayList<SiteCoordinates>(); for (SiteCoordinates siteIndex: findConnected) { connectedSites.addAll( getConnected( siteIndex.getIndexI(), siteIndex.getIndexJ(), siteIndex.getVisitedSites() )); } return connectedSites; } /** * Is there an adjacent site that's open? * * @param i * @param j * @return */ public ArrayList<SiteCoordinates> getConnected(int i, int j) { ArrayList<SiteCoordinates> list = new ArrayList<SiteCoordinates>(); if (i > 0) { if (isOpen(i-1, j)) { list.add(new SiteCoordinates(i-1, j, new SiteCoordinates(i, j))); } } if (j > 0) { if (isOpen(i, j-1)) { list.add(new SiteCoordinates(i, j-1, new SiteCoordinates(i, j))); } } if (i < grid.length - 1) { if (isOpen(i+1, j)) { int k = i+1; // System.out.println("Adding "+ k + ", "+j); list.add(new SiteCoordinates(i+1, j, new SiteCoordinates(i, j))); } } if (j < grid.length - 1) { if (isOpen(i, j+1)) { list.add(new SiteCoordinates(i, j+1, new SiteCoordinates(i, j))); } } return list; } public ArrayList<SiteCoordinates> getConnected(int i, int j, ArrayList<SiteCoordinates> visitedSites) { ArrayList<SiteCoordinates> connectedIndexes = getConnected(i, j); ArrayList<SiteCoordinates> scrubbedConnectedIndexes = new ArrayList<SiteCoordinates>(); boolean addToList = true; for (SiteCoordinates siteIndex : connectedIndexes) { addToList = true; for (SiteCoordinates visitedSite : visitedSites) { if ( siteIndex.getIndexI() == visitedSite.getIndexI() && siteIndex.getIndexJ() == visitedSite.getIndexJ() ) { addToList = false; break; } } if (addToList) { // add to list of adjacent sites and add this site to visited list visitedSites.add(new SiteCoordinates(i,j)); siteIndex.addVisitedSites(visitedSites); scrubbedConnectedIndexes.add(siteIndex); } } return scrubbedConnectedIndexes; } /** * does the system percolate? * * @return */ public boolean percolates() { // if any site in the top row is full then we're percolating for (int j = 0; j < grid.length; j++) { if (isFull(grid.length-1, j)) return true; } return false; } /** * Getters and setters * */ public boolean[][] getGrid() { return grid; } public void setGrid(boolean[][] grid) { this.grid = grid; } public int getOpenSiteCount() { return openSiteCount; } public void setOpenSiteCount(int openSiteCount) { this.openSiteCount = openSiteCount; } public static int getN() { return N; } public static void setN(int n) { N = n; } private void printGrid() { System.out.println(Arrays.deepToString(grid)); } } class SiteCoordinates { private int indexI; private int indexJ; private ArrayList<SiteCoordinates> visitedSites = new ArrayList<SiteCoordinates>(); SiteCoordinates(int i, int j) { setIndexI(i); setIndexJ(j); } SiteCoordinates(int i, int j, SiteCoordinates referringSite) { setIndexI(i); setIndexJ(j); visitedSites.add(referringSite); } void setIndexI(int i) { indexI = i; } void setIndexJ(int j) { indexJ = j; } public int getIndexI() { return indexI; } public int getIndexJ() { return indexJ; } public ArrayList<SiteCoordinates> getVisitedSites() { return visitedSites; } public void addVisitedSite(SiteCoordinates visitedSite) { visitedSites.add(visitedSite); } public void addVisitedSites(ArrayList<SiteCoordinates> visitedSites) { this.visitedSites.addAll(visitedSites); } }
package com.wipro.atm.webdriver.pages; import com.wipro.atm.webdriver.model.User; import com.wipro.atm.webdriver.utils.BaseUtility; import com.wipro.atm.webdriver.utils.WaitForElements; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class OpenCartSignInPage extends AbstractPage { Logger logger = LogManager.getRootLogger(); @FindBy(xpath = "//a[text()='login']") private WebElement lnkLogin; @FindBy(xpath = "//input[@name='email']") private WebElement txtLoginEmail; @FindBy(xpath = "//input[@name='password']") private WebElement txtLoginPassword; @FindBy(xpath = "//input[@type='submit']") private WebElement btnLogin; @FindBy(xpath = "//h1[contains(text(),'My Account')]") private WebElement lblYourAccount; public OpenCartSignInPage(WebDriver driver) { super(driver); } /** * below method is to login to the open cart application * @param user - email and password * @return - driver */ public OpenCartSignInPage loginToOpenCart(User user){ WaitForElements.waitForElementClickable(driver, 10, lnkLogin); lnkLogin.click(); WaitForElements.waitForElementClickable(driver, 10, txtLoginEmail); txtLoginEmail.sendKeys(user.getEmail()); logger.info("Email " + user.getEmail() + " has been entered in email field"); txtLoginPassword.sendKeys(user.getPassword()); logger.info("Password has been entered"); btnLogin.click(); WaitForElements.waitForElementToBeVisible(driver, 30, lblYourAccount); return new OpenCartSignInPage(driver); } public boolean isElementDisplayed() { return BaseUtility.isElementDisplayed(lblYourAccount); } }
/* 内部类定义在局部时: 1.不可以被成员修饰符修饰 2.可以直接访问外部类中的成员,因为还持有外部类中的引用,但是不可以访问它所在的局部中的变量, 只能访问被final修饰的局部变量。 */ class Outer{ int x = 3; void method(int a){ // 现在这么写不报错,之前版本得写成 final int a | a是局部变量,进栈内存,函数结束就释放了 int y = 4; //之前版本这样的话会报错(从内部类中访问局部变量y;需要被声明为最终类型),但是现在版本好像不报错了 // final int y = 4; // new Inner().function(); 不能放到这个位置,因为new的时候jvm还没读到 class Inner... // 局部的内部类,不能定义静态成员的,静态修饰符无法修饰局部成员 // 局部内部类都是非静态的,所以都得通过对象访问 class Inner{ void function(){ System.out.println("this is outer's x:" + Outer.this.x); System.out.println(y); System.out.println(a); } } new Inner().function(); } } class InnerClass2{ public static void main(String[] args){ new Outer().method(7); } }
package com.puhuilink.orderpay_detect; import com.puhuilink.orderpay_detect.beans.OrderEvent; import com.puhuilink.orderpay_detect.beans.OrderResult; import org.apache.commons.math3.distribution.AbstractMultivariateRealDistribution; import org.apache.flink.cep.CEP; import org.apache.flink.cep.PatternSelectFunction; import org.apache.flink.cep.PatternStream; import org.apache.flink.cep.PatternTimeoutFunction; import org.apache.flink.cep.pattern.Pattern; import org.apache.flink.cep.pattern.conditions.SimpleCondition; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.util.OutputTag; import java.util.List; import java.util.Map; /** * @author :yjj * @date :Created in 2021/7/14 18:05 * @description: * @modified By: * @version: $ */ public class OrderPayTimeOut { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); env.setParallelism(1); SingleOutputStreamOperator<OrderEvent> dataStream = env.readTextFile("C:\\Users\\无敌大大帅逼\\IdeaProjects\\UserBehaviorAnalysis\\OrderPayDelect\\src\\main\\resources\\OrderLog.csv") .map(data -> { String[] split = data.split(","); return new OrderEvent(Long.parseLong(split[0]), split[1], split[2], Long.parseLong(split[3])); }).assignTimestampsAndWatermarks( new AscendingTimestampExtractor<OrderEvent>() { @Override public long extractAscendingTimestamp(OrderEvent element) { return element.getTimestamp() * 1000; } } ); Pattern<OrderEvent, OrderEvent> orderPayPattern = Pattern.<OrderEvent>begin("create").where(new SimpleCondition<OrderEvent>() { @Override public boolean filter(OrderEvent orderEvent) throws Exception { return "create".equals(orderEvent.getEventType()); } }).followedBy("pay").where(new SimpleCondition<OrderEvent>() { @Override public boolean filter(OrderEvent orderEvent) throws Exception { return "pay".equals(orderEvent.getEventType()); } }).within(Time.minutes(15)); //2.定义侧输出流标签,用来表示超时事件 OutputTag<OrderResult> orderTimeoutputTag = new OutputTag<OrderResult>("order-timeout"){}; //3.将pattern应用到数据流上,得到pattern stream PatternStream<OrderEvent> pattern = CEP.pattern(dataStream.keyBy(OrderEvent::getOrderId), orderPayPattern); //4.调用select方法,实现对匹配复杂事件和超时复杂事件的提取和处理 SingleOutputStreamOperator<OrderResult> select = pattern.select(orderTimeoutputTag, new OrderTimeoutSelect(), new OrderPaySelect()); select.print(); select.getSideOutput(orderTimeoutputTag).print(); env.execute(); } private static class OrderTimeoutSelect implements PatternTimeoutFunction<OrderEvent,OrderResult> { @Override public OrderResult timeout(Map<String, List<OrderEvent>> map, long l) throws Exception { Long timeoutOrder = map.get("create").iterator().next().getOrderId(); return new OrderResult(timeoutOrder,"timeout " + l); } } private static class OrderPaySelect implements PatternSelectFunction<OrderEvent,OrderResult> { @Override public OrderResult select(Map<String, List<OrderEvent>> map) throws Exception { Long timeoutOrder = map.get("pay").iterator().next().getOrderId(); return new OrderResult(timeoutOrder," pay "); } } }
package fr.pederobien.uhc.commands.configuration.edit.editions; import fr.pederobien.uhc.commands.configuration.edit.EditBaseConfiguration; import fr.pederobien.uhc.commands.configuration.edit.EditBlockedexConfiguration; import fr.pederobien.uhc.commands.configuration.edit.EditHungerGameConfiguration; import fr.pederobien.uhc.commands.configuration.edit.EditSpawnConfiguration; import fr.pederobien.uhc.interfaces.IBase; import fr.pederobien.uhc.interfaces.IBlockedexConfiguration; import fr.pederobien.uhc.interfaces.IConfigurationContext; import fr.pederobien.uhc.interfaces.IEditConfiguration; import fr.pederobien.uhc.interfaces.IHungerGameConfiguration; import fr.pederobien.uhc.interfaces.ISpawn; public class EditConfigurationFactory { private static IEditConfiguration<IBase> editBaseConfiguration; private static IEditConfiguration<ISpawn> editSpawnConfiguration; private static IEditConfiguration<IHungerGameConfiguration> editHungerGameConfiguration; private static IEditConfiguration<IBlockedexConfiguration> editBlockedexConfiguration; public synchronized static IEditConfiguration<IBase> getEditBaseConfiguration() { if (editBaseConfiguration == null) editBaseConfiguration = new EditBaseConfiguration(); return editBaseConfiguration; } public synchronized static IEditConfiguration<ISpawn> getEditSpawnConfiguration() { if (editSpawnConfiguration == null) editSpawnConfiguration = new EditSpawnConfiguration(); return editSpawnConfiguration; } public synchronized static IEditConfiguration<IHungerGameConfiguration> getEditHungerGameConfiguration(IConfigurationContext context) { if (editHungerGameConfiguration == null) editHungerGameConfiguration = new EditHungerGameConfiguration(context); return editHungerGameConfiguration; } public synchronized static IEditConfiguration<IBlockedexConfiguration> getEditBlockedexConfiguration(IConfigurationContext context) { if (editBlockedexConfiguration == null) editBlockedexConfiguration = new EditBlockedexConfiguration(context); return editBlockedexConfiguration; } public static void setAllAvailable(boolean available) { editBaseConfiguration.setAvailable(available); editSpawnConfiguration.setAvailable(available); editHungerGameConfiguration.setAvailable(available); editBlockedexConfiguration.setAvailable(available); } }
package com.itfdms.itfdms_mc_service.handler; import com.alibaba.fastjson.JSONObject; import com.itfdms.common.util.mobile.DingTalkMsgTemplate; import com.itfdms.itfdms_mc_service.config.DingTalkPropertiesConfig; import com.xiaoleilu.hutool.http.HttpUtil; import com.xiaoleilu.hutool.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 发送钉钉消息逻辑 * * @ProjectName: itfdms_blog * @Package: com.itfdms.itfdms_mc_service.handler * @ClassName: DingTalkMessageHandler * @Description: 发送钉钉消息逻辑 * @Author: lxr * @CreateDate: 2018-08-28 20:20 * @UpdateUser: lxr * @UpdateDate: 2018-08-28 20:20 * @UpdateRemark: The modified content * @Version: 1.0 **/ @Slf4j @Component public class DingTalkMessageHandler { @Autowired private DingTalkPropertiesConfig dingTalkPropertiesConfig; /** * 业务处理 * @param text 消息 * @return */ public boolean process(String text){ String webhook = dingTalkPropertiesConfig.getWebhook(); if (StrUtil.isBlank(webhook)){ log.error("钉钉配置错误,webhook为空"); return false; } DingTalkMsgTemplate dingTalkMsgTemplate = new DingTalkMsgTemplate(); dingTalkMsgTemplate.setMsgtype("text"); DingTalkMsgTemplate.TextBean textBean = new DingTalkMsgTemplate.TextBean(); textBean.setContent(text); dingTalkMsgTemplate.setText(textBean); String result = HttpUtil.post(webhook, JSONObject.toJSONString(dingTalkMsgTemplate)); log.info("钉钉提醒成功,报文响应:{}", result); return true; } }
package com.accp.pub.mapper; import com.accp.pub.pojo.Dareportforms; public interface DareportformsMapper { int deleteByPrimaryKey(Integer darfid); int insert(Dareportforms record); int insertSelective(Dareportforms record); Dareportforms selectByPrimaryKey(Integer darfid); int updateByPrimaryKeySelective(Dareportforms record); int updateByPrimaryKey(Dareportforms record); }