text
stringlengths
10
2.72M
// https://www.youtube.com/watch?v=ymxPZk7TesQ class Solution { public int countComponents(int n, int[][] edges) { int[] ids = new int[n]; for (int i = 0; i < ids.length; i++) ids[i] = i; for (int[] edge: edges) union(edge[0], edge[1], ids); Set<Integer> set = new HashSet<>(); for (int i = 0; i < ids.length; i++) set.add(find(i, ids)); return set.size(); } private void union(int edge1, int edge2, int[] ids) { int parent1 = find(edge1, ids); int parent2 = find(edge2, ids); ids[parent1] = parent2; } private int find(int edge, int[] ids) { if (ids[edge] != edge) ids[edge] = find(ids[edge], ids); return ids[edge]; } }
package com.ahuo.personapp.core.net; import android.content.Context; import com.ahuo.personapp.core.config.AppConfig; import com.ahuo.tools.network.retrofit.KKNetWorkRequest; /** * Created on 17-5-10 * * @author liuhuijie */ public class ApiManager { private ApiService mApiService; private ApiManager() { } private static ApiManager sApiManager; public static ApiManager getInstance() { if (sApiManager == null) { sApiManager = new ApiManager(); } return sApiManager; } public void init(Context context) { KKNetWorkRequest.getInstance().init(context, AppConfig.API_HOST); mApiService = KKNetWorkRequest.getInstance().create(ApiService.class); } public ApiService getApiService() { return mApiService; } }
package ru.malichenko.market.ws; import lombok.RequiredArgsConstructor; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import ru.malichenko.market.services.ProductService; import ru.malichenko.market.ws.products.GetAllProductsResponse; import ru.malichenko.market.ws.products.GetProductByTitleRequest; import ru.malichenko.market.ws.products.GetProductByTitleResponse; @Endpoint @RequiredArgsConstructor public class ProductEndpoint { private static final String NAMESPACE_URI = "http://www.malichenko.ru/market/ws/products"; private final ProductService productService; @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getProductByTitleRequest") @ResponsePayload public GetProductByTitleResponse getProductByTitleRequest(@RequestPayload GetProductByTitleRequest request) { GetProductByTitleResponse response = new GetProductByTitleResponse(); response.setProduct(productService.getSOAPProductByTitle(request.getTitle())); return response; } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getAllProductsRequest") @ResponsePayload public GetAllProductsResponse getAllProductsRequest() { GetAllProductsResponse response = new GetAllProductsResponse(); productService.getAllSOAPProducts().forEach(response.getAllProduct()::add); return response; } }
package service; import domain.Subject; import repository.SubjectInterface; import repository.SubjectRepository; /** * Created by rodrique on 8/14/2017. */ public class SubjectServImpl implements SubjectService { private static SubjectServImpl service = null; SubjectInterface repository = SubjectRepository.getInstance(); public static SubjectServImpl getInstance() { if(service == null) service = new SubjectServImpl(); return service; } public Subject create(Subject subject) { return repository.create(subject);} public Subject read(String subjectName) {return repository.read(subjectName);} public Subject update(Subject subject) {return repository.update(subject);} public void delete(String subjectName) {repository.delete(subjectName);} }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.common.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.objectweb.proactive.core.config.PAProperties; import org.objectweb.proactive.core.config.PAProperty; /** * PropertiesDumper * * @author The ProActive Team */ public class PropertiesDumper { static String[] excludePropertiesArray = new String[] { "java.rmi.server.codebase", "java.rmi.server.codebase", "proactive.http.port" }; static HashSet<String> excludeProperties = new HashSet<String>(); static { for (String p : excludePropertiesArray) { excludeProperties.add(p); } } public static void dumpProperties(File file) throws IOException { if (file.exists()) { if (!file.canWrite()) { throw new IllegalArgumentException("File " + file + " exists and is write-protected."); } file.delete(); } Element root = new Element("ProActiveUserProperties"); Document document = new Document(root); Element props = new Element("properties"); root.addContent(props); Map<Class<?>, List<PAProperty>> allProperties = PAProperties.getAllProperties(); for (Class<?> cl : allProperties.keySet()) { for (PAProperty prop : allProperties.get(cl)) { if ((prop.getValueAsString() != null) && (!excludeProperties.contains(prop.getName()))) { Element propel = new Element("prop"); Attribute key = new Attribute("key", prop.getName()); Attribute value = new Attribute("value", prop.getValueAsString()); propel.setAttribute(key); propel.setAttribute(value); props.addContent(propel); } } } XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(document, new FileOutputStream(file)); file.deleteOnExit(); } }
package gestionEleves; public class Eleve1A extends EleveECTS{ public Eleve1A(String nom) { super(nom); } @Override public int resultat() { if (this.getMoyenne() >= 12) { return 60; } else { return 0; } } }
package com.utils; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.How; import com.configs.Configs; import io.github.bonigarcia.wdm.ChromeDriverManager; public class Support { public static WebDriver driver; public void launch() { switch(Configs.browser.toLowerCase()) { case "chrome": ChromeDriverManager.getInstance().version("2.35").setup(); driver = new ChromeDriver(); break; } } public void tearDown() { driver.quit(); } public void openPage(String url) { driver.manage().window().maximize(); driver.get(url); } public WebElement getElement(How how, String locator) throws Exception { Thread.sleep(5000); switch (how){ case CLASS_NAME: return driver.findElement(By.className(locator)); case CSS: return driver.findElement(By.cssSelector(locator)); case ID: return driver.findElement(By.id(locator)); case ID_OR_NAME: return driver.findElement(By.id(locator)); case LINK_TEXT: return driver.findElement(By.linkText(locator)); case NAME: return driver.findElement(By.name(locator)); case PARTIAL_LINK_TEXT: return driver.findElement(By.partialLinkText(locator)); case TAG_NAME: return driver.findElement(By.tagName(locator)); case XPATH: return driver.findElement(By.xpath(locator)); case UNSET: break; } return null; } public void fillText(WebElement e, String text) { e.sendKeys(text); } public void click(WebElement e) { e.click(); } public void keyEvent(WebElement e, String key) { switch(key.toLowerCase()) { case "enter": e.sendKeys(Keys.ENTER); break; } } }
package com.julysky; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import com.julysky.autoConfiguration.EnableServiceRegistry; import com.julysky.domain.User; import com.julysky.repository.UserRepository; @EnableServiceRegistry @SpringBootApplication public class LittleRpcServerApplication { private static Logger logger = LoggerFactory.getLogger(LittleRpcServerApplication.class); public static void main(String[] args) { SpringApplication.run(LittleRpcServerApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(UserRepository userRepository) throws Exception { return args -> { prepareData(userRepository); }; } public void prepareData(UserRepository userRepository) { User julysky = new User("julysky", 24); userRepository.save(julysky); } }
package communication; public class InvalidUserNameException extends Exception { public InvalidUserNameException(){ super(); } }
package com.davivienda.sara.constantes; /** * FormatoDiarioElectronico * * Enumeración de los tipos de formato Diario electrónico * @author jjvargas */ public enum FormatoDiarioElectronico { EDC(0, "EDC"); public Integer codigo; public String nombre; FormatoDiarioElectronico(Integer codigo, String nombre) { this.codigo = codigo; this.nombre = nombre; } public static FormatoDiarioElectronico getFormatoDiarioElectronico(Integer codigo) { FormatoDiarioElectronico formatoDiarioElectronico = FormatoDiarioElectronico.EDC; for (FormatoDiarioElectronico item : FormatoDiarioElectronico.values()) { if (item.codigo.equals(codigo)) { formatoDiarioElectronico = item; break; } } return formatoDiarioElectronico; } public static FormatoDiarioElectronico getFormatoDiarioElectronico(String nombre) { FormatoDiarioElectronico formatoDiarioElectronico = FormatoDiarioElectronico.EDC; for (FormatoDiarioElectronico item : FormatoDiarioElectronico.values()) { if (item.nombre.equals(nombre)) { formatoDiarioElectronico = item; break; } } return formatoDiarioElectronico; } @Override public String toString() { return this.nombre; } }
package hdfcraft; public interface ProgressReceiver { /** * Set the progress as a value from 0.0f to 1.0f (inclusive). * * @param progress The progress to report. * @throws org.pepsoft.util.ProgressReceiver.OperationCancelled If the * operation has been canceled, for instance by the user, or because * of an exception on another thread. */ void setProgress(float progress) throws OperationCancelled; /** * Report that the operation has been aborted due to an exception having * been thrown. Any other threads working on the same operation will be * canceled. * * @param exception The exception which has been thrown. */ void exceptionThrown(Throwable exception); /** * Report that the operation has succeeded successfully. */ void done(); /** * Change the message describing the current operation. * * @param message A message describing the current operation. * @throws org.pepsoft.util.ProgressReceiver.OperationCancelled If the * operation has been canceled, for instance by the user, or because * of an exception on another thread. */ void setMessage(String message) throws OperationCancelled; /** * Check whether the operation has been canceled. An * <code>OperationCancelled</code> exception will be thrown if it has. * * @throws org.pepsoft.util.ProgressReceiver.OperationCancelled If the * operation has been canceled, for instance by the user, or because * of an exception on another thread. */ void checkForCancellation() throws OperationCancelled; /** * Restart the progress bar. All progress will be wiped out and the next * expected progress report will be expected to be as if progress started * from 0.0f again. * * @throws org.pepsoft.util.ProgressReceiver.OperationCancelled If the * operation has been canceled, for instance by the user, or because * of an exception on another thread. */ void reset() throws OperationCancelled; public static class OperationCancelled extends Exception { public OperationCancelled(String message) { super(message); } private static final long serialVersionUID = 1L; } }
package com.esum.framework.common.poller; public interface PollerListener { public void onListenCompleted(FileEvent fileEvent); }
/** * COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved. * * @author rbanking */ package com.classroom.services.web.security.tokens; import java.util.Collection; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; /** * Security token * * @author mkol * */ public class RESTAuthenticationToken extends UsernamePasswordAuthenticationToken { /** * */ private static final long serialVersionUID = 1L; /** * The Constructor. * * @param principal * the principal * @param credentials * the credentials */ public RESTAuthenticationToken(Object principal, Object credentials) { super(principal, credentials); } /** * The Constructor. * * @param principal * the principal * @param credentials * the credentials * @param authorities * the authorities */ public RESTAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) { super(principal, credentials, authorities); } }
package com.android_dev.tatenuufrn.activities; import android.content.Context; import android.content.Intent; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android_dev.tatenuufrn.R; import com.android_dev.tatenuufrn.applications.TatenuUFRNApplication; import com.android_dev.tatenuufrn.managers.APIManager; import com.android_dev.tatenuufrn.vendor.OAuthTokenRequest; import com.google.api.client.auth.oauth2.Credential; import com.wuman.android.auth.OAuthManager; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class Login extends Activity { private Button loginButton; private String jsonResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); SharedPreferences sharedPreferences = getSharedPreferences(TatenuUFRNApplication.SHARED_PREFERENCES_NAME, MODE_PRIVATE); sharedPreferences.getString("userToken", ""); loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // login("mylogin"); // LOGIN FROM INSIDE THE UFRN sigaa_login(); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data){ Log.d("Result", "reqCode: " + String.valueOf(requestCode) + " resCode: " + String.valueOf(resultCode)); } public void sigaa_login(){ OAuthTokenRequest.getInstance().getTokenCredential(this, "http://apitestes.info.ufrn.br/authz-server", "taten-ufrn-id", "tatenufrn", new OAuthManager.OAuthCallback<Credential>() { @Override public void run(OAuthManager.OAuthFuture<Credential> future) { try { Credential credential = future.getResult(); OAuthTokenRequest.getInstance().setCredentials(credential); if (credential != null) { getUserData(); } } catch (IOException e) { e.printStackTrace(); } // make API queries with credential.getAccessToken() } }); } public void login(String login){ final Context context = this; Intent intent = new Intent(context, ListEvents.class); APIManager.getInstance().login(this, login, intent); } public void getUserData(){ final Context context = this; String urlJsonObj = "http://apitestes.info.ufrn.br/usuario-services/services/usuario/info"; OAuthTokenRequest.getInstance().resourceRequest(this, Request.Method.GET, urlJsonObj, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String nome = jsonObject.getString("nome"); String login = jsonObject.getString("login"); jsonResponse = ""; jsonResponse += "Name: " + nome + "\n\n"; jsonResponse += "Login: " + login + "\n\n"; VolleyLog.d("SAID", "UserData", response); Log.i("USERDATA", response); login(login); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("SAIDA", "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
package ch.xch.androiddemo.utils; import android.content.Context; import android.content.SharedPreferences; /** * Created by XCH on 2014/12/3. */ public class SharedPreferencesUtil { private SharedPreferences sp; private SharedPreferences.Editor editor; public SharedPreferencesUtil(Context context) { sp = context.getSharedPreferences(Constant.TEXT_SETTING, Context.MODE_PRIVATE); editor = sp.edit(); } public int getTheme() { return sp.getInt(Constant.TEXT_THEME, Constant.THEME_DARK); } public void setTheme(int theme) { editor.putInt(Constant.TEXT_THEME, theme); editor.commit(); } }
package com.yourcompany.selenium.yourclientprojectname.BlablaTestSuiteRegistration; import com.yourcompany.selenium.yourclientprojectname.Common.ChromeDriver.Factory.ChromeDriverFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URL; public class LoginTest { private static WebDriver driver; @BeforeClass public static void setup() { driver = ChromeDriverFactory.create(); driver.get("https://blablawriting.com/"); } @Test public void Login() throws Exception { WebElement LoginLink=driver.findElement(By.xpath("/html/body/header/div[1]/div/div[3]/div/nav/a")); LoginLink.click(); WebElement EmailInput=driver.findElement(By.xpath("//*[@id=\"user_login\"]")); EmailInput.sendKeys("marina.hotinetskaya@boosta.co"); WebElement PasswordInput=driver.findElement(By.xpath("//*[@id=\"user_pass\"]")); PasswordInput.sendKeys("123456"); WebElement SignINButton = driver.findElement(By.xpath("//*[@id=\"wp-submit\"]")); SignINButton.click(); WebElement Username=driver.findElement(By.xpath("/html/body/header/div[1]/div/div[3]/div/nav/div/span")); Assert.assertEquals(Username.getText(),"marina.hotinetskaya@boosta.co"); } @AfterTest public static void tearDown() throws Exception { driver.quit(); } }
package com.cn.ouyjs.thread.lock.productAndCustomer; import java.math.BigDecimal; /** * @author ouyjs * @date 2019/8/9 10:38 */ public class Goods { private String name; private Integer number; private BigDecimal price; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", number=" + number + ", price=" + price + '}'; } }
package configuration; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import connection.DBConfiguration; public class GetActive { EncryptandDecrypt ec = new EncryptandDecrypt(); DBConfiguration db = new DBConfiguration(); Connection conn = db.getConnection(); ResultSet rs = null; public String getAcadYear() throws SQLException { Statement stmnt = conn.createStatement(); rs = stmnt.executeQuery("SELECT * FROM `r_academic_year` where Academic_Year_Active_Flag = 'Present' "); int i = 0 ; String yearid = ""; while(rs.next()){ yearid = ec.decrypt(ec.key, ec.initVector, rs.getString("Academic_Year_Description")); } return yearid; } }
package com.myvodafone.android.front.helpers; import android.text.Editable; import android.text.Html; import android.text.style.BulletSpan; import org.xml.sax.XMLReader; public class UlTagHandler implements Html.TagHandler { int openTag; @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { if (tag.equals("ul")) { if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n\n"); } else { output.append("\n"); } } if (tag.equals("li") && opening) { if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } openTag = output.length(); } if (tag.equals("li") && !opening) { if (output.length() > 0 && output.charAt(output.length() - 1) != '\n') { output.append("\n"); } output.setSpan(new BulletSpan(10 * BulletSpan.STANDARD_GAP_WIDTH), openTag, output.length(), 0); } } }
package ariel.manndrops.game.viewmodel.events; public class OnUserAnswered { public String userAnswer; public OnUserAnswered(String userAnswer) { this.userAnswer = userAnswer; } }
/** * */ package com.DB.dao; import java.util.List; import com.DB.model.Role; import com.DB.model.User; import com.DB.model.View; /** * @author Bruce GONG * */ public interface RoleDao { public Role getRole(String username); public List<Role> getAllRoles(); public boolean addMember(Role role, String username); public boolean removeMember(Role role, String username);//should be used with addMember() public List<User> getUsersInRole(Role role); public List<View> getViewsWithRole(Role role); public boolean createRole(String rolename); public boolean updateViews4Role(Role role); public boolean removeViewsOfRole(Role role); public boolean deleteRole(String rolename); }
package net.mv.flatware; public interface Plate { public void holdFood(); public void disintegrate(); }
package com.needii.dashboard.dao; import java.util.List; import com.needii.dashboard.model.Promotion; import com.needii.dashboard.model.search.PromotionSearchCriteria; import com.needii.dashboard.utils.Pagination; public interface PromotionDao { List<Promotion> findAll(PromotionSearchCriteria searchCriteria, Pagination pagination); long count(PromotionSearchCriteria searchCriteria); List<Promotion> findAll(); List<Promotion> findBySupplierId(long supplierId); List<Promotion> findBySupplierId(long supplierId, int status, int limit, int offset); Long countBySupplierId(long supplierId); Promotion findOne(long id); Promotion findOne(String code); void create(Promotion entity); void update(Promotion entity); void delete(Promotion entity); long count(); }
/** * Copyright (C) 2016 Robinhood Markets, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.robinhood.spark; import android.database.DataSetObservable; import android.database.DataSetObserver; /** * A simple adapter class - evenly distributes your points along the x axis, does not * draw a base line, and has support for registering/notifying {@link DataSetObserver}s when * data is changed. */ public abstract class SparkAdapter { private final DataSetObservable observable = new DataSetObservable(); /** * returns the number of points to be drawn */ public abstract int getCount(); /** * returns the object at the given index */ public abstract Object getItem(int index); /** * Gets the float representation of the X value of the point at the given index. */ public float getX(int index) { return index; } /** * Gets the float representation of the Y value of the point at the given index. */ public abstract float getY(int index); /** * Return true if you wish to draw a "baseLine" - a horizontal line across the graph used * to compare the rest of the graph's points against. */ public boolean hasBaseLine() { return false; } /** * Gets the float representation of the Y value of the desired baseLine. */ public float getBaseLine() { return 0; } /** * Notifies the attached observers that the underlying data has been changed and any View * reflecting the data set should refresh itself. */ public final void notifyDataSetChanged() { observable.notifyChanged(); } /** * Notifies the attached observers that the underlying data is no longer valid or available. * Once invoked this adapter is no longer valid and should not report further data set * changes. */ public final void notifyDataSetInvalidated() { observable.notifyInvalidated(); } /** * Register a {@link DataSetObserver} to listen for updates to this adapter's data. * @param observer the observer to register */ public final void registerDataSetObserver(DataSetObserver observer) { observable.registerObserver(observer); } /** * Unregister a {@link DataSetObserver} from updates to this adapter's data. * @param observer the observer to unregister */ public final void unregisterDataSetObserver(DataSetObserver observer) { observable.unregisterObserver(observer); } }
package com.swapp.service; import org.springframework.ui.Model; public interface SwboardService { public abstract void execute(Model model); }
package ilc.db; /** * Created by Administrator on 1/28/2018. */ public class IntentFiltersTables { }
package com.em.controller; import java.io.Serializable; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import com.em.dto.EmployeeDto; import com.em.service.EmployeeServiceInterface; @Controller @SessionAttributes("empDto") public class EmpAdminController { @Autowired EmployeeServiceInterface serviceInterface; // will take to save page @GetMapping("/saveEmpPage") public String saveEmpPage() { return "saveEmp"; } // it will recieve form data @RequestMapping(value = "/saveEmployee", method = RequestMethod.POST) String saveEmployee(@ModelAttribute EmployeeDto employee, BindingResult result, Model model, HttpSession session) { if (result.hasErrors()) { return "saveEmp"; } System.out.println(employee); EmployeeDto empAdmin = (EmployeeDto) session.getAttribute("empDto"); employee.setCompany(empAdmin.getCompany()); employee.setDepartment(empAdmin.getDepartment()); long id = (Long) serviceInterface.saveEmpInDb(employee); if (id > 0) { model.addAttribute("info", "emp created with login id =" + " " + employee.getLoginId() + " with passwrd " + empAdmin.getPassword()); return "saveEmp"; } return "employeeDetails"; } }
package de.hpi.is.idd.datasets; import info.debatty.java.stringsimilarity.JaroWinkler; import info.debatty.java.stringsimilarity.NormalizedLevenshtein; import org.apache.commons.codec.language.DoubleMetaphone; import org.simmetrics.StringDistance; import org.simmetrics.StringMetric; import org.simmetrics.metrics.HammingDistance; import org.simmetrics.metrics.Levenshtein; import org.simmetrics.metrics.MongeElkan; import java.io.Serializable; import java.util.*; public class NCVotersIDDUtility extends de.hpi.is.idd.interfaces.DatasetUtils implements Serializable { protected static final String ID = "id"; protected static final String FIRST_NAME = "first_name"; protected static final String MIDDLE_NAME = "midl_name"; protected static final String LAST_NAME = "last_name"; protected static final String HOUSE_NUM = "house_num"; protected static final String STREET = "street_name"; protected static final String ZIP_CODE = "zip_code"; protected static final String AGE = "age"; protected static final String SEX = "sex_code"; protected static final String BIRTH_PLACE = "birth_place"; protected static final String STATUS = "voter_status_desc"; protected static final String STATUS_REASON = "voter_status_reason_desc"; protected static final String RACE = "race_desc"; protected static final String PARTY = "party_cd"; protected static final String COUNTY = "county_id"; private static final long serialVersionUID = -7726140071035852774L; protected transient JaroWinkler jw = null; protected transient NormalizedLevenshtein nl = null; // sum of distances for all attributes protected double distances; // attributes that are considered for similarity protected int attribute_count; public NCVotersIDDUtility() { datasetThreshold = 0.75; jw = new JaroWinkler(); nl = new NormalizedLevenshtein(); } protected Double treatSpecialCases(Map<String, Object> record1, Map<String, Object> record2) { // same record? if (record1.get(ID) == record2.get(ID)) return 1.0; // return 0 if one is male and the other female if ((record1.get(SEX).equals("M") && record2.get(SEX).equals("F")) || (record1.get(SEX).equals("F") && record2.get(SEX).equals("M"))) return 0.0; // return 0 if birth_place, race or sex don't match String r1 = (String) record1.get(RACE); String r2 = (String) record2.get(RACE); if ((!r1.isEmpty()) && (!r2.isEmpty()) && (!r1.equals(r2)) && (!r1.equals("UNDESIGNATED")) && (!r2.equals("UNDESIGNATED")) && (!r1.equals("OTHER")) && (!r2.equals("OTHER"))) return 0.0; // only one record can be active at a time if (record1.get(STATUS).equals("ACTIVE") && record2.get(STATUS).equals("ACTIVE")) return 0.0; // only one record can be removed because of death if (record1.get(STATUS_REASON).equals("DECEASED") && record2.get(STATUS_REASON).equals("DECEASED")) return 0.0; // deceased person cannot have an active record if ((record1.get(STATUS).equals("ACTIVE") && record2.get(STATUS_REASON).equals("DECEASED")) || (record2.get(STATUS).equals("ACTIVE") && record1.get(STATUS_REASON).equals("DECEASED"))) return 0.0; // age has to be the same if (record1.get(AGE) != record2.get(AGE)) return 0.0; return -1.0; } protected double objectSimilarity(Object o1, Object o2) { return objectSimilarity(o1, o2, ""); } protected double objectSimilarity(Object o1, Object o2, Object def) { if (o1.equals(def) && o2.equals(def)) return 1.0; else if (o1.equals(def) || o2.equals(def)) { attribute_count--; return 0.0; } else { if (o1 instanceof Integer) return 1 - hammingDistance(o1.toString(), o2.toString()); else return 1 - nl.distance(o1.toString(), o2.toString()); } } public Double calculateSimilarity(Map<String, Object> record1, Map<String, Object> record2, Map<String, String> parameters) { Double specialCases = treatSpecialCases(record1, record2); if (specialCases >= 0) return specialCases; if (jw == null) { jw = new JaroWinkler(); } if (nl == null) { nl = new NormalizedLevenshtein(); } distances = 0; attribute_count = 5; distances += objectSimilarity(record1.get(BIRTH_PLACE), record2.get(BIRTH_PLACE)); distances += (record1.get(PARTY).equals(record2.get(PARTY)) ? 1.0 : 0.0); // first name rarely changes by much, so large differences influence negatively distances += (1 - jw.distance((String) record1.get(FIRST_NAME), (String) record2.get(FIRST_NAME))) * 2 - 1; // when marrying, old last name often moves to middle name // if this happens, ignore middle and last name, and only consider the rest if (record1.get(MIDDLE_NAME).equals(record2.get(LAST_NAME)) || record2.get(MIDDLE_NAME).equals(record1.get(LAST_NAME))) attribute_count -= 2; else { // at least two of the three attributes have to have the same DoubleMetaphone-Encoding int dms = 0; DoubleMetaphone dm = new DoubleMetaphone(); if (dm.isDoubleMetaphoneEqual((String) record1.get(FIRST_NAME), (String) record2.get(FIRST_NAME))) dms++; if (dm.isDoubleMetaphoneEqual((String) record1.get(MIDDLE_NAME), (String) record2.get(MIDDLE_NAME))) dms++; if (dm.isDoubleMetaphoneEqual((String) record1.get(LAST_NAME), (String) record2.get(LAST_NAME))) dms++; if (dms < 2) return 0.0; distances += objectSimilarity(record1.get(MIDDLE_NAME), record2.get(MIDDLE_NAME)); distances += objectSimilarity(record1.get(LAST_NAME), record2.get(LAST_NAME)); } // calculate difference of addresses double address_distance = 0.0, street_distance = 0.0; int address_attributes = 3, old_attribute_count = attribute_count; street_distance += objectSimilarity(record1.get(STREET), record2.get(STREET), "UNKNOWN"); address_distance += street_distance; if (old_attribute_count != attribute_count) street_distance = 1.0; address_distance += objectSimilarity(record1.get(ZIP_CODE), record2.get(ZIP_CODE), 0) * street_distance; address_distance += objectSimilarity(record1.get(HOUSE_NUM), record2.get(HOUSE_NUM), 0) * street_distance; address_attributes += old_attribute_count - attribute_count; attribute_count = old_attribute_count; String s1, s2, mc, mw; Integer c1, c2; s1 = (String) record1.get(STATUS_REASON); s2 = (String) record2.get(STATUS_REASON); c1 = (Integer) record1.get(COUNTY); c2 = (Integer) record2.get(COUNTY); mc = "MOVED FROM COUNTY"; mw = "MOVED WITHIN STATE"; // if moved from county, and counties are different, or moved within state // consider address information less heavily if (((s1.equals(mc) || s2.equals(mc)) && (!c1.equals(c2))) || (s1.equals(mw) || s2.equals(mw))) { distances += (address_distance / address_attributes); attribute_count += 1; } else { distances += address_distance; attribute_count += address_attributes; } return Double.max(distances / attribute_count, 0.0); } public Map<String, Object> parseRecord(Map<String, String> values) { HashMap<String, Object> result = new HashMap<>(); List<String> intColumns = Arrays.asList("house_num", "zip_code", "age", "county_id"); for (String key: values.keySet()) { String value = values.get(key); if ((!value.isEmpty()) && (intColumns.contains(key))) { Integer intValue; try { intValue = Integer.parseInt(value); } catch (NumberFormatException e) { intValue = 0; } result.put(key, intValue); } else result.put(key, value); } return result; } @Override public Double compareAttributeValue(String attribute, Object value1, Object value2) { if (value1 instanceof String) return jw.distance((String) value1, (String) value2); else if (value1 instanceof Integer) return hammingDistance(((Integer) value1).toString(), ((Integer) value2).toString()); else return jw.distance(value1.toString(), value2.toString()); } public double hammingDistance(String i1, String i2) { int length = Math.min(i1.length(), i2.length()); int matching_digits = 0; for (int i = 0; i < length; i++) { if (i1.charAt(i) == i2.charAt(i)) matching_digits++; } return (double)matching_digits / length; } public Boolean isMatch(Map<String, Double> similarities) { double similarity = 0.0; int attributeCount = 0; for (String key: similarities.keySet()) { attributeCount++; if (key.equals(FIRST_NAME)) { similarity += 2 * similarities.get(key); attributeCount++; } // age is always identical for duplicate records in the dataset else if (key.equals(AGE)) { if (similarities.get(key) != 1.0) return false; } else similarity += similarities.get(key); } return (similarity / attributeCount) >= datasetThreshold; } @Override public Double calculateAttributeSimilarity(Map<String, Double> similarities) { // TODO Auto-generated method stub return null; }; }
package control.erros; public class ErroExisteTurma extends Exception{ @Override public String getMessage() { return "Erro: Essa turma não está cadastrada no sistema ou ta desativada"; } }
// SPDX-License-Identifier: BSD-3-Clause package org.xbill.DNS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Collections; import org.junit.jupiter.api.Test; import org.xbill.DNS.DNSSEC.Algorithm; import org.xbill.DNS.DNSSEC.Digest; import org.xbill.DNS.EDNSOption.Code; import org.xbill.DNS.utils.base16; class OPTRecordTest { private static final int DEFAULT_EDNS_RCODE = 0; private static final int DEFAULT_EDNS_VERSION = 0; private static final int DEFAULT_PAYLOAD_SIZE = 1024; @Test void testForNoEqualityWithDifferentEDNS_Versions() { final OPTRecord optRecordOne = new OPTRecord(DEFAULT_PAYLOAD_SIZE, DEFAULT_EDNS_RCODE, 0); final OPTRecord optRecordTwo = new OPTRecord(DEFAULT_PAYLOAD_SIZE, DEFAULT_EDNS_RCODE, 1); assertNotEqual(optRecordOne, optRecordTwo); } @Test void testForNoEqualityWithDifferentEDNS_RCodes() { final OPTRecord optRecordOne = new OPTRecord(DEFAULT_PAYLOAD_SIZE, 0, DEFAULT_EDNS_VERSION); final OPTRecord optRecordTwo = new OPTRecord(DEFAULT_PAYLOAD_SIZE, 1, DEFAULT_EDNS_VERSION); assertNotEqual(optRecordOne, optRecordTwo); } @Test void testForEquality() { final OPTRecord optRecordOne = new OPTRecord(DEFAULT_PAYLOAD_SIZE, DEFAULT_EDNS_RCODE, DEFAULT_EDNS_VERSION); final OPTRecord optRecordTwo = new OPTRecord(DEFAULT_PAYLOAD_SIZE, DEFAULT_EDNS_RCODE, DEFAULT_EDNS_VERSION); assertEquals(optRecordOne, optRecordTwo); assertEquals(optRecordTwo, optRecordOne); } @Test void testToString() { try { Options.set("BINDTTL"); OPTRecord optRecord = new OPTRecord(DEFAULT_PAYLOAD_SIZE, 0xFF, DEFAULT_EDNS_VERSION); assertEquals( ".\t\t\t\tOPT\t ; payload 1024, xrcode 255, version 0, flags 0", optRecord.toString()); } finally { Options.unset("BINDTTL"); } } @Test void testMessageToString() { OPTRecord optRecord = new OPTRecord( DEFAULT_PAYLOAD_SIZE, 0xFF, DEFAULT_EDNS_VERSION, Flags.DO, new TcpKeepaliveOption(100), new DnssecAlgorithmOption(Code.DAU, Algorithm.ED25519, Algorithm.ED448), new DnssecAlgorithmOption(Code.DHU, Digest.SHA384), new DnssecAlgorithmOption(Code.N3U, NSEC3Record.Digest.SHA1)); Message m = Message.newQuery(Record.newRecord(Name.root, Type.A, DClass.IN)); m.addRecord(optRecord, Section.ADDITIONAL); assertTrue(m.toString().contains(";; OPT PSEUDOSECTION:")); assertTrue(m.toString().contains("DAU: [ED25519, ED448]")); assertTrue(m.toString().contains("DHU: [SHA-384]")); assertTrue(m.toString().contains("N3U: [SHA-1]")); } @Test void rdataFromString() { TextParseException thrown = assertThrows( TextParseException.class, () -> new OPTRecord().rdataFromString(new Tokenizer(" "), null)); assertTrue(thrown.getMessage().contains("no text format defined for OPT")); } @Test void rdataFromWire() throws IOException { byte[] buf = base16.fromString("000029100000000000000C000A00084531D089BA80C6EB"); OPTRecord record = (OPTRecord) OPTRecord.fromWire(new DNSInput(buf), Section.ADDITIONAL); assertEquals( Collections.singletonList(new CookieOption(base16.fromString("4531D089BA80C6EB"))), record.getOptions()); } @Test void rdataFromWire_nullPadded() throws IOException { byte[] buf = base16.fromString("000029100000000000000C000A00084531D089BA80C6EB00"); OPTRecord record = (OPTRecord) OPTRecord.fromWire(new DNSInput(buf), Section.ADDITIONAL); assertEquals( Collections.singletonList(new CookieOption(base16.fromString("4531D089BA80C6EB"))), record.getOptions()); } private void assertNotEqual(final OPTRecord optRecordOne, final OPTRecord optRecordTwo) { assertNotEquals(optRecordOne, optRecordTwo); assertNotEquals(optRecordTwo, optRecordOne); } }
public interface CarParkManager { public void addVehicle(); public void deleteVehicle(); public void getVehicleParked(); public void getVehicleByDate(); public float payment(Vehicle c); public void getDetailedVehicle(); }
// // Decompiled by Procyon v0.5.36 // package com.davivienda.sara.tablas.binentidad.servicio; import javax.persistence.Query; import com.davivienda.sara.base.exception.EntityServicioExcepcion; import java.util.logging.Level; import javax.persistence.EntityManager; import com.davivienda.sara.entitys.BinEntidad; import com.davivienda.sara.base.BaseEntityServicio; public class BinEntidadServicio extends BaseEntityServicio<BinEntidad> { public BinEntidadServicio(final EntityManager em) { super(em, BinEntidad.class); } public BinEntidad getEntidadXBin(final String bin) throws EntityServicioExcepcion { BinEntidad be = null; try { Query query = null; query = this.em.createNamedQuery("BinEntidad.RegistroUnico"); query.setParameter("bin", (Object)bin); be = (BinEntidad)query.getSingleResult(); } catch (IllegalStateException ex) { BinEntidadServicio.configApp.loggerApp.log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex); throw new EntityServicioExcepcion(ex); } catch (IllegalArgumentException ex2) { BinEntidadServicio.configApp.loggerApp.log(Level.SEVERE, "El par\u00e1metro no es v\u00e1lido ", ex2); throw new EntityServicioExcepcion(ex2); } return be; } }
package eu.javaspecialists.teacher; import java.awt.*; import java.io.*; import java.net.Socket; public class Student { private final ObjectOutputStream out; private final ObjectInputStream in; private final Robot robot; public Student(String serverMachine, String studentName) throws IOException, AWTException { Socket socket = new Socket(serverMachine, Teacher.PORT); robot = new Robot(); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream( new BufferedInputStream(socket.getInputStream())); out.writeObject(studentName); out.flush(); } public void run() throws ClassNotFoundException { try { while (true) { RobotAction action = (RobotAction) in.readObject(); Object result = action.execute(robot); if (result != null) { out.writeObject(result); out.flush(); out.reset(); } } } catch (IOException ex) { System.out.println("Connection closed"); } } public static void main(String[] args) throws Exception { Student student = new Student(args[0], args[1]); student.run(); } }
package com.alibaba.druid.bvt.bug; import com.alibaba.druid.sql.PagerUtils; import com.alibaba.druid.util.JdbcConstants; import junit.framework.TestCase; public class Issue1695 extends TestCase { public void test_for_mysql() throws Exception { String sql = "select ht.* from t_books ht"; String result = PagerUtils.count(sql, JdbcConstants.MYSQL); assertEquals("SELECT COUNT(*)\n" + "FROM t_books ht", result); } public void test_for_pg() throws Exception { String sql = "select ht.* from t_books ht"; String result = PagerUtils.count(sql, JdbcConstants.POSTGRESQL); assertEquals("SELECT COUNT(*)\n" + "FROM t_books ht", result); } public void test_for_oracle() throws Exception { String sql = "select ht.* from t_books ht"; String result = PagerUtils.count(sql, JdbcConstants.ORACLE); assertEquals("SELECT COUNT(*)\n" + "FROM t_books ht", result); } public void test_for_sqlserver() throws Exception { String sql = "select ht.* from t_books ht"; String result = PagerUtils.count(sql, JdbcConstants.SQL_SERVER); assertEquals("SELECT COUNT(*)\n" + "FROM t_books ht", result); } }
package com.operacloud.selenium.actions.extensions; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.PageFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.MediaEntityBuilder; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.operacloud.utils.ReadExcel; import com.selenium.actions.GeneralSeleniumActions; import io.github.bonigarcia.wdm.WebDriverManager; public class OperaCloudSeleniumActions extends GeneralSeleniumActions { public String testName, testDescription, testAuthor, testCategory; @BeforeSuite public void startReport() throws IOException { setUp(); reporter = new ExtentHtmlReporter("./reports/result.html"); reporter.setAppendExisting(false); extent = new ExtentReports(); extent.attachReporter(reporter); launchBrowser(); } //@BeforeMethod public void startApp() { test = extent.createTest(testName, testDescription); test.assignCategory(testCategory); node = test.createNode(testName); } /* * @DataProvider(name = "fetchData") public String[][] methodForData() throws * IOException { ReadExcel re = new ReadExcel(); return * re.excelRead(excelFileName); * * } */ @AfterSuite public void endReport() { extent.flush(); driver.quit(); } public void previewSuccessScheduledReport() throws InterruptedException, IOException { try { switchBetweenOpenedWindows("ex=PREVIEW&rep=EXIST"); /* * ArrayList<String> tabs2 = new ArrayList<String>(driver.getWindowHandles()); * driver.switchTo().window(tabs2.get(1)); String switchedUrl= * driver.getCurrentUrl(); System.out.println("Switched to " + switchedUrl); * * if(switchedUrl.contains("ex=PREVIEW&rep=EXIST")) { * reportStep("Report is generated successfully", "pass"); } Thread.sleep(5000); * driver.close(); driver.switchTo().window(tabs2.get(0)); */ } catch (Exception e) { e.printStackTrace(); } } }
package com.tenmsapp.tenminuteschool.fragments; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.MediaController; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerFragment; import com.tenmsapp.tenminuteschool.R; import com.tenmsapp.tenminuteschool.activities.ActivityHome; import com.tenmsapp.tenminuteschool.activities.ActivityLive; import java.util.List; /** * Created by Pongodev on 11/4/2015. */ public final class FragmentVideo extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener { private YouTubePlayer player; private String videoId; private int videoCurrentDuration; private int videoCompleteDuration; View view; FragmentVideoListener activityCommander; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize("AIzaSyB__E_VxHmsJ5qw1kvbjLpiEwXvspCJCFI", this); } @Override public void onDestroy() { if (player != null) { player.release(); } super.onDestroy(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { activityCommander = (FragmentVideoListener) activity; //activityCommander2 = (FragmentTabVideosListenerTwo) activity; } catch (ClassCastException e){ throw new ClassCastException(activity.toString()); } } public void setVideoId(String videoId) { if (videoId != null && !videoId.equals(this.videoId)) { this.videoId = videoId; if (player != null) { //Toast.makeText(getContext(),"2 ID: "+videoId,Toast.LENGTH_SHORT).show(); player.loadVideo(videoId); //player.play(); } } } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean restored) { this.player = player; player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT); //player.setOnFullscreenListener((ActivityHome) getActivity()); //player.setOnFullscreenListener((ActivityLive) getActivity()); player.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() { @Override public void onLoading() { } @Override public void onLoaded(String s) { } @Override public void onAdStarted() { } @Override public void onVideoStarted() { } @Override public void onVideoEnded() { activityCommander.videoEnded(); //Toast.makeText(getContext(), "Practice Now!", Toast.LENGTH_SHORT).show(); // Snackbar snackbar = Snackbar // .make(view.findViewById(R.id.main_content), "JUST DO IT!", Snackbar.LENGTH_LONG) // .setAction("Practice!", new View.OnClickListener() { // @Override // public void onClick(View v) { // Snackbar snackbar1 = Snackbar // .make(v, "Link Required!", Snackbar.LENGTH_LONG); // View sbView = snackbar1.getView(); // sbView.setBackgroundColor(Color.rgb(65,65,65)); // snackbar1.show(); // } // }); // View sbView = snackbar.getView(); // sbView.setBackgroundColor(Color.rgb(75,75,75)); // snackbar.show(); } @Override public void onError(YouTubePlayer.ErrorReason errorReason) { } }); if (!restored && videoId != null) { //Toast.makeText(getContext(),"1 ID: "+videoId,Toast.LENGTH_SHORT).show(); //player.cueVideo(videoId); //player.play(); setVideoId(videoId); player.loadVideo(videoId); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) { this.player = null; } public void backnormal(){ player.setFullscreen(false); } }
package com.cy.service.bus.impl; import java.util.List; import javax.persistence.Query; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.cy.bean.bus.BusLine; import com.cy.service.base.DAOSupport; import com.cy.service.bus.BusLineService; /** * 公交路线Service接口实现类 * @author CY * */ @Service @Transactional public class BusLineServiceBean extends DAOSupport<BusLine> implements BusLineService { @SuppressWarnings("unchecked") @Override public List<BusLine> getBusLinesByName(String name) { String jql = "select o from BusLine o where o.name like ?1 "; Query query = em.createQuery(jql); query.setParameter(1, "%"+name+"%"); return query.getResultList(); } }
package com.project.daicuongbachkhoa.student.physicsonestudent.tasksphysicsonestudent; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.project.daicuongbachkhoa.R; import com.project.daicuongbachkhoa.model.Tasks; public class TasksPhysicsOneStudent extends AppCompatActivity { private TextView txtSetGroupPhysicsOneStudent; private Button btnGoToGroupPhysicsOneStudent; private RecyclerView revListTasksPhysicsOneStudent; private FirebaseUser student; private FirebaseDatabase database; private DatabaseReference referenceTasks; private FirebaseRecyclerOptions<Tasks> recyclerOptions;//kiểu dữ liệu private FirebaseRecyclerAdapter<Tasks, AdapterTasksPhysicsOneStudent> adapter; private String linkGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tasks_physics_one_student); txtSetGroupPhysicsOneStudent = findViewById(R.id.txtSetGroupPhysicsOneStudent); revListTasksPhysicsOneStudent = findViewById(R.id.revListTasksPhysicsOneStudent); btnGoToGroupPhysicsOneStudent = findViewById(R.id.btnGoToGroupPhysicsOneStudent); //student = FirebaseAuth.getInstance().getCurrentUser(); database = FirebaseDatabase.getInstance(); Intent intent = getIntent(); String idTeacher = intent.getStringExtra("ID_TEACHER_PHYSICS_ONE_STUDENT"); linkGroup = intent.getStringExtra("LINK_GROUP_PHYSICS_ONE_STUDENT"); referenceTasks = database.getReference("Teachers").child(idTeacher).child("Subjects").child("PhysicsOne").child("Tasks"); //referenceTasks.keepSynced(true); showTasksPhysicsOneStudent(); txtSetGroupPhysicsOneStudent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setGroupPhysicsOneStudent(); } }); btnGoToGroupPhysicsOneStudent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goToGroupPhysicsOneStudent(linkGroup); } }); } private void goToGroupPhysicsOneStudent(String url) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } private void showTasksPhysicsOneStudent() { revListTasksPhysicsOneStudent.setHasFixedSize(true); LinearLayoutManager mLayoutManager = new LinearLayoutManager(this); mLayoutManager.setReverseLayout(true); mLayoutManager.setStackFromEnd(true);//đảo ngược danh sách, rất thú vị ! revListTasksPhysicsOneStudent.setLayoutManager(mLayoutManager); //String studentID = student.getUid(); //referenceTasks recyclerOptions = new FirebaseRecyclerOptions.Builder<Tasks>().setQuery(referenceTasks, Tasks.class).build();//khá dài adapter = new FirebaseRecyclerAdapter<Tasks, AdapterTasksPhysicsOneStudent>(recyclerOptions) { @Override protected void onBindViewHolder(@NonNull AdapterTasksPhysicsOneStudent holder, int i, @NonNull Tasks model) { holder.txtTitleTasks.setText(model.getTitleTasks()); holder.txtContentTasks.setText(model.getContentTasks()); } @NonNull @Override public AdapterTasksPhysicsOneStudent onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_tasks, parent, false); //tạo lập view AdapterTasksPhysicsOneStudent viewHolder = new AdapterTasksPhysicsOneStudent(view); return viewHolder; } }; revListTasksPhysicsOneStudent.setAdapter(adapter);//ok } @Override protected void onStart() { super.onStart();//đừng quên hàm này, nó là sự lắng nghe thay đổi ! adapter.startListening(); } @Override protected void onStop() { super.onStop(); adapter.stopListening(); } private void setGroupPhysicsOneStudent() { startActivity(new Intent(TasksPhysicsOneStudent.this, GetTasksPhysicsOneStudent.class)); } }
/** * Alipay.com Inc. * Copyright (c) 2004-2018 All Rights Reserved. */ package com.ranttu.rapid.reffer.test; import java.util.Map; /** * @author rapid * @version $Id: ByteCodeTest.java, v 0.1 2018年09月21日 1:23 AM rapid Exp $ */ public class ByteCodeTest { ByteCodeTest() throws InstantiationException { Map<String, String> a = null; a.put("1", "2"); } } //// class version 52.0 (52) //// access flags 0x21 //public class com/ranttu/rapid/reffer/test/ByteCodeTest { // //// compiled from: ByteCodeTest.java // //// access flags 0x0 //<init>()V // L0 // LINENUMBER 14 L0 // ALOAD 0 // INVOKESPECIAL java/lang/Object.<init> ()V // L1 // LINENUMBER 15 L1 // ACONST_NULL // LCONST_0 // ICONST_0 // INVOKESTATIC com/ranttu/rapid/reffer/misc/BackdoorObject.setByte (Ljava/lang/Object;JB)V // L2 // LINENUMBER 16 L2 // RETURN // L3 // LOCALVARIABLE this Lcom/ranttu/rapid/reffer/test/ByteCodeTest; L0 L3 0 // MAXSTACK = 4 // MAXLOCALS = 1 //} //
package comp1110.ass2; import org.junit.jupiter.api.Test; import java.util.Arrays; import static comp1110.ass2.ExampleGames.FULL_GAME_WITH_MOVES; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; @org.junit.jupiter.api.Timeout(value = 1000, unit = MILLISECONDS) public class ApplyMoveTest { private String errorPrefix(String[] inputState, String move) { return "Azul.applyMove({\"" + inputState[0] + "\", \"" + inputState[1] + "\", \"" + move + "\"}) returned invalid result "; } @Test public void testFloorFull() { String[] gameState = {"AF4bbccCbbbcdeeeeeeefB1615171913D0000000000", "A0MS2a2FB0MS2a2F"}; String move = "ACeF"; String[] next = {"BF4bbccCbbbcdB1615171913D0000000001", "A0MS2a2FeeeeeefB0MS2a2F"}; String[] out = Azul.applyMove(gameState, move); String errorMessagePrefix = errorPrefix(gameState, move); assertEquals(Arrays.toString(next), Arrays.toString(out), errorMessagePrefix + "expected 'e' tile to overflow to discard"); } @Test public void testStorageFull() { String[] gameState = {"AFCddddeeeB0504060401D0409050713", "A0Mb00e04d10b11c21a32S1a22a23b24a5FfB3Mc02e03d04b14e24b31d33S0b11d22c33c14a1Fccc"}; String move = "ACd0"; String[] next = {"BFCeeeB0504060401D0409050713", "A0Mb00e04d10b11c21a32S0d11a22a23b24a5FdddfB3Mc02e03d04b14e24b31d33S0b11d22c33c14a1Fccc"}; String[] out = Azul.applyMove(gameState, move); String errorMessagePrefix = errorPrefix(gameState, move); assertEquals(Arrays.toString(next), Arrays.toString(out), errorMessagePrefix + "expected move to overflow onto floor"); } @Test public void testTilingMove() { for (int i = 0; i < FULL_GAME_WITH_MOVES.length - 1; i++) { String[] previous = FULL_GAME_WITH_MOVES[i]; if (previous.length == 2) { continue; } String move = previous[2]; if (previous[2].length() == 3) { String[] next = FULL_GAME_WITH_MOVES[i + 1]; String[] prevState = {previous[0], previous[1]}; String[] nextState = {next[0], next[1]}; String[] out = Azul.applyMove(prevState.clone(), move); String errorMessagePrefix = errorPrefix(prevState, move); assertEquals(Arrays.toString(nextState), Arrays.toString(out), errorMessagePrefix); } } } @Test public void testDraftingMove() { for (int i = 0; i < FULL_GAME_WITH_MOVES.length - 1; i++) { String[] previous = FULL_GAME_WITH_MOVES[i]; if (previous.length == 2) { continue; } String move = previous[2]; if (previous[2].length() == 4) { String[] next = FULL_GAME_WITH_MOVES[i + 1]; String[] prevState = {previous[0], previous[1]}; String[] nextState = {next[0], next[1]}; String[] out = Azul.applyMove(prevState.clone(), move); String errorMessagePrefix = errorPrefix(prevState, move); assertEquals(Arrays.toString(nextState), Arrays.toString(out), errorMessagePrefix); } } } }
package com.git.cloud.request.model.po; import java.sql.Timestamp; import com.git.cloud.common.model.base.BaseBO; public class BmToDoPo extends BaseBO implements java.io.Serializable { private static final long serialVersionUID = 1L; private String todoId; private String srId; private String currentStep; private String currentGroupId; private String currentUserId; private String todoStatus; private String pageUrl; private String taskId; private String nodeId; private String instanceId; private Timestamp createTime; private Timestamp operateTime; private Timestamp dealTime; public BmToDoPo() { } public BmToDoPo(String todoId) { this.todoId = todoId; } public BmToDoPo(String todoId, String srId, String currentStep, String currentGroupId, String currentUserId, String todoStatus, String pageUrl, String taskId, String nodeId, String instanceId, Timestamp createTime, Timestamp operateTime, Timestamp dealTime) { this.todoId = todoId; this.srId = srId; this.currentStep = currentStep; this.currentGroupId = currentGroupId; this.currentUserId = currentUserId; this.todoStatus = todoStatus; this.pageUrl = pageUrl; this.taskId = taskId; this.nodeId = nodeId; this.instanceId = instanceId; this.createTime = createTime; this.operateTime = operateTime; this.dealTime = dealTime; } public String getTodoId() { return todoId; } public void setTodoId(String todoId) { this.todoId = todoId; } public String getSrId() { return srId; } public void setSrId(String srId) { this.srId = srId; } public String getCurrentStep() { return currentStep; } public void setCurrentStep(String currentStep) { this.currentStep = currentStep; } public String getCurrentGroupId() { return currentGroupId; } public void setCurrentGroupId(String currentGroupId) { this.currentGroupId = currentGroupId; } public String getCurrentUserId() { return currentUserId; } public void setCurrentUserId(String currentUserId) { this.currentUserId = currentUserId; } public String getTodoStatus() { return todoStatus; } public void setTodoStatus(String todoStatus) { this.todoStatus = todoStatus; } public String getPageUrl() { return pageUrl; } public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public Timestamp getOperateTime() { return operateTime; } public void setOperateTime(Timestamp operateTime) { this.operateTime = operateTime; } public Timestamp getDealTime() { return dealTime; } public void setDealTime(Timestamp dealTime) { this.dealTime = dealTime; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } }
package org.qamation.charities.extractor; import org.junit.Test; import org.qamation.charities.BaseTest; import java.util.List; public class CharityLinkExtractorTests extends BaseTest { @Test public void getCharitiesLinksTest() { CharityLinkExtractor extractor = new CharityLinkExtractor(driver,"https://charityintelligence.ca/research/a-z-charity-listing"); List<String> links = extractor.getLinks(); for (String s : links) { System.out.println(s); } } }
package com.alibaba.druid.bvt.bug; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.parser.SQLParserUtils; import com.alibaba.druid.sql.parser.SQLStatementParser; import com.alibaba.druid.util.JdbcConstants; import com.alibaba.druid.util.JdbcUtils; import com.alibaba.druid.util.Utils; import junit.framework.TestCase; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; /** * Created by wenshao on 03/02/2017. */ public class Issue4253 extends TestCase { private final DbType dbType = JdbcConstants.ORACLE; public void test_for_issue() throws Exception { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("bvt/parser/oracle-62.txt"); Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8); String input = Utils.read(reader); JdbcUtils.close(reader); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(input, dbType); Exception error = null; try { parser.parseStatement(true); } catch (Exception ex) { ex.printStackTrace(); error = ex; error.printStackTrace(); } assertNull(error); } }
package com.zeal.smartdo.home.model; import com.zeal.common.utils.DateUtils; import org.litepal.annotation.Column; import org.litepal.crud.DataSupport; import java.io.Serializable; public class Todo extends DataSupport implements Serializable{ public long id; @Column(unique = true) public long date; public String title; public int isFinish; public String content; public Todo(long date, String title, int isFinish, String content) { this.date = date; this.title = title; this.isFinish = isFinish; this.content = content; } @Override public String toString() { return "Todo{" + "date=" + DateUtils.getYearMonthAndDayAndHourMiniteSecond(date) + ", title='" + title + '\'' + ", " + (isFinish == 0 ? "未完成" : "已完成") + ", content='" + content + '\'' + '}'; } }
import java.util.Date; import java.text.SimpleDateFormat; class HoneyDemo { public static void main(String[] args) { HoneyComb hc = new HoneyComb(0); Bear br=new Bear("Bear", hc); Bee[] bees=new Bee [20]; // Bee b1=new Bee("bee"+1,hc); hc.start(); br.start(); // b1.start(); for(int i=0;i<bees.length;i++) { bees[i]=new Bee("bee"+i,hc); bees[i].start(); } } } class HoneyComb extends Thread { private int honeyWeight=0; private int capacity=20; private int upLine = 20; HoneyComb() { } HoneyComb(int honeyWeight) { this.honeyWeight = honeyWeight; } public synchronized boolean addHoney(int weight) { if(weight<0) return false; else { while(honeyWeight+weight>capacity) { try { System.out.print("."); this.wait(); } catch(Exception e) { } } honeyWeight+=weight; if(honeyWeight>=upLine) { try { //this.notifyAll(); notify(); System.out.println("upline meet !"); } catch(Exception e) { } } return true; } } public synchronized boolean takeHoney(int weight) { if(weight<0) { return false; } else { while(weight>honeyWeight) { try { System.out.println("takeHoney waiting ... "); this.wait(); } catch(Exception e) { } } honeyWeight-=weight; try { //this.notifyAll(); notify(); } catch(Exception e) { } return true; } } public void run() { while(true) { System.out.println(new Date()+" : "+ honeyWeight); try { Thread.sleep(1000); } catch(Exception e) { } } } } class Bee extends Thread { private String id; private HoneyComb hc; private int pWeight=1; Bee(String id, HoneyComb hc) { this.id=id; this.hc=hc; } private void produceHoney() { hc.addHoney(pWeight); System.out.print("-"); try { //Thread.sleep(500); } catch(Exception e) { } } public void run() { while(true) { produceHoney(); } } } class Bear extends Thread { private String id; private HoneyComb hc; private int sWeight=20; Bear(String id, HoneyComb hc) { this.id=id; this.hc=hc; } private void consumeHoney() { hc.takeHoney(sWeight); System.out.println(id+"consumed !"); } public void run() { while(true) { consumeHoney(); } } }
package com.zhicai.byteera.activity.community.dynamic.entity; /** Created by bing on 2015/6/2. */ public class OrganizationHomeDynamicEntity { private String avatarUrl; private String name; private String content; private int commentNum; private boolean like; private long time; public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getCommentNum() { return commentNum; } public void setCommentNum(int commentNum) { this.commentNum = commentNum; } public boolean isLike() { return like; } public void setLike(boolean like) { this.like = like; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } }
package com.jcircle.ratinginfo.request; import com.jcircle.ratinginfo.model.Movie; import com.jcircle.ratinginfo.model.MovieRatingFactor; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class CountryRatingRequest { private String countryCode; private MovieRatingFactor movieRatingFactor; }
package com.mingrisoft; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.Box; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.UIManager; class Candidate extends JCheckBox { // 定义内容类,该类继承JCheckBox类 /** * */ private static final long serialVersionUID = -5408876343113378593L; int len = 0; Candidate(String name, Icon icon) { // 该类包含有两个参数 super(name, icon); } public int getBallot(String name) { File file = new File("D://count.txt"); // 创建文件对象 FileReader fis; try { if (!file.exists()) // 如果该文件不存在 file.createNewFile(); // 新建文件 fis = new FileReader(file); BufferedReader bis = new BufferedReader(fis); // 创建BufferedReader对象 String str[] = new String[3]; String size; int i = 0; while ((size = bis.readLine()) != null) { // 循环读取文件内容 str[i] = size.trim(); // 去除字符串中的空格 if (str[i].startsWith(name)) { int length = str[i].indexOf(":"); String sub = str[i].substring(length + 1, str[i].length()); // 对字符串进行截取 len = Integer.parseInt(sub); continue; } i++; } } catch (Exception e) { e.printStackTrace(); } return len; } public void addBallot(String name) { // 定义增加选票方法 File file = new File("D://count.txt"); // 创建文件对象 FileReader fis; try { if (!file.exists()) // 如果该文件不存在 file.createNewFile(); // 新建文件 fis = new FileReader(file); // 对FileReader对象进行实例化 BufferedReader bis = new BufferedReader(fis); String str[] = new String[3]; String size; int i = 0; while ((size = bis.readLine()) != null) { // 循环读取文件 str[i] = size.trim(); if (str[i].startsWith(name)) { int length = str[i].indexOf(":"); // 获取指定字符索引位置 String sub = str[i].substring(length + 1, str[i].length()); // 对字符串进行截取 len = Integer.parseInt(sub) + 1; break; } i++; } FileWriter fw = new FileWriter(file); // 创建FileWriter 对象 BufferedWriter bufw = new BufferedWriter(fw); bufw.write(name + ":" + len); // 向流中写数据 bufw.close(); // 关闭流 fw.close(); } catch (Exception e) { e.printStackTrace(); } } } class MyMin extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 7341493970991277188L; Box baseBox, boxH, boxV; // 创建Box对象 JTextArea text; // 创建JTextArea对象 JButton button; // 创建JButton对象 Candidate candidateOne, candidateTwo, candidateThree; public MyMin() { // 在构造方法中设置窗体布局 setBounds(100, 100, 500, 120); setVisible(true); setTitle("选出你心中的好干部!!"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // 窗体关闭事件 System.exit(0); } }); baseBox = Box.createHorizontalBox(); boxH = Box.createHorizontalBox(); boxV = Box.createHorizontalBox(); candidateOne = new Candidate("小兵", new ImageIcon("src/images/0.gif")); candidateTwo = new Candidate("小陈", new ImageIcon("src/images/1.gif")); candidateThree = new Candidate("小李", new ImageIcon("src/images/2.gif")); candidateOne.setSelectedIcon(new ImageIcon("src/images/0.gif")); candidateTwo.setSelectedIcon(new ImageIcon("src/images/1.gif")); candidateThree.setSelectedIcon(new ImageIcon("src/images/2.gif")); boxH.add(candidateOne); boxH.add(candidateTwo); boxH.add(candidateThree); text = new JTextArea(); button = new JButton("显示得票数"); button.addActionListener(this); boxV.add(text); boxV.add(button); boxV.add(boxH); baseBox.add(boxV); Container con = getContentPane(); con.setLayout(new FlowLayout()); con.add(baseBox); con.validate(); } @Override public void actionPerformed(ActionEvent e) { text.setText(null); File file = new File("D://count.txt"); // 创建文件对象 if (!file.exists()) { // 如果该文件不存在 try { file.createNewFile(); // 新建文件 } catch (IOException e1) { e1.printStackTrace(); } } if (candidateOne.isSelected()) { candidateOne.addBallot(candidateOne.getText()); } if (candidateTwo.isSelected()) { candidateTwo.addBallot(candidateTwo.getText()); } if (candidateThree.isSelected()) { candidateThree.addBallot(candidateThree.getText()); } // 向文本框中追加信息 text.append(candidateOne.getText() + ":" + candidateOne.getBallot(candidateOne.getText()) + "\n"); text.append(candidateTwo.getText() + ":" + candidateTwo.getBallot(candidateTwo.getText()) + "\n"); text.append(candidateThree.getText() + ":" + candidateThree.getBallot(candidateThree.getText()) + "\n"); try { if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file); // 创建FileWriter类对象 BufferedWriter bufw = new BufferedWriter(fw); // 创建BufferedWriter类对象 bufw.write(text.getText()); // 将字符串数组中元素写入到磁盘文件中 bufw.close(); // 将BufferedWriter流关闭 fw.close(); } catch (IOException e1) { e1.printStackTrace(); } candidateOne.setSelected(false); candidateTwo.setSelected(false); candidateThree.setSelected(false); } } public class Ballot { public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } new MyMin(); } }
package hu.lamsoft.hms.androidclient.activity; import android.os.Bundle; import android.widget.TextView; import hu.lamsoft.hms.androidclient.R; import hu.lamsoft.hms.androidclient.restapi.nutritionist.dto.BlogEntryDTO; public class BlogEntryActivity extends DTODetailsActivity<BlogEntryDTO> { private TextView blogEntryWriter; private TextView blogEntryPreface; private TextView blogEntryContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blog_entry); getSupportActionBar().setTitle(baseDTO.getTitle()); blogEntryWriter = (TextView) findViewById(R.id.blog_entry_activity_writer_text_view); blogEntryPreface = (TextView) findViewById(R.id.blog_entry_activity_preface_text_view); blogEntryContent = (TextView) findViewById(R.id.blog_entry_activity_content_text_view); blogEntryWriter.setText(baseDTO.getWriter().getCustomer().getFirstname()+" "+baseDTO.getWriter().getCustomer().getLastname()); blogEntryPreface.setText(baseDTO.getPreface()); blogEntryContent.setText(baseDTO.getContent()); } }
package com.joalib.DAO; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.joalib.DTO.PointDTO; import com.joalib.DAO.memberinfoDAO; public class PointDAO { SqlSessionFactory sqlfactory; //싱글톤 패턴 private static PointDAO instance; public static PointDAO getinstance() { if (instance == null) { // >DAO 객체 만든적 있어? synchronized (PointDAO.class) { instance = new PointDAO(); } } return instance; } public PointDAO(){ try { Reader reader = Resources.getResourceAsReader("com/joalib/DAO/mybatis_test-config.xml"); //xml 연결 sqlfactory = new SqlSessionFactoryBuilder().build(reader); //batis를 증명하는 아이. } catch (IOException e) { e.printStackTrace(); } } // //현재 포인트 조회 public int memberPointNow(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int total_point = sqlsession.selectOne("pointNowSelect",member_id); sqlsession.commit(); sqlsession.close(); return total_point; } //포인트 내역 조회 public List<PointDTO> memberPointList(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); List<PointDTO> dto = sqlsession.selectList("pointListSelect",member_id); sqlsession.commit(); sqlsession.close(); return dto; } //포인트 충전(임시) public int PointChargeTemp(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int i = sqlsession.insert("pointChargeTemp",member_id); sqlsession.commit(); sqlsession.close(); return i; } //포인트 충전(자유게시판 포인트) public int boardPointCharge(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int i = sqlsession.insert("boardPointCharge",member_id); sqlsession.commit(); sqlsession.close(); return i; } //포인트 충전(자유게시판 댓글 포인트) public int boardCommentPointCharge(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int i = sqlsession.insert("boardCommnetPointCharge",member_id); sqlsession.commit(); sqlsession.close(); return i; } //포인트 충전(불량도서 신고 포인트 + 1000) public int faultPointCharge(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int i = sqlsession.insert("faultPointCharge",member_id); sqlsession.commit(); sqlsession.close(); return i; } //포인트 충전(중고도서 나눔 포인트 + 5000) public int donatePointCharge(String member_id) { SqlSession sqlsession = sqlfactory.openSession(); int i = sqlsession.insert("donateCompletePoint",member_id); sqlsession.commit(); sqlsession.close(); return i; } //totalPoint를 가져와서 포인트 충전해주는 구문 ////insert into joalib.point values ('test5', 1000, now(), 'test2', ((select total_point from joalib.point as temp where member_id = 'test5' order by update_date desc limit 1)+1000)); }
package com.sutran.client.service; import com.sutran.client.bean.GenTbHorometro; public interface GenTbHorometroService extends ServiceTemplate<GenTbHorometro, Integer> { }
package com.se.onck3client.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; public class Person { private Integer id; private String firstName; private String lastName; private Double money; private List<CreditCard> creditCards; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public List<CreditCard> getCreditCards() { return creditCards; } public void setCreditCards(List<CreditCard> creditCards) { this.creditCards = creditCards; } public CreditCard getCreditCard(int theId) { if(creditCards !=null) { for(CreditCard c : creditCards) { if(c.getId() == theId) return c; } } return null; } public void addCreditCard(CreditCard c) { if(creditCards == null) { creditCards = new ArrayList<CreditCard>(); } creditCards.add(c); } public Person(Integer id, String firstName, String lastName, Double money, List<CreditCard> creditCards) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; this.money = money; this.creditCards = creditCards; } public Person() { super(); // TODO Auto-generated constructor stub } }
package demos.okan.earthquakes.util; public class Constants { public static final double EARTHQUAKE_MAGNITUDE_THRESHOLD = 8.0; }
package com.tbonzer.hello.rs; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.tbonzer.hello.resource.Greeting; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; @Controller public class GreetingController { private static final String TEMPLATE = "Hello %s!"; @ApiOperation(value = "getGreeting", nickname = "getGreeting") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "User's name", required = false, dataType = "string", paramType = "query", defaultValue="Niklas") }) @RequestMapping(value = "/greeting", method = RequestMethod.GET) @ResponseBody public HttpEntity<Greeting> greeting( @RequestParam(value = "name", required = false, defaultValue = "World") String name) { Greeting greeting = new Greeting(String.format(TEMPLATE, name)); greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)) .withSelfRel()); return new ResponseEntity<Greeting>(greeting, HttpStatus.OK); } }
package ru.steagle.service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import java.util.List; import ru.steagle.config.Config; import ru.steagle.config.Keys; import ru.steagle.datamodel.DataModel; import ru.steagle.datamodel.Sensor; import ru.steagle.protocol.Request; import ru.steagle.protocol.RequestTask; import ru.steagle.protocol.request.GetSensorsCommand; import ru.steagle.protocol.responce.Sensors; public class SensorRequestCommand extends BaseRequestCommand implements IRequestDataCommand { public static final String PARAM_SENSOR_ID = "sensorId"; private static final long MAX_LOADING_INTERVAL_MS = 60000; private static final long LOADING_PAUSE_MS = 5000; private static final String TAG = SensorRequestCommand.class.getName(); protected DataModel dataModel; protected long time2finish; protected IBroadcastSender broadcastSender; protected String deviceId; protected String sensorId; protected String statusId; protected boolean isTerminated; protected Context context; public SensorRequestCommand(Context context, DataModel dataModel, IBroadcastSender broadcastSender, String deviceId, String sensorId, String statusId) { this.context = context; this.dataModel = dataModel; this.broadcastSender = broadcastSender; this.deviceId = deviceId; this.sensorId = sensorId; this.statusId = statusId; time2finish = System.currentTimeMillis() + MAX_LOADING_INTERVAL_MS; } protected boolean authCheck() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); return prefs.getString(Keys.LOGIN.getPrefKey(), null) != null && prefs.getString(Keys.PASSWORD.getPrefKey(), null) != null; } @Override public boolean canRun() { return canRun && authCheck() && (System.currentTimeMillis() > time2load); } @Override public boolean isTerminated() { return isTerminated; } @Override public void run() { canRun = false; runLoading(new AsyncRun<List<Sensor>>() { @Override public void onSuccess(List<Sensor> list) { dataModel.setSensors(list); if (System.currentTimeMillis() > time2finish || sensorStatusChanged(list)) { Intent intent = new Intent(SteagleService.BROADCAST_ACTION); intent.putExtra(SteagleService.OBJECT_NAME, SteagleService.Dictionary.SENSOR_STATUS_CHANGE.toString()); intent.putExtra(PARAM_SENSOR_ID, sensorId); broadcastSender.sendBroadcast(intent); isTerminated = true; } else { Intent intent = new Intent(SteagleService.BROADCAST_ACTION); intent.putExtra(SteagleService.OBJECT_NAME, SteagleService.Dictionary.SENSOR.toString()); broadcastSender.sendBroadcast(intent); } time2load = System.currentTimeMillis() + LOADING_PAUSE_MS; canRun = true; } @Override public void onFailure() { time2load = System.currentTimeMillis() + LOADING_PAUSE_MS; canRun = true; } }); } private boolean sensorStatusChanged(List<Sensor> list) { if (sensorId == null || statusId == null) return true; for (Sensor sensor: list) { if (sensorId.equals(sensor.getId()) && statusId.equals(sensor.getStatusId())) return true; } return false; } public void runLoading(final AsyncRun<List<Sensor>> asyncRun) { Request request = new Request().add(new GetSensorsCommand(context, deviceId)); Log.d(SteagleService.TAG, "wait for SENSOR list changes request: " + request); RequestTask requestTask = new RequestTask(Config.getRegServer(context)) { @Override public void onPostExecute(String result) { Log.d(SteagleService.TAG, "wait for SENSOR list changes response: " + result); Sensors objects = new Sensors(result); if (objects.isOk()) { asyncRun.onSuccess(objects.getList()); } else { asyncRun.onFailure(); } } @Override protected void onCancelled() { asyncRun.onFailure(); } }; requestTask.execute(request.serialize()); } }
package person.zhao.thread; /** * synchonized synchonize可以放在方法上,也可以同步方法块 * 无论修饰方法还是对象(方法块), 锁定的都是调用该方法的对象 * * 一个对象有多个synchonized方法或者方法块, * 调用一个其他的就都锁定 * 原理见上面一段儿 * * 不同实例的sychonized方法互不影响 * static的sychonized方法则相反,作用在所有的实例上 * * static和非static方法的锁互不干预,一个锁的是Class,一个锁的是obj * synchonized函数可以被继承,但是synchnized关键字不被继承 */ public class BaseDemo4 { public void p() throws Exception { Object obj1 = new Object(); Object obj2 = new Object(); // 线程A,B是使用相同的对象锁,A,B串行 // 线程C是不同对象,C和A竞争 Thread ta = new Thread(new MyThread41("A", obj1)); Thread tb = new Thread(new MyThread41("B", obj1)); Thread tc = new Thread(new MyThread41("C", obj2)); ta.start(); tb.start(); tc.start(); } public static void main(String[] args) { try { new BaseDemo4().p(); } catch (Exception e) { e.printStackTrace(); } } } class MyThread41 implements Runnable { private String name = null; private Object obj = null; public MyThread41(String name, Object obj) { super(); this.name = name; this.obj = obj; } @Override public void run() { // synchorized放在for上面和for下面会有不同的现象, 有意思。。。, 看来synchronize块结束,是有机会释放锁的 // thread C存在与否也对A B的结果有影响。 有意思。。。, 看来有竞争也会导致释放锁的时机不同。 synchronized (obj) { for (int i = 1; i <= 10; i++) { System.out.println(String.format("[thread %s] - %s", name, String.valueOf(i))); } } } }
/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cglib.proxy; /** * Lazy-loading {@link Enhancer} callback. */ public interface LazyLoader extends Callback { /** * Return the object which the original method invocation should be * dispatched. Called as soon as the first lazily-loaded method in * the enhanced instance is invoked. The same object is then used * for every future method call to the proxy instance. * @return an object that can invoke the method */ Object loadObject() throws Exception; }
package com.gci.api; public interface Constants { public static final String SERVER_URI = "http://localhost/api"; public static final String GET_CONTRACTS_URI = "/contracts"; public static final String GET_CONTRACT_URI = "/contract"; public static final String GET_INVOICES_URI = "/invoices"; public static final String GET_INVOICE_URI = "/invoice"; public static final String UNKNOWN = "<NA>"; public static final int RANDOM_ID_LENGTH = 10; public static final int RANDOM_SERVICE_NAME_LENGTH = 10; public static final int RANDOM_SITE_NAME_LENGTH = 10; public static final String SITE_PREFIX = "Site "; public static final String SERVICE_PREFIX = "100 MBS "; }
package com.tinygame.cmdhandler; import com.tinygame.model.MoveState; import com.tinygame.model.User; import com.tinygame.model.UserManager; import com.tinygame.msg.GameMsgProtocol; import com.tinygame.server.Broadcaster; import io.netty.channel.ChannelHandlerContext; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> { static private final Logger LOGGER = LoggerFactory.getLogger(UserMoveToCmdHandler.class); @Override public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) { if (null==ctx || null == cmd){ return; } Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get(); if (null == userId){ return; } /** * 获取移动用户 * */ User user = UserManager.getUserById(userId); if (null == user){ LOGGER.error("未找到用户,userId={}",userId); return; } /** * 设置用户移动状态 * */ MoveState moveState = user.getMoveState(); moveState.fromPosX=cmd.getMoveFromPosX(); moveState.fromPosY=cmd.getMoveFromPosY(); moveState.toPosX=cmd.getMoveToPosX(); moveState.toPosY=cmd.getMoveToPosY(); moveState.startTime=System.currentTimeMillis(); GameMsgProtocol.UserMoveToResult.Builder resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder(); resultBuilder.setMoveUserId(userId); resultBuilder.setMoveFromPosX(moveState.getFromPosX()); resultBuilder.setMoveFromPosY(moveState.getFromPosY()); resultBuilder.setMoveToPosX(moveState.getToPosX()); resultBuilder.setMoveToPosY(moveState.getToPosY()); resultBuilder.setMoveStartTime(moveState.getStartTime()); GameMsgProtocol.UserMoveToResult newResult = resultBuilder.build(); Broadcaster.broadCast(newResult); } }
package by.htp.carparking.dao.hbm; import java.util.ArrayList; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import by.htp.carparking.dao.CarDao; import by.htp.carparking.domain.Car; //@Component @Repository(value="daoHBM") public class CarDaoHibernateImpl implements CarDao { @Override public void create(Car entity) { // TODO Auto-generated method stub } @Override public Car read(int id) { // TODO Auto-generated method stub return null; } @Override public List<Car> readAll() { /* * Session session = SessionFactoryManager * .getSessionFactory().openSession(); * * Criteria criteria = session.createCriteria(Car.class); * * return criteria.list(); */ ArrayList<Car> cars = new ArrayList<Car>(); cars.add(new Car()); return cars; } @Override public void update(Car entity) { // TODO Auto-generated method stub } @Override public void delete(int id) { // TODO Auto-generated method stub } }
package common.environment; import common.environment.driver.Browser; import common.util.PropertiesUtil; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static common.environment.driver.Browser.chrome; import static common.environment.driver.Browser.fireFox; import static common.util.PropertiesUtil.*; public class DriverProvider { private static final Logger LOGGER = Logger.getLogger(DriverProvider.class); static Driver getDriver(Browser browser, boolean enableCookies) throws IOException { return new Driver(browser, enableCookies); } private DriverProvider() { } static class Driver { private WebDriver fDriver; private final Browser fBrowser; private final boolean fEnableCookies; Driver(Browser browser, boolean enableCookies) throws IOException { this.fBrowser = browser; this.fEnableCookies = enableCookies; initializeDriver(); } WebDriver getWebDriver() { return fDriver; } void quitDriver() { fDriver.quit(); LOGGER.info("Driver quit successfully"); } private void initializeDriver() throws IOException { switch (fBrowser) { case chrome: initializeChromeDriver(); break; case fireFox: initializeFirefoxDriver(); break; default: LOGGER.info("Initializing default common.environment.driver"); initializeFirefoxDriver(); } } private void initializeFirefoxDriver() throws IOException { System.setProperty(PATH_PROPERTY_FIREFOX_DRIVER, PropertiesUtil.getProperty(fireFox)); if (fEnableCookies) { fDriver = new FirefoxDriver(); } else { FirefoxProfile profile = new FirefoxProfile(); profile.setPreference(FIREFOX_NETWORK_COOKIE_BEHAVIOR, 2); FirefoxOptions options = new FirefoxOptions(); options.setProfile(profile); fDriver = new FirefoxDriver(options); } LOGGER.info("Successfully launched fireFox common.environment.driver"); } private void initializeChromeDriver() throws IOException { LOGGER.info("Initializing Chrome webDriver"); System.setProperty(PATH_PROPERTY_CHROME_DRIVER, PropertiesUtil.getProperty(chrome)); ChromeDriverService driverService = ChromeDriverService.createDefaultService(); ChromeOptions options = new ChromeOptions(); options.addArguments(Arrays.asList("allow-running-insecure-content", "ignore-certificate-errors")); if (!fEnableCookies) { Map<String, Integer> preference = new HashMap<>(); preference.put(CHROME_NETWORK_COOKIES_BEHAVIOR, 2); options.setExperimentalOption("prefs", preference); } fDriver = new ChromeDriver(driverService, options); LOGGER.info("Successfully launched chrome common.environment.driver"); } } }
public class Master { private String name; public Master(String name) { this.name=name; } public String getName() { return name; } public void input() { System.out.println(getName()); } }
package com.example.pokedex; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.api.APIClient; import com.example.models.FlavorTextEntries; import com.example.models.IDImgTypes; import com.example.models.RecyclerAPI; import com.squareup.picasso.Picasso; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class PokemonIntent extends AppCompatActivity { private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; private ImageView pokemonPic; private TextView nameTextView, numberTextView; private TextView type1TextView; private TextView type2TextView; private TextView catchButtonText; private TextView pokemonDesc; private Boolean catched; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pokemon); sharedPreferences = getApplicationContext().getSharedPreferences("PokemonPull", 0); editor = sharedPreferences.edit(); catched = false; pokemonPic = findViewById(R.id.imageView); nameTextView = findViewById(R.id.pokemon_name); numberTextView = findViewById(R.id.pokemon_number); type1TextView = findViewById(R.id.pokemon_type1); type2TextView = findViewById(R.id.pokemon_type2); catchButtonText = findViewById(R.id.button); pokemonDesc = findViewById(R.id.Description); APIClient.BASE_URL = "https://pokeapi.co/api/v2/" ; RecyclerAPI service = APIClient.getInstance().create(RecyclerAPI.class); Call<IDImgTypes> call = service.getId(getIntent().getIntExtra("id", 0)); call.enqueue(new Callback<IDImgTypes>() { @Override public void onResponse(Call<IDImgTypes> call, Response<IDImgTypes> response) { numberTextView.setText(String.format("#%03d", response.body().getId())); nameTextView.setText(response.body().getName()); if(response.body().getTypes().size() == 2) { type1TextView.setText(response.body().getTypes().get(0).getType().getName()); type2TextView.setText(response.body().getTypes().get(1).getType().getName()); } else if(response.body().getTypes().size() == 1) { type1TextView.setText(response.body().getTypes().get(0).getType().getName()); } if (sharedPreferences.getBoolean(response.body().getName(),false)) { catchPokemon(); } else { releasePokemon(); } ImageView ivBasicImage = (ImageView) findViewById(R.id.imageView); Picasso.get().load(response.body().getSprites().getFrontDefault()).into(ivBasicImage); } @Override public void onFailure(Call<IDImgTypes> call, Throwable t) { Toast.makeText(getApplicationContext(),"JSON parsing failed",Toast.LENGTH_LONG).show(); } }); Call<FlavorTextEntries> call_2 = service.getFlav(getIntent().getIntExtra("id", 0)); call_2.enqueue(new Callback<FlavorTextEntries>() { @Override public void onResponse(Call<FlavorTextEntries> call, Response<FlavorTextEntries> response) { for(int i = 0 ; i < response.body().getFlavorTextEntries().size() ; i++){ if(response.body().getFlavorTextEntries().get(i).getLanguage().getName().equals("en")) pokemonDesc.setText(response.body().getFlavorTextEntries().get(i).getFlavorText()); } } @Override public void onFailure(Call<FlavorTextEntries> call, Throwable t) { } }); } public void toggleCatch(View view) { if (catched) { releasePokemon(); } else { catchPokemon(); } } @SuppressLint({"DefaultLocale", "SetTextI18n"}) private void catchPokemon() { catched = true; catchButtonText.setText("Release"); editor.putBoolean(numberTextView.getText().toString(), true); editor.putBoolean(nameTextView.getText().toString(), true); editor.commit(); } private void releasePokemon() { catched = false; catchButtonText.setText("Catch"); editor.remove(nameTextView.getText().toString()); editor.remove(numberTextView.getText().toString()); editor.commit(); } }
package com.feng.stream; import java.util.ArrayList; import java.util.List; public class EmployeeData { public static List<Employee> getEmployees(){ List<Employee> list = new ArrayList<>(); list.add(new Employee(101,"晴天","女",19)); list.add(new Employee(102,"雨天","女",18)); list.add(new Employee(103,"阴天","女",18)); list.add(new Employee(103,"阴天","女",18)); list.add(new Employee(104,"多云","男",28)); list.add(new Employee(105,"冰雹","男",33)); return list; } }
package com.Guru99_2021.testCases; import com.Guru99_2021.base.BaseClass; import com.Guru99_2021.pages.LoginPage; import com.Guru99_2021.utilities.Reporting; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners({Reporting.class}) public class LoginPageTest extends BaseClass { public static LoginPage loginPage; public static WebDriver driver; public LoginPageTest(){ super(); } @BeforeTest public void setUp(){ initialization(); loginPage=new LoginPage(driver); } @Test(priority = 0) public void testuserIDField(){ loginPage.setUserIDField(properties.getProperty("userID")); logger.info("userID entered"); } @Test(priority = 1) public void testpasswordField(){ loginPage.setPasswordField(properties.getProperty("password")); logger.info("password entered"); } @Test(priority = 2) public void testloginButton(){ loginPage.setLoginButton(); logger.info("login Button successfully clicked"); } }
package com.lesports.albatross.adapter.compertition; import android.content.Context; import android.graphics.Color; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.lesports.albatross.R; import com.lesports.albatross.entity.compertition.LiveStream; import com.lesports.albatross.utils.ViewHolder; import java.util.List; /** * 直播适配器 * Created by zhouchenbin on 16/6/24. */ public class LivesAdapter extends BaseAdapterNew<LiveStream>{ private final String UNSTART ="UNSTART",END ="END"; public LivesAdapter(Context context, List<LiveStream> mDatas) { super(context, mDatas); } private int selectedPosition = 0; @Override protected int getResourceId(int i) { // if(i%2==0) // // return R.layout.rase_detail_tab_detail_live_list_leftitem; // else // return R.layout.rase_detail_tab_detail_live_list_rightitem; return R.layout.live_stream_item; } //R.layout.live_stream_item item //R.drawable.comp_detail_record_pre 选中状态 //R.drawable.comp_detail_record_nor 正常状态 @Override protected void setViewData(View view, int position) { LiveStream livesEntity = getItem(position); // TextView liveName = ViewHolder.get(view, R.id.live_name); // ImageView liveImg = ViewHolder.get(view,R.id.img_liv); // ViewGroup liveBox = ViewHolder.get(view, R.id.live_box); // ImageView vipLabel = ViewHolder.get(view, R.id.member_label); //只有一个直播流的名字 ,更改背景和字体颜色 TextView liveName = ViewHolder.get(view, R.id.live_streams_name); if (TextUtils.isEmpty(livesEntity.getLiveName())) liveName.setText("视频直播" ); else liveName.setText(livesEntity.getLiveName()); if (selectedPosition == position) { // 选中 liveName.setTextColor(Color.parseColor("#ffffff")); liveName.setBackgroundResource(R.drawable.comp_detail_record_pre); }else { //为选中 liveName.setTextColor(Color.parseColor("#999999")); liveName.setBackgroundResource(R.drawable.comp_detail_record_nor); } //因为livesEntity.getLiveStatus()为字符串 // // if (UNSTART.equals(livesEntity.getLiveStatus())){ // liveName.setTextColor(Color.parseColor("#cccccc")); // liveBox.setBackgroundResource(R.drawable.match_detail_ic_box_unuse); // liveImg.setImageResource(R.drawable.match_detail_ic_livestream_unuse); // }else { // if(selectedPosition!=position) { // liveName.setTextColor(context.getResources().getColorStateList(R.color.color_selector_666666_to_color)); // liveImg.setImageResource(R.drawable.match_detail_ic_livestream_selector); // liveBox.setBackgroundResource(R.drawable.match_detail_ic_box_selector); // } // else { // liveName.setTextColor(Color.WHITE); // liveImg.setImageResource(R.drawable.match_detail_ic_livestream_hl); // liveBox.setBackgroundResource(R.drawable.match_detail_ic_box_hl); // } // } // switch (livesEntity.getLiveStatus()) { // case 1:// ""://位开始 // //// if(livesEntity.getIsPay()) // 会员付费 //// { //// vipLabel.setVisibility(View.VISIBLE); //// vipLabel.setImageResource(R.drawable.match_live_member_label_unactive); //// } //// else //// { //// vipLabel.setVisibility(View.GONE); //// } // break; // case ""://正在播放 // //// if(livesEntity.getIsPay()) // 会员付费 //// { //// vipLabel.setVisibility(View.VISIBLE); //// vipLabel.setImageResource(R.drawable.match_live_member_label_active); //// } //// else //// { // vipLabel.setVisibility(View.GONE); //// } // /* liveName.setTextColor(Color.parseColor("#29c4c6")); // liveImg.setVisibility(View.VISIBLE);*/ // break; // } } public void setSelectedPosition(int position){ selectedPosition = position; notifyDataSetChanged(); } }
package com.project.ship.rooms; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.project.CrewAction; import com.project.ResourceLoader; import com.project.RoomSize; import com.project.ship.Room; import com.project.ship.Ship; import com.project.weapons.Weapon; public class WeaponsRoom extends Room { /*back and front in one list*/ private List<Weapon> weapons = new ArrayList<>(); private List<Weapon> frontWeapons = new ArrayList<>(); private List<Weapon> backWeapons = new ArrayList<>(); public WeaponsRoom(Weapon[] we,String name,int actionHealth, int damageableRadius, RoomSize size, Ship ship) { super(name,actionHealth,getNoOfActions(we),size,ship); this.setDamageableRadius(damageableRadius); weapons = (ArrayList<Weapon>) Arrays.asList(we); } public WeaponsRoom(List<Weapon> frontWeapons,List<Weapon> backWeapons,String name,int actionHealth, int noOfActions, int damageableRadius, RoomSize size, Ship ship) { super(name,actionHealth,getNoOfActions(frontWeapons)+getNoOfActions(backWeapons),size, ship); this.frontWeapons=frontWeapons; this.backWeapons =backWeapons ; this.setDamageableRadius(damageableRadius); weapons.addAll(backWeapons); weapons.addAll(frontWeapons); } public static int getNoOfActions(Weapon[] weapons){ int noOfActions = 0; for(int i = 0;i<weapons.length;i++){ noOfActions+=weapons[i].getActions().size(); } return noOfActions; } public static int getNoOfActions(List<Weapon> weapons){ int noOfActions = 0; for(int i = 0;i<weapons.size();i++){ noOfActions+=weapons.get(i).getActions().size(); } return noOfActions; } @Override protected CrewAction getLeastDependantAction() { /*consolidate all actions*/ List<CrewAction> allActions = new ArrayList<CrewAction>(); for(int i = 0;i<weapons.size();i++){ for(CrewAction action : weapons.get(i).getActions()){ if(!action.isBroken()){ allActions.add(action); } } } /*Set smallest as null*/ int smallest = Integer.MAX_VALUE; CrewAction leastDependant = null; /*Loop through and search for the smallest*/ for(CrewAction action : allActions){ /*Update smallest value*/ if(action.getActionsNeededAfterUse().size() < smallest){ smallest = action.getActionsNeededAfterUse().size(); leastDependant = action; /*Break on 0 as you can't get smaller than it*/ if(smallest == 0){ break; } } } return leastDependant; } @Override protected boolean ActionsLeft() { for(Weapon weapon : weapons){ for(CrewAction action : weapon.getActions()){ if(!action.isBroken()){ return true; } } } return false; } public void UseRoom() { } public BufferedImage getIcon() { return ResourceLoader.getImage("res/roomIcons/weaponsRoomIcon.png"); } public ArrayList<String> getOptions() { for(int i = 0;i<weapons.size();i++) { } return null; } public List<Weapon> getWeapons() { return weapons; } public void setWeapons(ArrayList<Weapon> weapons) { this.weapons = weapons; } public List<Weapon> getFrontWeapons() { return frontWeapons; } public void setFrontWeapons(List<Weapon> frontWeapons) { this.frontWeapons = frontWeapons; } public List<Weapon> getBackWeapons() { return backWeapons; } public void setBackWeapons(List<Weapon> backWeapons) { this.backWeapons = backWeapons; } }
package com.gsccs.sme.plat.svg.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gsccs.sme.api.domain.StatistGovNum; import com.gsccs.sme.api.domain.base.Attach; import com.gsccs.sme.plat.auth.service.SmsService; import com.gsccs.sme.plat.auth.service.UserService; import com.gsccs.sme.plat.svg.dao.AppealAttachTMapper; import com.gsccs.sme.plat.svg.dao.AppealItemTMapper; import com.gsccs.sme.plat.svg.dao.AppealPushTMapper; import com.gsccs.sme.plat.svg.dao.AppealTopicTMapper; import com.gsccs.sme.plat.svg.dao.AppealTraceTMapper; import com.gsccs.sme.plat.svg.model.AppealAttachT; import com.gsccs.sme.plat.svg.model.AppealAttachTExample; import com.gsccs.sme.plat.svg.model.AppealItemT; import com.gsccs.sme.plat.svg.model.AppealItemTExample; import com.gsccs.sme.plat.svg.model.AppealPushT; import com.gsccs.sme.plat.svg.model.AppealPushTExample; import com.gsccs.sme.plat.svg.model.AppealTopicT; import com.gsccs.sme.plat.svg.model.AppealTopicTExample; import com.gsccs.sme.plat.svg.model.AppealTraceT; import com.gsccs.sme.plat.svg.model.AppealTraceTExample; /** * 项目申报业务实现类 * * @创建时间:2016.3.1 */ @Service(value = "appealService") public class AppealServiceImpl implements AppealService { @Autowired private AppealItemTMapper appealItemTMapper; @Autowired private AppealTopicTMapper appealTopicTMapper; @Autowired private AppealAttachTMapper appealAttachTMapper; @Autowired private AppealTraceTMapper appealTraceTMapper; @Autowired private AppealPushTMapper appealPushTMapper; @Autowired private SmsService smsService; @Autowired private UserService userService; public void insertTopic(AppealTopicT topicT) { if (null == topicT) { return; } topicT.setAddtime(new Date()); appealTopicTMapper.insert(topicT); if (null != topicT.getAttachs() && topicT.getAttachs().size() > 0) { for (Attach attach : topicT.getAttachs()) { AppealAttachT attachT = new AppealAttachT(); attachT.setTopicid(topicT.getId()); attachT.setFilename(attach.getFilename()); attachT.setFilepath(attach.getFilepath()); attachT.setFiletype(attach.getFiletype()); appealAttachTMapper.insert(attachT); } } } @Override public void updateTopic(AppealTopicT topicT) { if (null == topicT) { return; } appealTopicTMapper.updateByPrimaryKeyWithBLOBs(topicT); if (null != topicT.getAttachs() && topicT.getAttachs().size() > 0) { for (Attach attach : topicT.getAttachs()) { AppealAttachT attachT = new AppealAttachT(); attachT.setTopicid(topicT.getId()); attachT.setFilename(attach.getFilename()); attachT.setFilepath(attach.getFilepath()); attachT.setFiletype(attach.getFiletype()); saveAttach(attachT); } } } public void saveAttach(AppealAttachT attachT){ if (null ==attachT){ return; } AppealAttachTExample example = new AppealAttachTExample(); AppealAttachTExample.Criteria c = example.createCriteria(); c.andFilenameEqualTo(attachT.getFilename()); List<AppealAttachT> list = appealAttachTMapper.selectByExample(example); if (null != list && list.size()>0){ return; }else{ appealAttachTMapper.insert(attachT); } } @Override public void delTopics(List<Long> ids) { AppealTopicTExample example = new AppealTopicTExample(); AppealTopicTExample.Criteria c = example.createCriteria(); c.andIdIn(ids); appealTopicTMapper.deleteByExample(example); } @Override public AppealTopicT findTopicById(Long id) { AppealTopicT topicT = appealTopicTMapper.selectByPrimaryKey(id); if (null != topicT) { List<AppealAttachT> attachTs = findTopicAttachs(id); if (null != attachTs && attachTs.size() > 0) { List<Attach> attachs = new ArrayList<>(); for (AppealAttachT attachT : attachTs) { Attach attach = new Attach(); attach.setId(attachT.getId().toString()); attach.setFilename(attachT.getFilename()); attach.setFilepath(attachT.getFilepath()); attach.setFiletype(attachT.getFiletype()); attachs.add(attach); } topicT.setAttachs(attachs); } } return topicT; } public List<AppealAttachT> findTopicAttachs(Long topicid) { if (null != topicid) { AppealAttachTExample example = new AppealAttachTExample(); AppealAttachTExample.Criteria c = example.createCriteria(); c.andTopicidEqualTo(topicid); c.andItemidIsNull(); return appealAttachTMapper.selectByExample(example); } return null; } public List<AppealAttachT> findItemAttachs(Long itemid) { if (null != itemid) { AppealAttachTExample example = new AppealAttachTExample(); AppealAttachTExample.Criteria c = example.createCriteria(); c.andItemidEqualTo(itemid); return appealAttachTMapper.selectByExample(example); } return null; } @Override public void insertItem(AppealItemT itemT) { if (null == itemT) { return; } itemT.setStatus("0"); // 已提交 itemT.setPushnum(0); itemT.setAddtime(new Date()); appealItemTMapper.insert(itemT); if (null != itemT.getAttachs() && itemT.getAttachs().size() > 0) { for (Attach attach : itemT.getAttachs()) { AppealAttachT attachT = new AppealAttachT(); attachT.setItemid(itemT.getId()); attachT.setTopicid(itemT.getTopicid()); attachT.setFilename(attach.getFilename()); attachT.setFilepath(attach.getFilepath()); attachT.setFiletype(attach.getFiletype()); appealAttachTMapper.insert(attachT); } } // 保存轨迹 AppealTraceT traceT = new AppealTraceT(); traceT.setContent("提交事项申请"); traceT.setItemid(itemT.getId()); traceT.setCorpid(itemT.getCorpid()); traceT.setStatus("1"); this.insertTrace(traceT); //发送短信 //smsService.sendMsg(itemT.getSvgid(), "您有新的申请,请尽快登录平台受理!"); } @Override public void updateItem(AppealItemT itemT) { if (null != itemT) { itemT.setEndtime(new Date()); appealItemTMapper.updateByPrimaryKeySelective(itemT); if (null != itemT.getAttachs() && itemT.getAttachs().size() > 0) { for (Attach attach : itemT.getAttachs()) { AppealAttachT attachT = new AppealAttachT(); attachT.setItemid(itemT.getId()); attachT.setTopicid(itemT.getTopicid()); attachT.setFilename(attach.getFilename()); attachT.setFilepath(attach.getFilepath()); attachT.setFiletype(attach.getFiletype()); appealAttachTMapper.insert(attachT); } } if(null != itemT.getStatus() && itemT.getStatus().equals("2")){ //发送短信 smsService.sendMsg(itemT.getCorpid(), "您的申请已受理,请尽快登录平台确认!"); } } } @Override public void delItems(List<Long> ids) { AppealAttachTExample example1 = new AppealAttachTExample(); AppealAttachTExample.Criteria c1 = example1.createCriteria(); c1.andItemidIn(ids); appealAttachTMapper.deleteByExample(example1); AppealItemTExample example = new AppealItemTExample(); AppealItemTExample.Criteria c = example.createCriteria(); c.andIdIn(ids); appealItemTMapper.deleteByExample(example); } @Override public void delAttachs(List<Long> ids) { AppealAttachTExample example = new AppealAttachTExample(); AppealAttachTExample.Criteria c = example.createCriteria(); c.andIdIn(ids); appealAttachTMapper.deleteByExample(example); } @Override public AppealItemT findItemById(Long id) { AppealItemT itemT = appealItemTMapper.selectByPrimaryKey(id); if (null != itemT) { List<AppealAttachT> attachTs = findItemAttachs(id); List<Attach> attachs = new ArrayList<>(); for (AppealAttachT attachT : attachTs) { Attach attach = new Attach(); attach.setId(attachT.getId().toString()); attach.setFilename(attachT.getFilename()); attach.setFilepath(attachT.getFilepath()); attach.setFiletype(attachT.getFiletype()); attachs.add(attach); } itemT.setAttachs(attachs); } return itemT; } @Override public List<AppealTopicT> find(AppealTopicT topicT, String order, int page, int pageSize) { AppealTopicTExample example = new AppealTopicTExample(); AppealTopicTExample.Criteria criteria = example.createCriteria(); proSearchParam(topicT, criteria); example.setCurrPage(page); example.setPageSize(pageSize); return appealTopicTMapper.selectPageByExample(example); } @Override public int count(AppealTopicT topicT) { AppealTopicTExample example = new AppealTopicTExample(); AppealTopicTExample.Criteria criteria = example.createCriteria(); proSearchParam(topicT, criteria); return appealTopicTMapper.countByExample(example); } @Override public List<AppealItemT> find(AppealItemT itemT, String order, int page, int pageSize) { AppealItemTExample example = new AppealItemTExample(); AppealItemTExample.Criteria criteria = example.createCriteria(); proSearchParam(itemT, criteria); if (order != null && order.trim().length() > 0) { example.setOrderByClause(order); } example.setCurrPage(page); example.setPageSize(pageSize); return appealItemTMapper.selectPageByExample(example); } @Override public int count(AppealItemT itemT) { AppealItemTExample example = new AppealItemTExample(); AppealItemTExample.Criteria criteria = example.createCriteria(); proSearchParam(itemT, criteria); return appealItemTMapper.countByExample(example); } @Override public List<AppealAttachT> find(AppealAttachT param) { AppealAttachTExample example = new AppealAttachTExample(); AppealAttachTExample.Criteria criteria = example.createCriteria(); proSearchParam(param, criteria); return appealAttachTMapper.selectByExample(example); } @Override public List<AppealTraceT> find(Long appealid) { if (null != appealid) { AppealTraceTExample example = new AppealTraceTExample(); AppealTraceTExample.Criteria c = example.createCriteria(); c.andItemidEqualTo(appealid); return appealTraceTMapper.selectByExample(example); } return null; } @Override public void insertTrace(AppealTraceT traceT) { if (null != traceT) { traceT.setAddtime(new Date()); appealTraceTMapper.insert(traceT); } } @Override public void insertAppealPush(AppealPushT pushT) { if (null != pushT) { pushT.setAddtime(new Date()); appealPushTMapper.insert(pushT); } } @Override public AppealPushT findAppealPushById(Long id) { return appealPushTMapper.selectByPrimaryKey(id); } @Override public List<AppealPushT> find(AppealPushT param) { AppealPushTExample example = new AppealPushTExample(); AppealPushTExample.Criteria criteria = example.createCriteria(); proSearchParam(param, criteria); return appealPushTMapper.selectByExample(example); } public void proSearchParam(AppealTopicT topicT, AppealTopicTExample.Criteria criteria) { if (null != topicT) { if (null != topicT.getSvgid()) { criteria.andSvgidEqualTo(topicT.getSvgid()); } if (null != topicT.getScode()) { criteria.andScodeEqualTo(topicT.getScode()); } if (null != topicT.getSubscode()) { criteria.andSubscodeEqualTo(topicT.getSubscode()); } } } public void proSearchParam(AppealItemT itemT, AppealItemTExample.Criteria criteria) { if (null != itemT) { if (null != itemT.getCorpid()) { criteria.andCorpidEqualTo(itemT.getCorpid()); } if (null != itemT.getTopicid()) { criteria.andTopicidEqualTo(itemT.getTopicid()); } if (null != itemT.getStatus()) { criteria.andStatusEqualTo(itemT.getStatus()); } if (null != itemT.getSvgid()) { criteria.andSvgidEqualTo(itemT.getSvgid()); } } } public void proSearchParam(AppealAttachT attachT, AppealAttachTExample.Criteria criteria) { if (null != attachT) { if (null != attachT.getCorpid()) { criteria.andCorpidEqualTo(attachT.getCorpid()); } if (null != attachT.getItemid()) { criteria.andItemidEqualTo(attachT.getItemid()); } } } public void proSearchParam(AppealPushT param, AppealPushTExample.Criteria criteria) { if (null != param) { if (null != param.getItemid()) { criteria.andItemidEqualTo(param.getItemid()); } if (null != param.getTopicid()) { criteria.andTopicidEqualTo(param.getTopicid()); } if (null != param.getSvgid()) { criteria.andSvgidEqualTo(param.getSvgid()); } if (null != param.getTasktype()) { criteria.andTasktypeEqualTo(param.getTasktype()); } } } @Override public List<StatistGovNum> statistSvgAppealNum() { return appealItemTMapper.selectStatBySvg(); } }
package com.lti.StringBuffer; /** * Created by busis on 2020-12-03. */ public class StrBuffer { public static void main(String[] args) { StringBuffer sb=new StringBuffer(); //can be empty sb.append("Hello"); sb.append(" World"); System.out.println(sb); sb.delete(0,2); //Deletes 0,1 System.out.println(sb); sb.reverse(); //reverse sb.insert(1,"jj"); //insert at 1 position System.out.println(sb); StringBuffer sb2=new StringBuffer("Hello"); StringBuffer sb3=new StringBuffer(sb2); sb3.append(" | " + sb2.reverse()); System.out.println(sb3); } }
package bspq21_e4.ParkingManagement.client.gui; import bspq21_e4.ParkingManagement.client.gui.*; import bspq21_e4.ParkingManagement.server.data.PremiumUser; import bspq21_e4.ParkingManagement.server.data.Slot; import bspq21_e4.ParkingManagement.server.rsh.PremiumUserRSH; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Locale; import java.util.ResourceBundle; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @class RegisterWindow Window which allows registering premium users * @author BSPQ21-E4 */ public class RegisterWindow extends JFrame { public JTextField tfEmail; public JTextField tfPlate; private JLabel lbEmail; private JLabel lbPlate; private JPanel panelContenidos; private JLabel lb; private Thread hilo; private static ResourceBundle resourceBundle; final Logger logger = LoggerFactory.getLogger(RegisterWindow.class); /** * Creating the application. */ public RegisterWindow() { setResizable(false); resourceBundle = ResourceBundle.getBundle("SystemMessages", Locale.getDefault()); initialize(); } public ResourceBundle getResourceBundle() { return resourceBundle; } /** * Initializing the contents of the frame. */ public void initialize() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setBounds(100, 100, 500, 250); this.setMinimumSize(new Dimension(750, 500)); panelContenidos = new JPanel(); panelContenidos.setBackground(Color.WHITE); setContentPane(panelContenidos); panelContenidos.setLayout(new BorderLayout(15, 15)); //Panel Central JPanel panelCentral = new JPanel(); panelCentral.setBackground(Color.WHITE); panelCentral.setLayout(new GridLayout(2, 2)); panelContenidos.add(panelCentral, BorderLayout.CENTER); //Panel Inferior JPanel panelInferior = new JPanel(); panelInferior.setBackground(Color.white); panelInferior.setLayout(new GridLayout(1, 3)); panelContenidos.add(panelInferior, BorderLayout.SOUTH); JButton btnVolver = new JButton(getResourceBundle().getString("return")); btnVolver.setForeground(Color.WHITE); btnVolver.setBackground(new Color(72, 61, 139)); /** * This action listener is related with the return button When this button is * clicked this window will be closed and the authorization or logging window * will be displayed again * * @see bspq21_e4.ParkingManagement.client.gui.AuthWindow */ btnVolver.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub AuthWindow frame = new AuthWindow(); frame.setVisible(true); dispose(); } }); JButton btnRegister = new JButton(getResourceBundle().getString("register")); btnRegister.setForeground(Color.WHITE); btnRegister.setBackground(new Color(72, 61, 139)); /** * This action listener is related with the register button When this button is * clicked a new Premium user will be created and stored in the DB * * @see bspq21_e4.ParkingManagement.server.rsh.PremiumUserRSH */ btnRegister.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String email = tfEmail.getText(); String plate = tfPlate.getText(); PremiumUser user = new PremiumUser(); user.setEmail(email); user.setPlate(plate); user.setMonthfee(100); PremiumUserRSH.getInstance().savePremiumUsers(user); // try { // Thread.sleep(3000); // } catch (Exception e1) { // e1.printStackTrace(); // } List<PremiumUser> listaComprobacion = PremiumUserRSH.getInstance().checkPremiumUsers(); boolean encontrado = false; for (PremiumUser u : listaComprobacion) { if (u.getPlate().equals(user.getPlate())) { JOptionPane.showMessageDialog(null, getResourceBundle().getString("guestUserFirstTime")); logger.info(getResourceBundle().getString("guestUserFirstTime")); AuthWindow v = new AuthWindow(); v.setVisible(true); dispose(); encontrado = true; break; } } if (encontrado != true) { JOptionPane.showMessageDialog(null, getResourceBundle().getString("error")); logger.info(getResourceBundle().getString("error")); } } }); JButton btnClose = new JButton(getResourceBundle().getString("close")); btnClose.setForeground(Color.WHITE); btnClose.setBackground(new Color(72, 61, 139)); /** * This action listener is related with the close button When this button is * clicked the window will be closed and the program ends */ btnClose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); lbEmail = new JLabel(getResourceBundle().getString("email")); lbPlate = new JLabel(getResourceBundle().getString("plate")); tfEmail = new JTextField(); tfPlate = new JTextField(); panelCentral.add(lbEmail); panelCentral.add(tfEmail); panelCentral.add(lbPlate); panelCentral.add(tfPlate); panelInferior.add(btnClose); panelInferior.add(btnRegister); panelInferior.add(btnVolver); } }
/* * Copyright 2020 WeBank * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.wedatasphere.schedulis.exec.execapp; import azkaban.execapp.FlowRunner; import azkaban.execapp.JobRunner; import azkaban.executor.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory; import java.util.Set; import static azkaban.Constants.FAILED_PAUSED_CHECK_TIME_MS; import static azkaban.Constants.FAILED_PAUSED_MAX_WAIT_MS; public class KillFlowTrigger extends Thread { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(KillFlowTrigger.class); private final Logger logger; private FlowRunner flowRunner; private long timeOut; private final Object monitor = new Object(); private long waitTime; private long interval; public KillFlowTrigger(FlowRunner flowRunner, Logger logger) { this.flowRunner = flowRunner; this.interval = flowRunner.getAzkabanProps().getLong(FAILED_PAUSED_MAX_WAIT_MS, 1 * 60 * 60 * 1000); this.waitTime = flowRunner.getAzkabanProps().getLong(FAILED_PAUSED_CHECK_TIME_MS, 1 * 60 * 1000); this.timeOut = System.currentTimeMillis() + this.interval; this.logger = logger; } private void updateTime(){ this.timeOut = System.currentTimeMillis() + interval; } @Override public void run() { logger.warn("作业流已暂停, 当作业流没有可运行任务时,在" + this.interval / 1000 + "秒后该作业将会被终止运行."); try { while (true) { synchronized (monitor) { if (hasActiveJob()) { LOGGER.debug("execId:{}, has active job , update time." , flowRunner.getExecutionId()); updateTime(); } if (System.currentTimeMillis() >= this.timeOut) { if (flowRunner != null && !flowRunner.isKilled() && !flowRunner.isFlowFinished()) { logger.warn("workflow timeout termination, execId:" + this.flowRunner.getExecutionId()); flowRunner.kill(); } break; } monitor.wait(waitTime); } } } catch (InterruptedException ie) { logger.info("cancel kill workflow, execId: " + this.flowRunner.getExecutionId()); } } public void stopKillFLowTrigger(){ this.interrupt(); } private boolean hasActiveJob(){ Set<JobRunner> activeJobs = flowRunner.getActiveJobRunners(); if(activeJobs.isEmpty()){ return false; } for(JobRunner jobRunner: activeJobs){ if(!jobRunner.getStatus().equals(Status.FAILED_WAITING)){ return true; } } return false; } }
package net.yosi.isageek.atomiclauncher.ui; import com.mojang.minecraftpe.Minecraft_Market; public class LauncherActivity extends Minecraft_Market { }
import java.util.Random; /** * Created by Гамзат on 01.06.2017. * * Урок 29 - Подсчет количества выпадений числа в рулетке (массив) */ public class Bender { public static void main(String[] args) { Random roulette = new Random(); int num[] = new int[33]; int sum = 0; // Суммирование выпадающих чисел. for (int i = 0; i < 1000; i++){ ++num[roulette.nextInt(33)]; } System.out.println("Номер\tЧисло"); // Вывод массива. for (int i = 0; i < num.length; i++){ System.out.println(i + "\t\t" + num[i]); sum += num[i]; } // Вывод System.out.println("--------------------------"); System.out.println("Проверка"); System.out.println("Сумма равно: " + sum); System.out.println("--------------------------"); } }
import java.util.ArrayList; import java.util.List; public class Cart { List<String> items; public Cart(){ items = new ArrayList<String>(); } //method adding items to the basket public void add(String item) { items.add(item); } // method checking the size - quantity of items in the basket public int getTotal() { return items.size(); } // method checking if the basket contains added items public Boolean contain(String itemName) { return items.contains(itemName); } // method checking the total price for the basket public Double checkout() { double total = 0; for(String item: items){ if(item.equals("Apples")){ total += 0.6; }else if(item.equals("Oranges")){ total += 0.25; } } return total; } }
package com.tech.interview.siply.redbus.service.contract; import com.tech.interview.siply.redbus.entity.dto.DriverDTO; import java.util.List; import java.util.UUID; public interface DriverService { String addDriver(DriverDTO driverDTO); void deleteDriverUser(UUID id); DriverDTO getDriverById(UUID id); List<DriverDTO> getAllDriverUsers(); }
package com.mmall.controller; import com.mmall.dao.UserMapper; import com.sun.jmx.snmp.Timestamp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; /** * Created by zhang on 2018/3/26. */ @Controller @RequestMapping(value = "/test") public class TestController { @Autowired private UserMapper userMapper; private static final Logger logger = LoggerFactory.getLogger(TestController.class); public static void main(String[] args) { //Timestamp a = new Timestamp(System.currentTimeMillis()); Timestamp a = new Timestamp(System.currentTimeMillis()); System.out.println(a); Date c = new Date(); System.out.println(c); } @RequestMapping(value = "test.do") @ResponseBody public String test(String str){ logger.info("testinfo"); logger.warn("testwarm"); logger.error("testerror"); return "张洪涛是好人:506震惊部"; } }
package 数据结构.线性结构.线性表; /** * Created by Yingjie.Lu on 2018/8/30. */ /** * @Title: 通过链表实现的线性表 * @Date: 2018/8/30 9:21 */ public class MyLinkedList { private Node first=new Node(null); private Node last=new Node(null); private int size=0; public int size(){ return size; } /** * @Title: 定义节点 * @Date: 2018/8/30 10:47 */ private class Node{ Object data;//数据 Node next;//下一个节点 Node(Object o){ this.data=o; } } /** * @Title: 添加一个元素 * @Date: 2018/8/30 10:46 */ public void add(Object o){ Node node=new Node(o); last.next=node;//将刚添加的节点与上个节点关联 last=node;//把刚添加的节点设置为最后一个节点 if(size==0){ first=last; } size++; } /** * @Title: 通过index获取一个元素 * @Date: 2018/8/30 10:47 */ public Object get(int index){ if(index>=size()){//如果index大于所有的总个数,那么直接返回null return null; } Node node=first; for(int i=0;i<index;i++){ node=node.next; } return node.data; } /** * @Title: 删除一个元素 * @Date: 2018/8/30 10:48 */ public boolean remove(int index){ if(index>=size()){//如果index大于所有的总个数,那么直接返回null return false; } Node node=first; for(int i=0;i<index;i++){ if(i==index-2){ Node needDelete=node.next;//先将要删除的节点的地址保存起来 node.next=node.next.next;//直接将要删除的上一个节点的next指向要删除的节点的下一个节点 needDelete.next=null;//将要删除的节点的next设置为null size--; break; } node=node.next; } return true; } /** * @Title: 通过index更新一个元素 * @Date: 2018/8/30 11:13 */ public boolean update(int index,Object o){ if(index>=size()){//如果index大于所有的总个数,那么直接返回null return false; } Node node=first; Node needUpdate=new Node(o); for(int i=0;i<index;i++){ if(i==index-2){ Node needDelete=node.next;//先将要删除的节点的地址保存起来 needUpdate.next=node.next.next;//将要更新节点的next指向要删除的节点的下一个节点 node.next=needUpdate;//将要删除的上一个节点的next指向要更新节点 needDelete.next=null;//将要删除的节点的next设置为null break; } node=node.next; } return true; } /** * @Title: 获取第一个元素 * @Date: 2018/8/30 10:47 */ public Object getFirst(){ return first.data; } /** * @Title: 获取最后一个元素 * @Date: 2018/8/30 10:47 */ public Object getLast(){ return last.data; } public static void main(String[] args){ MyLinkedList linkedList=new MyLinkedList(); for(int i=0;i<10;i++){ linkedList.add(i); } linkedList.remove(5); linkedList.update(3,4); for(int i=0;i<linkedList.size();i++){ System.out.println(linkedList.get(i)); } } }
package referencetype.sec02; public class ArraryCreateByNewExample { public static void main(String[] args) { int[] arr1 = new int[3]; for(int i=0; i<arr1.length; i++) { System.out.println("arr1[" + i + "] : " + arr1[i]); } arr1[0] = 10; arr1[1] = 20; arr1[2] = 30; System.out.println("------------"); for(int i=0; i<arr1.length; i++) { System.out.println("arr1[" + i + "] : " + arr1[i]); } System.out.println("------------"); double[] arr2 = new double[3]; for(int i=0; i<arr2.length; i++) { System.out.println("arr2[" + i +"] : " + arr2[i]); } arr2[0] = 10.1; arr2[1] = 20.2; arr2[2] = 30.3; System.out.println("-----------"); for(int i=0; i<arr2.length; i++) { System.out.println("arr2[" + i +"] : " + arr2[i]); } System.out.println("-----------"); String[] arr3 = new String[3]; for(int i=0; i<arr3.length; i++) { System.out.println("arr3[" + i + "] : " + arr3[i]); } System.out.println("-----------"); arr3[0] = "1월"; arr3[1] = "2월"; arr3[2] = "3월"; for(int i=0; i<arr3.length; i++) { System.out.println("arr3[" + i + "] : " + arr3[i]); } } }
package ru.cft.focusstart.task2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; public class ModelFigureTypeWithParameters { private static final Logger log = LoggerFactory.getLogger(ModelFigureTypeWithParameters.class.getName()); private String figureType; private ArrayList<Double> parameters; public ModelFigureTypeWithParameters(String figureType, ArrayList<Double> parameters) { this.figureType = figureType; this.parameters = parameters; log.info("Создали экземпляр класса: {}", ModelFigureTypeWithParameters.class.getName()); } public String getFigureType() { return figureType; } public ArrayList<Double> getParameters() { return parameters; } }
package com.lidaye.shopIndex.domain.vo; import com.lidaye.shopIndex.domain.entity.Shop; import com.lidaye.shopIndex.domain.entity.ShopImage; import lombok.Data; import java.util.List; @Data public class ShopVo extends Shop { private List<ShopImage> shopImages; }
package test; import java.util.Arrays; import java.util.Collections; public class Bio { Integer[] L = {2,2,3,3,4,5,6,7,8}; Integer[] X = {0,10}; int y=2; public static void partialDigest(Integer[] L ){ int max = Collections.max(Arrays.asList(L));//5 Integer[] Lnew = new Integer[L.length-max]; Integer[] X= {0,max}; } public static void place(int[] L,int[] X){ } public static void delta(int y, int[]X){ } // def partialDigest(L): // width=max(L) // L.remove(width) // X=[0,width] // Place(L,X) // // // def Place(L,X): // if (len(L)==0): // print(X) // return // y=max(L) // dyX=delta(y,X) // if (set(dyX).issubset(L)): // X.append(y) // for x1 in dyX: // L.remove(x1) // Place(L,X) // X.remove(y) // for x2 in dyX: // L.append(x2) // w=max(X)-y // dwX=delta(w,X) // if (set(dwX).issubset(L)): // X.append(w) // for x1 in dwX: // L.remove(x1) // Place(L,X) // X.remove(w) // for x2 in dwX: // L.append(x2) // return // // // def delta(y,X): // D=[] // for i in range(len(X)): // t=abs(y-X[i]) // D.append(t) // return D // // L=[2,2,3,3,4,5,6,7,8,10] // partialDigest(L) //#0 2 4 7 10 }
package fr.skytasul.quests.utils.types; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import fr.skytasul.quests.BeautyQuests; import fr.skytasul.quests.utils.DebugUtils; import fr.skytasul.quests.utils.compatibility.DependenciesManager; import fr.skytasul.quests.utils.compatibility.QuestsPlaceholders; public class Command { public final String label; public final boolean console; public final boolean parse; public final int delay; public Command(String label, boolean console, boolean parse, int delay) { this.label = label; this.console = console; this.parse = parse; this.delay = delay; } public void execute(Player o){ Runnable run = () -> { String formattedcmd = label.replace("{PLAYER}", o.getName()); if (parse && DependenciesManager.papi.isEnabled()) formattedcmd = QuestsPlaceholders.setPlaceholders(o, formattedcmd); CommandSender sender = console ? Bukkit.getConsoleSender() : o; Bukkit.dispatchCommand(sender, formattedcmd); DebugUtils.logMessage(sender.getName() + " performed command " + formattedcmd); }; if (delay == 0 && Bukkit.isPrimaryThread()) { run.run(); }else Bukkit.getScheduler().runTaskLater(BeautyQuests.getInstance(), run, delay); } public Map<String, Object> serialize(){ Map<String, Object> map = new HashMap<>(); map.put("label", label); map.put("console", console); if (parse) map.put("parse", parse); if (delay > 0) map.put("delay", delay); return map; } public static Command deserialize(Map<String, Object> map){ return new Command((String) map.get("label"), (boolean) map.get("console"), (boolean) map.getOrDefault("parse", Boolean.FALSE), (int) map.getOrDefault("delay", 0)); } }
package org.viqueen.java.bytecode.cpool; /** * CONSTANT_Float_info { * u1 tag; * u4 bytes; * } * @since 1.0.0 */ public class FloatInfo extends CPInfo { private final float value; public FloatInfo(float value) { super(Tag.FLOAT); this.value = value; } public float getValue() { return value; } }
package com.thinkdevs.cryptomarket.adapters; import android.content.Context; import android.os.Build; import androidx.appcompat.widget.AppCompatImageView; import androidx.recyclerview.widget.RecyclerView; import android.text.Html; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.thinkdevs.cryptomarket.R; import com.thinkdevs.cryptomarket.model.Notemodel; import java.util.Calendar; import java.util.List; import java.util.Locale; /** * Created by ABC on 9/3/2017. */ public class NoteRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int MENU_ITEM_VIEW_TYPE = 0; private static final int HEADER_ITEM_VIEW_TYPE = 1; // An Activity's Context. private final Context mContext; // The list of Native Express ads and menu items. private final List<Object> mRecyclerViewItems; private int mExpandedPosition=-1; public NoteRecyclerAdapter(Context context, List<Object> recyclerViewItems) { this.mContext = context; this.mRecyclerViewItems = recyclerViewItems; } public class HeaderHolder extends RecyclerView.ViewHolder{ TextView noteDate; View mView; public HeaderHolder(View itemView) { super(itemView); mView=itemView; noteDate=mView.findViewById(R.id.noteDate); } } public class NoteViewHolder extends RecyclerView.ViewHolder { View mView; AppCompatImageView ci; TextView nh,nb,nt; NoteViewHolder(View view) { super(view); mView=view; ci=(AppCompatImageView) mView.findViewById(R.id.noteFlag); nh=(TextView)mView.findViewById(R.id.noteTitle); nb=(TextView)mView.findViewById(R.id.noteBody); nt=(TextView)mView.findViewById(R.id.noteTime); } public void setIcon(String icon) { switch (icon){ case "PAYOUT": ci.setImageResource(R.drawable.ic_wallet); break; case "REFER": ci.setImageResource(R.drawable.ic_referral); break; default: ci.setImageResource(R.drawable.ic_notifications); } } public void setTitle(String title) { nh.setText(title); } public void setBody(String body) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { nb.setText(Html.fromHtml(body,Html.FROM_HTML_MODE_LEGACY)); } else nb.setText(Html.fromHtml(body)); } public void setTime(long time) { // nt.setText(DateUtils.getRelativeTimeSpanString(time,new Date().getTime(),DateUtils.SECOND_IN_MILLIS)); nt.setText(getTime(time)); } } @Override public int getItemCount() { return mRecyclerViewItems.size(); } /** * Determines the view type for the given position. */ @Override public int getItemViewType(int position) { if(mRecyclerViewItems.get(position).getClass()==Long.class) return HEADER_ITEM_VIEW_TYPE; else return MENU_ITEM_VIEW_TYPE; } /** * Creates a new view for a menu item view or a Native Express ad view * based on the viewType. This method is invoked by the layout manager. */ @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if(viewType==MENU_ITEM_VIEW_TYPE) { View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.notification_item, viewGroup, false); return new NoteViewHolder(menuItemLayoutView); } else { View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.header_sub, viewGroup, false); return new HeaderHolder(menuItemLayoutView); } } /** * Replaces the content in the views that make up the menu item view and the * Native Express ad view. This method is invoked by the layout manager. */ @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if(getItemViewType(position)==HEADER_ITEM_VIEW_TYPE) { HeaderHolder headerHolder= (HeaderHolder) holder; headerHolder.noteDate.setText(getDate((Long) mRecyclerViewItems.get(position))); } if (getItemViewType(position)==MENU_ITEM_VIEW_TYPE) { NoteViewHolder noteItemHolder = (NoteViewHolder) holder; Notemodel ep = (Notemodel) mRecyclerViewItems.get(position); final boolean isExpanded = position == mExpandedPosition; noteItemHolder.nb.setEllipsize(isExpanded ? null : TextUtils.TruncateAt.END); noteItemHolder.nb.setMaxLines(isExpanded ? Integer.MAX_VALUE : 1); noteItemHolder.itemView.setActivated(isExpanded); noteItemHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mExpandedPosition = isExpanded ? -1 : position; notifyDataSetChanged(); } }); noteItemHolder.setIcon(ep.getType()); noteItemHolder.setTitle(ep.getTitle()); noteItemHolder.setBody(ep.getBody()); noteItemHolder.setTime(ep.getTime()); } } private String getDate(long milliSeconds) { Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(milliSeconds); String date = DateFormat.format("dd MMMM ''yy", cal).toString(); return date; } private String getTime(long milliSeconds) { Calendar cal = Calendar.getInstance(Locale.ENGLISH); cal.setTimeInMillis(milliSeconds); String date = DateFormat.format("hh:mm a", cal).toString(); return date; } }
package walmartHomepage; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.BaseClass.BaseClass1; public class StoreAvailability { WebDriver driver; public StoreAvailability(WebDriver driver) { this.driver = driver; } public String Storeavailability1() { /*System.setProperty("webdriver.chrome.driver", "C:\\Users\\Arti\\workspace1\\walmart12\\Resources\\chromedriver.exe"); driver = new ChromeDriver();*/ driver.get("https://www.walmart.com/search/?query=laptop"); WebDriverWait wait1 = new WebDriverWait(driver, 30); wait1.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Store availability"))).click(); // enter zipcode senkeys 94538 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); WebElement zipcode = driver.findElement(By.xpath(".//*[@title='Enter zip code']")); zipcode.sendKeys("94538"); // click go button WebElement gobutton = driver.findElement(By.id("button")); gobutton.click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // display 5 stores for zipcode 94538 // driver.findElement(By.xpath(".//*[@title='all stores near // 94538']")).click(); // 5 matching nodes store .//*[@class='option option-small'] List<WebElement> stores = driver.findElements(By.xpath(".//*[@class='option option-small']")); System.out.println(stores.size()); for (WebElement ww : stores) { String storeTitle = ww.getAttribute("aria-label"); System.out.println(" print 5 locations " + storeTitle); // if (storeTitle.contains("Osgood Rd")) if (ww.getText().contains("Osgood Rd")) { System.out.println("Nearest store is Osgood"); // ww.getText()); break; } } return driver.getPageSource(); } }
package com.gxtc.huchuan.bean.dao; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; /** * Created by Gubr on 2017/3/15. * 课程推送 次数 保存 */ @Entity public class ChatPush { @Id private Long id; /** * 最后 推送的时间 保存到 */ private String date; /** * 推送次数 */ private int count; @Generated(hash = 450434780) public ChatPush(Long id, String date, int count) { this.id = id; this.date = date; this.count = count; } @Generated(hash = 563492952) public ChatPush() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getDate() { return this.date; } public void setDate(String date) { this.date = date; } public int getCount() { return this.count; } public void setCount(int count) { this.count = count; } }
package separateDigits; public class TestForLoop { public static void main(String[] args) { int lengthofIntegers = 3; int firstUserNum = 119; int secondUserNum = 911; int i; int sumDigits = 0; for (i = 0; i >= (-lengthofIntegers + 1); --i) { sumDigits = (int) ((Math.floor(firstUserNum * Math.pow(10, i) % 10) + (Math.floor(secondUserNum * Math.pow(10, i)) % 10))); System.out.println(sumDigits); } } }
/* * Created on 19/08/2008 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.citibank.ods.modules.product.prodassettype.action; import com.citibank.ods.common.action.BaseODSAction; import com.citibank.ods.common.action.BaseODSDetailAction; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.modules.product.prodassettype.functionality.ProdAssetTypeDetailFnc; import com.citibank.ods.modules.product.prodassettype.functionality.valueobject.ProdAssetTypeDetailFncVO; import com.citibank.ods.modules.product.prodqlfyprvt.functionality.ProdQlfyPrvtDetailFnc; import com.citibank.ods.modules.product.prodqlfyprvt.functionality.valueobject.ProdQlfyPrvtDetailFncVO; /** * @author rcoelho */ public class ProdAssetTypeDetailAction extends BaseODSDetailAction{ /* * Parte do nome do módulo ou ação */ private static final String C_SCREEN_NAME = "ProdAssetType.ProdAssetTypeDetail"; /** * @see com.citibank.ods.commom.action.BaseAction#getFncVOPublishName() */ public String getFncVOPublishName() { return ProdAssetTypeDetailFncVO.class.getName(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getODSFuncionality() */ protected BaseFnc getFuncionality() { return new ProdAssetTypeDetailFnc(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getScreenName() */ protected String getScreenName() { return C_SCREEN_NAME; } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#extraActions(com.citibank.ods.common.functionality.valueobject.BaseFncVO, * java.lang.String) */ protected String extraActions( BaseFncVO fncVO_, String invokePath_ ) { return null; } }
package com.project.android.app.kys.popup; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import com.project.android.app.kys.R; import com.project.android.app.kys.callbacks.ResponseListener; import com.project.android.app.kys.controller.AddInfoController; import com.project.android.app.kys.fragments.DepartmentFragment; import com.project.android.app.kys.fragments.DisciplineFragment; import com.project.android.app.kys.fragments.MajorFragment; import com.project.android.app.kys.helper.Util; public class AUMajorDialog extends DialogFragment { public View mView; public EditText mName; public EditText mInitials; public EditText mSummary; public DepartmentFragment mDepartmentFragment; public static AUMajorDialog mFragment; public static AUMajorDialog newInstance() { mFragment = new AUMajorDialog(); return mFragment; } public void setParentFragment(DepartmentFragment fragment) { this.mDepartmentFragment = fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); mView = inflater.inflate(R.layout.activity_add_major, null); initViews(mView); builder.setView(mView) // Add action buttons .setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { String name = mName.getText().toString(); String init = mInitials.getText().toString(); String summary = mSummary.getText().toString(); Integer deptId = mDepartmentFragment.mDepartmentID; if (Util.isNull(name) || Util.isNull(init) || Util.isNull(summary)) { String msg = getResources().getString(R.string.all_field_must_be_filled); Util.showLongToast(getActivity(), msg); } else { ResponseListener.getInstnace().setAddMajorListener(mFragment); AddInfoController.createInstance(getActivity()).addMajor(deptId, name, init, summary); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AUMajorDialog.this.getDialog().cancel(); } }); return builder.create(); } private void initViews(View view) { mName = (EditText) view.findViewById(R.id.add_major_name); mInitials = (EditText) view.findViewById(R.id.add_major_initials); mSummary = (EditText) view.findViewById(R.id.add_major_summary); } public void onResponse(String response) { Util.showLongToast(getActivity(), response); AUMajorDialog.this.getDialog().cancel(); } }
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; public class servlet2 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) // object of HttpServletResponse interface is response which will be send to the client,here res is a response throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); ServletContext sc = getServletContext(); // getServletContext() method of GenericServlet class returns the object of ServletContext. //HttpServlet class extends the GenericServlet class ,therefore,getServletContext() method is also a method of HttpServlet class which can be call by another method(doGet() or doPost() ) of the HttpServlet class without using any object . as we know method of one class can call another method of same class without using any object String str=sc.getInitParameter("name"); pw.println("value of parameter in configutation file(web.xml) is:"+str); } }
package graficos; import javax.swing.JFrame; import java.awt.event.*; public class EventoVentana { public static void main(String[] args) { MarcoVentana mimarco=new MarcoVentana(); mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//cierra la venta y el programa MarcoVentana mimarco2=new MarcoVentana(); mimarco2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//cierra solo la ventan el programa sigue activo mimarco.setTitle("Ventana 1"); mimarco2.setTitle("Ventana 2"); mimarco.setBounds(300, 300, 500, 350); mimarco2.setBounds(0, 0, 500, 350); } } class MarcoVentana extends JFrame{ public MarcoVentana(){ //setTitle("Respondiendo"); //setBounds(300, 300, 500, 350); setVisible(true); //M_Ventana oyente_ventana=new M_Ventana(); //addWindowListener(oyente_ventana); addWindowListener(new M_Ventana()); } } class M_Ventana extends WindowAdapter{//Ereda de window adapter para poder tener acceso a los metodos de la interfasce Action Listener @Override public void windowIconified(WindowEvent e) { // metodo que actua al minimiazar el MarcoVentana System.out.println("Ventana minimizada"); } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub System.out.println("Ventana Abierta"); } }
package be.openclinic.adt; import be.openclinic.common.OC_Object; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; import be.mxs.common.util.system.ScreenHelper; import net.admin.Service; import java.sql.*; import java.util.Hashtable; import java.util.Vector; import java.util.Iterator; public class Bed extends OC_Object{ private String name; private Service service; private String serviceUID; private int priority; private String comment; private String location; public String getName(){ return name; } public void setName(String name){ this.name = name; } public Service getService(){ if(this.service==null){ if(this.serviceUID!=null && this.serviceUID.length() > 0){ this.setService(Service.getService(this.serviceUID)); } else{ this.service = null; } } return service; } public void setService(Service service){ this.service = service; } public int getPriority(){ return priority; } public void setPriority(int priority){ this.priority = priority; } public String getComment(){ return comment; } public void setComment(String comment){ this.comment = comment; } public String getLocation(){ return location; } public void setLocation(String location){ this.location = location; } public String getServiceUID(){ return this.serviceUID; } public void setServiceUID(String serviceUID){ this.serviceUID = serviceUID; } //--- STORE ----------------------------------------------------------------------------------- public void store(){ PreparedStatement ps = null; ResultSet rs = null; String sInsert, sSelect, sDelete; int iVersion = 1; String[] ids; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ if(this.getUid()!=null && this.getUid().length()>0){ ids = this.getUid().split("\\."); if(ids.length==2){ sSelect = "SELECT * FROM OC_BEDS WHERE OC_BED_SERVERID = ? AND OC_BED_OBJECTID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); rs = ps.executeQuery(); if(rs.next()){ iVersion = rs.getInt("OC_BED_VERSION")+1; } rs.close(); ps.close(); sInsert = " INSERT INTO OC_BEDS_HISTORY "+ " SELECT OC_BED_SERVERID,"+ " OC_BED_OBJECTID,"+ " OC_BED_NAME,"+ " OC_BED_SERVICEUID,"+ " OC_BED_PRIORITY,"+ " OC_BED_COMMENT,"+ " OC_BED_LOCATION,"+ " OC_BED_CREATETIME,"+ " OC_BED_UPDATETIME,"+ " OC_BED_UPDATEUID,"+ " OC_BED_VERSION "+ " FROM OC_BEDS"+ " WHERE OC_BED_SERVERID = ?"+ " AND OC_BED_OBJECTID = ?"; ps = oc_conn.prepareStatement(sInsert); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); sDelete = "DELETE FROM OC_BEDS WHERE OC_BED_SERVERID = ? AND OC_BED_OBJECTID = ?"; ps = oc_conn.prepareStatement(sDelete); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.executeUpdate(); ps.close(); } } else{ ids = new String[] {MedwanQuery.getInstance().getConfigString("serverId"),MedwanQuery.getInstance().getOpenclinicCounter("OC_BEDS")+""}; } if(ids.length==2){ sInsert = " INSERT INTO OC_BEDS ( OC_BED_SERVERID,"+ " OC_BED_OBJECTID,"+ " OC_BED_NAME,"+ " OC_BED_SERVICEUID,"+ " OC_BED_PRIORITY,"+ " OC_BED_COMMENT,"+ " OC_BED_LOCATION,"+ " OC_BED_CREATETIME,"+ " OC_BED_UPDATETIME,"+ " OC_BED_UPDATEUID,"+ " OC_BED_VERSION"+ ") "+ " VALUES(?,?,?,?,?,?,?,?,?,?,?)"; ps = oc_conn.prepareStatement(sInsert); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); ps.setString(3,this.getName()); ps.setString(4,ScreenHelper.checkString(this.getService().code)); ps.setInt(5,this.getPriority()); ps.setString(6,this.getComment()); ps.setString(7,this.getLocation()); ps.setTimestamp(8,new Timestamp(this.getCreateDateTime().getTime())); ps.setTimestamp(9,new Timestamp(this.getUpdateDateTime().getTime())); ps.setString(10,this.getUpdateUser()); ps.setInt(11,iVersion); ps.executeUpdate(); ps.close(); this.setUid(ids[0]+"."+ids[1]); } } catch(Exception e){ Debug.println("OpenClinic => Bed.java => store => "+e.getMessage()); e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- GET ------------------------------------------------------------------------------------- public static Bed get(String uid){ Bed bed = new Bed(); if(uid!=null && uid.length()>0){ String [] ids = uid.split("\\."); Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); PreparedStatement ps = null; ResultSet rs = null; try{ if(ids.length==2){ String sSelect = "SELECT * FROM OC_BEDS WHERE OC_BED_SERVERID = ? AND OC_BED_OBJECTID = ? "; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(ids[0])); ps.setInt(2,Integer.parseInt(ids[1])); rs = ps.executeQuery(); if(rs.next()){ bed.setUid(uid); bed.setName(ScreenHelper.checkString(rs.getString("OC_BED_NAME"))); bed.setLocation(ScreenHelper.checkString(rs.getString("OC_BED_LOCATION"))); bed.setPriority(rs.getInt("OC_BED_PRIORITY")); bed.setComment(ScreenHelper.checkString(rs.getString("OC_BED_COMMENT"))); bed.serviceUID = ScreenHelper.checkString(rs.getString("OC_BED_SERVICEUID")); bed.setCreateDateTime(rs.getTimestamp("OC_BED_CREATETIME")); bed.setUpdateDateTime(rs.getTimestamp("OC_BED_UPDATETIME")); bed.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_BED_UPDATEUID"))); bed.setVersion(rs.getInt("OC_BED_VERSION")); } } } catch(Exception e){ Debug.println("OpenClinic => Bed.java => get => "+e.getMessage()); e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } return bed; } //--- IS OCCUPIED ----------------------------------------------------------------------------- public Hashtable isOccupied(){ Hashtable hOccupied = new Hashtable(); Boolean bStatus = Boolean.FALSE; String sPatientUid; String sEncounterUid; PreparedStatement ps = null; ResultSet rs = null; String sSelect = " SELECT a.* FROM OC_ENCOUNTERS a,OC_ENCOUNTER_SERVICES b "+ " WHERE"+ " a.OC_ENCOUNTER_SERVERID=b.OC_ENCOUNTER_SERVERID AND"+ " a.OC_ENCOUNTER_OBJECTID=b.OC_ENCOUNTER_OBJECTID AND"+ " b.OC_ENCOUNTER_BEDUID = ? AND "+ " b.OC_ENCOUNTER_SERVICEENDDATE IS NULL AND"+ " a.OC_ENCOUNTER_BEGINDATE <= ? AND "+ " (a.OC_ENCOUNTER_ENDDATE >= ? OR a.OC_ENCOUNTER_ENDDATE IS NULL)"; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sSelect); ps.setString(1,this.getUid()); ps.setTimestamp(2,ScreenHelper.getSQLTime()); ps.setTimestamp(3,ScreenHelper.getSQLTime()); rs = ps.executeQuery(); if(rs.next()){ bStatus = Boolean.TRUE; sEncounterUid = ScreenHelper.checkString(rs.getString("OC_ENCOUNTER_SERVERID"))+"."+ScreenHelper.checkString(rs.getString("OC_ENCOUNTER_OBJECTID")); sPatientUid = ScreenHelper.checkString(rs.getString("OC_ENCOUNTER_PATIENTUID")); hOccupied.put("status",bStatus); hOccupied.put("patientUid",sPatientUid); hOccupied.put("encounterUid",sEncounterUid); } else{ hOccupied.put("status",bStatus); hOccupied.put("patientUid",""); hOccupied.put("encounterUid",""); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return hOccupied; } //--- SELECT BEDS IN SERVICE ------------------------------------------------------------------ public static Vector selectBedsInService(String sServiceUID){ PreparedStatement ps = null; ResultSet rs = null; Vector vChildServices = Service.getChildIds(sServiceUID); String sServiceUIDS = ""; if(vChildServices.size()!=0){ Iterator iter = vChildServices.iterator(); while(iter.hasNext()){ sServiceUIDS+= "'"+iter.next()+"',"; } } else{ sServiceUIDS+= "'"+sServiceUID+"',"; } Vector vBeds = new Vector(); String sSelect = "SELECT * FROM OC_BEDS WHERE OC_BED_SERVICEUID IN ("+sServiceUIDS.substring(0,sServiceUIDS.length()-1)+")"; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sSelect); rs = ps.executeQuery(); Bed bTmp; while(rs.next()){ bTmp = new Bed(); bTmp.setUid(ScreenHelper.checkString(rs.getString("OC_BED_SERVERID"))+"."+ScreenHelper.checkString(rs.getString("OC_BED_OBJECTID"))); bTmp.setName(ScreenHelper.checkString(rs.getString("OC_BED_NAME"))); if(rs.getInt("OC_BED_PRIORITY")!=0){ bTmp.setPriority(rs.getInt("OC_BED_PRIORITY")); } bTmp.serviceUID = ScreenHelper.checkString(rs.getString("OC_BED_SERVICEUID")); bTmp.setComment(ScreenHelper.checkString(rs.getString("OC_BED_COMMENT"))); vBeds.addElement(bTmp); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vBeds; } //--- SELECT BEDS ----------------------------------------------------------------------------- public static Vector selectBeds(String serverID, String objectID, String name, String serviceID, String priority, String comment, String sortColumn){ PreparedStatement ps = null; ResultSet rs = null; Connection oc_conn = null; Vector vBeds = new Vector(); String sSelect = "SELECT * FROM OC_BEDS"; String sConditions = ""; String sLower = MedwanQuery.getInstance().getConfigString("lowerCompare"); if(serverID.length() > 0 ) sConditions+= " OC_BED_SERVERID = ? AND"; if(objectID.length() > 0 ) sConditions+= " OC_BED_OBJECTID = ? AND"; if(name.length() > 0 ) sConditions+= " "+sLower.replaceAll("<param>","OC_BED_NAME")+" LIKE ? AND"; if(serviceID.length() > 0 ) sConditions+= " OC_BED_SERVICEUID = ? AND"; if(priority.length() > 0 ) sConditions+= " OC_BED_PRIORITY = ? AND"; if(comment.length() > 0 ) sConditions+= " "+sLower.replaceAll("<param>","OC_BED_COMMENT")+" LIKE ? AND"; if(sConditions.length() > 0){ sSelect = sSelect+" WHERE "+sConditions; sSelect = sSelect.substring(0,sSelect.length() -3); } if(sortColumn.length() > 0){ sSelect+= " ORDER BY "+sortColumn; } try{ oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); ps = oc_conn.prepareStatement(sSelect); int i = 1; if(serverID.length() > 0 ) ps.setInt(i++,Integer.parseInt(serverID)); if(objectID.length() > 0 ) ps.setInt(i++,Integer.parseInt(objectID)); if(name.length() > 0 ) ps.setString(i++,"%"+name.toLowerCase()+"%"); if(serviceID.length() > 0 ) ps.setString(i++,serviceID); if(priority.length() > 0 ) ps.setInt(i++,Integer.parseInt(priority)); if(comment.length() > 0 ) ps.setString(i++,"%"+comment.toLowerCase()+"%"); rs = ps.executeQuery(); Bed bTmp; while(rs.next()){ bTmp = new Bed(); bTmp.setUid(ScreenHelper.checkString(rs.getString("OC_BED_SERVERID"))+"."+ScreenHelper.checkString(rs.getString("OC_BED_OBJECTID"))); bTmp.setName(ScreenHelper.checkString(rs.getString("OC_BED_NAME"))); if(rs.getInt("OC_BED_PRIORITY") != 0){ bTmp.setPriority(rs.getInt("OC_BED_PRIORITY")); } bTmp.serviceUID = ScreenHelper.checkString(rs.getString("OC_BED_SERVICEUID")); bTmp.location = ScreenHelper.checkString(rs.getString("OC_BED_LOCATION")); bTmp.setComment(ScreenHelper.checkString(rs.getString("OC_BED_COMMENT"))); vBeds.addElement(bTmp); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } return vBeds; } }
import java.awt.Color; import edu.princeton.cs.algs4.Picture; /* Score : 82/100 Correctness: 21/31 tests passed Memory: 6/6 tests passed Timing: 18/17 tests passed */ public class SeamCarver { private Picture picture; private final double maxEng = 255 * 255 + 255 * 255 + 255 * 255; private double[][] edgeTo; private double[][] distTo; private double[][] energies; public SeamCarver(Picture picture) { if(picture == null) throw new java.lang.IllegalArgumentException(); this.picture = picture; } public Picture picture() { return new Picture(this.picture); } public int width() { return picture.width(); } public int height() { return picture.height(); } public double energy(int x, int y) { if (x < 0 || x >= width() || y < 0 || y >= height() ) throw new java.lang.IllegalArgumentException(); if (x == 0 || y == 0 || x == width() - 1 || y == height() - 1) return 1000.0; return Math.sqrt(sqg(picture.get(x - 1, y), picture.get(x + 1, y)) + sqg(picture.get(x, y - 1), picture.get(x, y + 1))); } private double sqg(Color one, Color two) { double r = Math.abs(one.getRed() - two.getRed()); double g = Math.abs(one.getGreen() - two.getGreen()); double b = Math.abs(one.getBlue() - two.getBlue()); return r * r + g * g + b * b; } public int[] findHorizontalSeam() { distTo = new double[height()][width()]; edgeTo = new double[height()][width()]; energies = new double[height()][width()]; for (int i = 0; i < height() ; i++) { for (int j = 0; j < width() ; j++) { if (j == 0) { distTo[i][j] = 0; } else distTo[i][j] = Double.POSITIVE_INFINITY; edgeTo[i][j] = -1; energies[i][j] = energy(j, i); } } for (int i = 0; i < width() - 1; i++) { for (int j = 0; j < height() ; j++) { if (j - 1 >= 0) { relax(j, i, j - 1, i + 1); } relax(j, i, j, i + 1); if (j + 1 < height() ) { relax(j, i, j + 1, i + 1); } } } double min = Double.POSITIVE_INFINITY; int end = 0; for (int i = 0; i < height() ; i++) { if (distTo[i][width() - 1] < min) { min = distTo[i][width() - 1]; end = i; } } int[] res = new int[width()]; int len = width() - 1; int t = end; while (len > 0) { res[len] = t; if (t - 1 >= 0 && edgeTo[t - 1][len - 1] == t) { t = t - 1; } else if (t + 1 < height() && edgeTo[t + 1][len - 1] == t) t = t + 1; len--; } res[len] = t; // while (len >= 0) { // res[len--] = t; // if (t - 1 >= 0 && edgeTo[t - 1][len - 1] == t) { // t = t - 1; // } else if (t + 1 < height() && edgeTo[t + 1][len - 1] == t) { // t = t + 1; // } // } return res; } private void relax(int i, int j, int x, int y) { if (distTo[x][y] > distTo[i][j] + energies[x][y]) { distTo[x][y] = distTo[i][j] + energies[x][y]; edgeTo[x][y] = j; } } public int[] findVerticalSeam() { distTo = new double[width()][height()]; edgeTo = new double[width()][height()]; energies = new double[width()][height()]; for (int i = 0; i < width() ; i++) { for (int j = 0; j < height() ; j++) { if (i == 0) { distTo[i][j] = 0; } else distTo[i][j] = Double.POSITIVE_INFINITY; edgeTo[i][j] = -1; energies[i][j] = energy(i, j); } } for (int i = 0; i < height() - 1; i++) { for (int j = 0; j < width() ; j++) { if (j - 1 >= 0) { relax(j, i, j - 1, i + 1); } relax(j, i, j, i + 1); if (j + 1 < width() ) { relax(j, i, j + 1, i + 1); } } } double min = Double.POSITIVE_INFINITY; int end = 0; for (int i = 0; i < width() ; i++) { if (distTo[i][height() - 1] < min) { min = distTo[i][height() - 1]; end = i; } } int[] res = new int[height() ]; int h = height() - 1; int t = end; while (h > 0) { res[h] = t; if (t - 1 >= 0 && edgeTo[t - 1][h - 1] == t) t = t - 1; else if (t + 1 < width() && edgeTo[t + 1][h - 1] == t) t = t + 1; h--; } res[h] = t; // while (h >= 0) { // res[h--] = t; // if (t - 1 >= 0 && edgeTo[h - 1][t - 1] == t) { // t = t - 1; // } else if (t + 1 < width() && edgeTo[h - 1][t + 1] == t) { // t = t + 1; // } // } return res; } public void removeHorizontalSeam(int[] seam) { if (height() <= 1) throw new java.lang.IllegalArgumentException(); if (seam.length != width()) throw new java.lang.IllegalArgumentException(); Picture res = new Picture(width(), height() - 1); int prev = seam[0]; for (int i = 0; i < width(); i++) { if (seam[i] < 0 || seam[i] >= height()) throw new java.lang.IllegalArgumentException(); if (seam[i] < prev - 1 || seam[i] > prev + 1) throw new java.lang.IllegalArgumentException(); prev = seam[i]; for (int j = 0; j < height() - 1; j++) { if (j < prev) { res.set(i, j, picture.get(i, j)); } else { res.set(i, j, picture.get(i, j + 1)); } } } picture = res; edgeTo = null; distTo = null; energies = null; } public void removeVerticalSeam(int[] seam) { if (width() <= 1) throw new java.lang.IllegalArgumentException(); if (seam.length != height() ) throw new java.lang.IllegalArgumentException(); Picture res = new Picture(width() - 1, height()); int prev = seam[0]; for (int i = 0; i < height(); i++) { if (seam[i] < 0 || seam[i] >= width()) throw new java.lang.IllegalArgumentException(); if (seam[i] < prev - 1 || seam[i] > prev + 1) throw new java.lang.IllegalArgumentException(); prev = seam[i]; for (int j = 0; j < width() - 1; j++) { if (j < prev) { res.set(j, i, picture.get(j, i)); } else { res.set(j, i, picture.get(j + 1, i)); } } } picture = res; edgeTo = null; distTo = null; energies = null; } }
package com.kic.BoardVO; import java.util.Date; public class BoardVO { private int num; private String title; private String content; private String writer; private Date writedate; private int readno; private int rnum; public BoardVO(){} public BoardVO(int num, String title, String content, String writer) { super(); this.num = num; this.title = title; this.content = content; this.writer = writer; } public int getRnum() { return rnum; } public void setRnum(int rnum) { this.rnum = rnum; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public Date getWritedate() { return writedate; } public void setWritedate(Date writedate) { this.writedate = writedate; } public int getReadno() { return readno; } public void setReadno(int readno) { this.readno = readno; } }
package net.awesomekorean.podo.lesson.lessons; public class LessonInit { private boolean isActive = false; private LessonItem specialLesson = null; private boolean isCurrent = false; private Boolean isLocked = false; private boolean isCompleted = false; private Integer dayCount = null; public boolean getIsLocked() { return isLocked; } public void setIsLocked(boolean b) { this.isLocked = b; } public boolean getIsCompleted() { return this.isCompleted; } public void setIsCompleted(boolean b) { this.isCompleted = b; } public boolean getIsActive() { return isActive; } public boolean setIsActive(boolean isActive) { return this.isActive = isActive; } public LessonItem getSLesson() { return specialLesson; } public boolean getIsCurrent() { return isCurrent; } public void setIsCurrent(boolean current) { isCurrent = current; } public Integer getDayCount() { return dayCount; } public boolean getHasVideo() { return false; } }
package com.zaiou.cleaning.config; import java.util.HashMap; import java.util.Map; /** * @author zaiou 2019-05-28 * @Description: 任务初始化 * @modify zaiou 2019-05-28 */ public class TaskInitConfig { public static Map<String,String> parserInitConfig=new HashMap<>(); static { parserInitConfig.put("cleaningCmUserParseJob","解析用户定义表【CmUser】作业"); } }
package ManyToOne; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import javax.persistence.ManyToOne; @Entity @NoArgsConstructor @AllArgsConstructor @Data public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne @JoinColumn(name = "college_id", nullable = false) private College college; }
package com.epam.esm.service.ext.impl; import com.epam.esm.entity.BookGroup; import com.epam.esm.service.ext.BookGroupService; public class BookGroupServiceJpa implements BookGroupService { @Override public BookGroup create(BookGroup bookGroup) { return null; } @Override public BookGroup findById(long id) { return null; } @Override public void delete(long id) { } @Override public BookGroup update(BookGroup bookGroup, long id) { return null; } }
package com.fotoable.fotoime.utils; import android.util.Log; import com.fotoable.fotoime.BuildConfig; /** * Created by zhanglf on 2016/6/28. */ public class LogUtil { public static void i(String TAG, String msg){ if (BuildConfig.DEBUG){ Log.i(TAG, msg); } } }
package me.sh4rewith.domain; public interface StorageCoordinates { public static enum StorageType { FILESYSTEM, MONGO, ELASTICSEARCH } StorageType storageType(); String coordinates(); }