text
stringlengths
10
2.72M
package com.lehvolk.xodus.web.exceptions; import javax.ws.rs.InternalServerErrorException; /** * Exception Xodus database * @author Alexey Volkov * @since 16.11.2015 */ public class XodusRestException extends InternalServerErrorException { private static final long serialVersionUID = 317880648307744850L; public XodusRestException(Throwable cause) { super(cause); } }
package io.quarkus.bootstrap.devmode; import io.quarkus.bootstrap.model.ApplicationModel; import io.quarkus.maven.dependency.GACTV; import io.quarkus.maven.dependency.ResolvedDependency; import java.util.ArrayList; import java.util.List; import org.jboss.logging.Logger; public class DependenciesFilter { private static final Logger log = Logger.getLogger(DependenciesFilter.class); public static List<ResolvedDependency> getReloadableModules(ApplicationModel appModel) { final List<ResolvedDependency> reloadable = new ArrayList<>(); if (appModel.getApplicationModule() != null) { reloadable.add(appModel.getAppArtifact()); } appModel.getDependencies().forEach(d -> { if (d.isReloadable()) { reloadable.add(d); } else if (d.isWorkspaceModule()) { //if this project also contains Quarkus extensions we do no want to include these in the discovery //a bit of an edge case, but if you try and include a sample project with your extension you will //run into problems without this final StringBuilder msg = new StringBuilder(); msg.append("Local Quarkus extension dependency "); msg.append(d.getGroupId()).append(":").append(d.getArtifactId()).append(":"); if (!d.getClassifier().isEmpty()) { msg.append(d.getClassifier()).append(":"); } if (!GACTV.TYPE_JAR.equals(d.getType())) { msg.append(d.getType()).append(":"); } msg.append(d.getVersion()).append(" will not be hot-reloadable"); log.warn(msg.toString()); } }); return reloadable; } }
package net.lantrack.project.search.service.impl; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import net.lantrack.framework.core.entity.PageEntity; import net.lantrack.framework.core.importexport.excel.ExportExcelUtil; import net.lantrack.framework.core.lcexception.ServiceException; import net.lantrack.framework.core.service.PageService; import net.lantrack.framework.core.util.GsonUtil; import net.lantrack.framework.sysbase.util.UserUtil; import net.lantrack.project.base.service.DictBaseService; import net.lantrack.project.search.dao.ColumnInfoDao; import net.lantrack.project.search.dao.TableInfoDao; import net.lantrack.project.search.entity.ColumnInfo; import net.lantrack.project.search.entity.ColumnInfoExample; import net.lantrack.project.search.entity.ColumnInfoExample.Criteria; import net.lantrack.project.search.entity.DataSerchModel; import net.lantrack.project.search.model.CustomCondtion; import net.lantrack.project.search.entity.TableInfo; import net.lantrack.project.search.entity.TableInfoExample; import net.lantrack.project.search.service.DataSerchModelService; import net.lantrack.project.search.service.TableInfoService; @Service public class TableInfoServiceImpl implements TableInfoService { @Autowired protected TableInfoDao tableInfoDao; @Autowired protected ColumnInfoDao columnInfoDao; @Autowired protected PageService pageService; @Autowired protected DataSerchModelService dataSerchModelService; @Autowired protected DictBaseService dictBaseService; @Override public List<TableInfo> getTreeTables() { TableInfoExample example = new TableInfoExample(); try { return this.tableInfoDao.selectByExample(example); } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } } @Override public void getColumnPage(Integer tableId, PageEntity page) { this.pageService.getPage(page.getPerPageCount(), page.getCurrentPage()); try { List<ColumnInfo> list = this.columnInfoDao.getListPage(tableId, page); page.setContent(list); } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } } @Override public void getCustomerDatas(String ids,PageEntity page,List<CustomCondtion> conds) { this.pageService.getPage(page.getPerPageCount(), page.getCurrentPage()); if(StringUtils.isBlank(ids)) { throw new ServiceException("请求参数异常"); } String[] split = ids.split(","); ColumnInfoExample columnExample = new ColumnInfoExample(); Criteria cr = columnExample.createCriteria(); cr.andIdIn(Arrays.asList(split)); List<ColumnInfo> columns = this.columnInfoDao.selectByExample(columnExample); String table = null; String column = "*"; StringBuffer colBuffer = new StringBuffer(); for(ColumnInfo info:columns) { if(table ==null) { table = info.getTableName(); } colBuffer.append(info.getColumnName()).append(","); } if(colBuffer.length()>0) { column = colBuffer.substring(0, colBuffer.length()-1); } String sql = "select " + column + " from " + table +" where 1 = 1 "; //查询条件 String concatCondSql = concatCondSql(conds); System.out.println(concatCondSql.length()); if(concatCondSql!=null&&concatCondSql.length()>3) { sql = sql + " and " + concatCondSql; } try { List<Map<String, Object>> list = this.tableInfoDao.selectDataBySqlListPage(sql, page,""); page.setContent(list); } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } } //拼接查询条件 private String concatCondSql(List<CustomCondtion> conds) { if(conds==null||conds.size()==0) { return ""; } CustomCondtion condtion = conds.get(conds.size()-1); condtion.setConcatCond(null); // String sql = "(asd and asd and asd or ( asd and asd or ( asd )))"; int orCount = 1; StringBuffer sqlBuffer = new StringBuffer(" ("); for(CustomCondtion cond:conds) { if(StringUtils.isBlank(cond.getCondtion())&&StringUtils.isBlank(cond.getValue())){ continue; } sqlBuffer.append(cond.getField()).append(" ").append(cond.getCondtion()) .append(formatValue(cond.getFieldType(),cond.getValue(),cond.getCondtion())); String concatCond = cond.getConcatCond(); if(concatCond!=null) { concatCond = concatCond.toLowerCase(); switch (concatCond) { //and 连接从左往右拼接 case CONCAT_CONDTION_AND: sqlBuffer.append(" and "); break; // or 连接把后面的条件当成新的条件组 case CONCAT_CONDTION_OR: sqlBuffer.append(" or ( "); orCount++; break; } } } //最后右括号闭合 for(int i=0;i<orCount;i++) { sqlBuffer.append(")"); } return sqlBuffer.toString(); } //格式化查询数据 private String formatValue(String fieldType,String value,String cond) { if(fieldType==null) { fieldType = ""; } String format=""; switch (fieldType) { case "date": if("like".equals(cond)&&StringUtils.isNotBlank(value)){ format = "'%"+value+"%'"; }else{ format = "'"+value+"'"; } break; case "datetime": if("like".equals(cond)&&StringUtils.isNotBlank(value)){ format = "'%"+value+"%'"; }else{ format = "'"+value+"'"; } break; case "varchar": if("like".equals(cond)&&StringUtils.isNotBlank(value)){ format = "'%"+value+"%'"; }else{ format = "'"+value+"'"; } break; case "int": format = value; break; case "double": format = value; break; case "float": format = value; break; case "boolean": format = value; break; default:format = value; } return format; } @Override public Map<String, String> getCustomerColumn(String ids) { if(StringUtils.isBlank(ids)) { throw new ServiceException("请求参数异常"); } String[] split = ids.split(","); ColumnInfoExample columnExample = new ColumnInfoExample(); Criteria cr = columnExample.createCriteria(); cr.andIdIn(Arrays.asList(split)); try { List<ColumnInfo> columns = this.columnInfoDao.selectByExample(columnExample); Map<String, String> columnMapping = new LinkedHashMap<>(columns.size()); for(ColumnInfo info:columns) { columnMapping.put(info.getColumnName(), info.getZhName()); } return columnMapping; } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } } @Override public DataSerchModel saveTemplate(String who,String modelName,String ids, String json) { if(StringUtils.isBlank(ids)) { throw new ServiceException("模板字段不能为空"); } DataSerchModel model = new DataSerchModel(); model.setModelField(ids); model.setShowWho(who); model.setOfficeCode(UserUtil.getUser().getOfficeId()); model.setModelName(modelName); //查出对应的列名 Map<String,String> column = this.getCustomerColumn(ids); StringBuffer bf = new StringBuffer(); for(Map.Entry<String, String> entry:column.entrySet()) { bf.append(entry.getValue()).append(","); } if(bf.length()>0) { model.setModelFieldZh(bf.substring(0, bf.length()-1)); } //查询条件 List<CustomCondtion> conds = null; if(json!=null&&!"".equals(json.trim())) { try { conds = GsonUtil.jsonToList(json, CustomCondtion[].class); } catch (Exception e) { } } //保存查询条件 if(conds!=null&&conds.size()>0) { model.setModelCond(json); String sql = concatCondSql(conds); // 查询条件 <,>,>=,<= Map<String, String> condMap = this.dictBaseService.queryDictMapByTypeAndDepart("search_cond", 0); for(Map.Entry<String, String> entry:condMap.entrySet()) { sql = sql.replace(entry.getKey(), entry.getValue()); } sql = sql.replace(CONCAT_CONDTION_AND, "并且"); sql = sql.replace(CONCAT_CONDTION_OR, "或者"); sql = sql.replace("(", " "); sql = sql.replace(")", " "); for(Map.Entry<String, String> entry:column.entrySet()) { sql = sql.replace(entry.getKey(), entry.getValue()); } model.setModelCondZh(sql); } try { this.dataSerchModelService.save(model); return model; } catch (Exception e) { throw new ServiceException(e.getMessage()); } } @Override public void exportExcel(Map<String, String> column, List<Map<String, Object>> resultList, HttpServletResponse response) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { ExportExcelUtil.exportExcelByColumnMap(column, resultList, outStream, "yyyy-MM-dd"); ExportExcelUtil.downloadExcel(new Date().getTime()+"", outStream, response); } catch (Exception e) { throw new ServiceException(e.getMessage()); } } @Override public DataSerchModel templateById(Integer id) { return dataSerchModelService.queryById(id); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.support; import java.sql.SQLException; import org.junit.jupiter.api.Test; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.PessimisticLockingFailureException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.lang.Nullable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * @author Rick Evans * @author Juergen Hoeller * @author Chris Beams */ public class SQLStateSQLExceptionTranslatorTests { @Test public void translateNullException() { assertThatIllegalArgumentException().isThrownBy(() -> new SQLStateSQLExceptionTranslator().translate("", "", null)); } @Test public void translateBadSqlGrammar() { doTest("07", BadSqlGrammarException.class); } @Test public void translateDataIntegrityViolation() { doTest("23", DataIntegrityViolationException.class); } @Test public void translateDuplicateKey() { doTest("23505", DuplicateKeyException.class); } @Test public void translateDuplicateKeyOracle() { doTest("23000", 1, DuplicateKeyException.class); } @Test public void translateDuplicateKeyMySQL() { doTest("23000", 1062, DuplicateKeyException.class); } @Test public void translateDuplicateKeyMSSQL1() { doTest("23000", 2601, DuplicateKeyException.class); } @Test public void translateDuplicateKeyMSSQL2() { doTest("23000", 2627, DuplicateKeyException.class); } @Test public void translateDataAccessResourceFailure() { doTest("53", DataAccessResourceFailureException.class); } @Test public void translateTransientDataAccessResourceFailure() { doTest("S1", TransientDataAccessResourceException.class); } @Test public void translatePessimisticLockingFailure() { doTest("40", PessimisticLockingFailureException.class); } @Test public void translateCannotAcquireLock() { doTest("40001", CannotAcquireLockException.class); } @Test public void translateUncategorized() { doTest("00000000", null); } @Test public void invalidSqlStateCode() { doTest("NO SUCH CODE", null); } /** * PostgreSQL can return null. * SAP DB can apparently return empty SQL code. * Bug 729170 */ @Test public void malformedSqlStateCodes() { doTest(null, null); doTest("", null); doTest("I", null); } private void doTest(@Nullable String sqlState, @Nullable Class<?> dataAccessExceptionType) { doTest(sqlState, 0, dataAccessExceptionType); } private void doTest(@Nullable String sqlState, int errorCode, @Nullable Class<?> dataAccessExceptionType) { SQLExceptionTranslator translator = new SQLStateSQLExceptionTranslator(); SQLException ex = new SQLException("reason", sqlState, errorCode); DataAccessException dax = translator.translate("task", "SQL", ex); if (dataAccessExceptionType == null) { assertThat(dax).as("Expected translation to null").isNull(); return; } assertThat(dax).as("Specific translation must not result in null").isNotNull(); assertThat(dax).as("Wrong DataAccessException type returned").isExactlyInstanceOf(dataAccessExceptionType); assertThat(dax.getCause()).as("The exact same original SQLException must be preserved").isSameAs(ex); } }
package com.mss.entity; import com.mss.annotations.RequiredString; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Transient; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlTransient; import java.io.Serializable; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @Entity public class User implements Serializable { @Transient public static final String USERNAME_REGEX = "[a-zA-Z][a-zA-z0-9_]*"; @Transient public static final String CAMELCASE_REGEX = "[A-Z][a-z]*"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int userId; @Column(unique = true) @Size(min = 5, max = 30, message = "Must be between 5 and 30 characters") @Pattern(regexp = USERNAME_REGEX, message = "Must start with alphanumerical character and may include numbers or '_'") private String username; @RequiredString private String password; @Pattern(regexp = CAMELCASE_REGEX) private String firstName; @Pattern(regexp = CAMELCASE_REGEX) private String lastName; @Column(unique=true) @Email private String email; @NotNull private long registrationTime; @OneToMany(mappedBy = "user") @XmlTransient @Transient private List<Thread> threads = new ArrayList<>(); @OneToMany(mappedBy = "user") @XmlTransient @Transient private List<Message> messages = new ArrayList<>(); private LocalDate dob; private String gender; public int getUserId() { return userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } 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 String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public long getRegistrationTime() { return registrationTime; } public void setRegistrationTime(long registrationTime) { this.registrationTime = registrationTime; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public List<Thread> getThreads() { return threads; } public void setThreads(List<Thread> threads) { this.threads = threads; } public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } }
import java.util.Scanner; public class micro01 { public static void main(String[] args) { Scanner s = new Scanner(System.in); float cel , far ; System.out.println(" Tabela de conversao: Celsius -> Fahrenheit"); System.out.print("Digite a temperatura em Celsius: "); cel = s.nextFloat(); far = (9*cel+160)/5; System.out.println("A nova temperatura é:"+far+"F"); } }
package net.datacrow.console.components; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.PlainDocument; import net.datacrow.util.Utilities; public class DcFilePatternTextField extends DcShortTextField { public DcFilePatternTextField() { super(500); } @Override protected Document createDefaultModel() { return new ShortStringDocument(); } protected class ShortStringDocument extends PlainDocument { @Override public void insertString(int i, String s, AttributeSet attributeset) throws BadLocationException { if (i + 1 < MAX_TEXT_LENGTH) super.insertString(i, s.equals("_") ? "_" : Utilities.toFilename(s), attributeset); } } }
package com.bookstore; import java.util.List; /** * Created by blakerollins on 10/30/14. */ public interface BookRepository { Book lookupById(String id); void addBook(String title, String description, String price, String pubDate); void updateBook(String id, String title, String description, String price, String pubDate); void removeBook(String id); List<Book> listBooks(); List<Book> listBooksSortByPriceAsc(); List<Book> listBooksSortByTitleAsc(); List<Book> listBooksSortByTitleDesc(); List<Book> listBooksSortByPriceDesc(); List<Book> listBooksSortByPubDateDesc(); List<Book> listBooksSortByPubDateAsc(); }
public class Cone extends Shape { public Cone (double radius, double height) { super(radius, height); } public double getVolume() { return (Math.PI * (Math.pow(radius, 2)) * (height/3)); } public double getSurfaceArea() { return (Math.PI * radius) * (radius + (Math.sqrt((Math.pow(height, 2)) + Math.pow(radius, 2)))); } public String toString() { return this.getClass().toString() + " with radius " + this.radius + " and height " + this.height; } }
package uno.iut.fr.uno.modele.carte; import android.media.Image; import uno.iut.fr.uno.modele.Color; import uno.iut.fr.uno.modele.ConstValue; import uno.iut.fr.uno.modele.IStrategyCarte; import uno.iut.fr.uno.modele.carte.Carte; /** * Created by Max on 04/03/2015. */ public class CarteEvent extends Carte { private IStrategyCarte strategy = null; public CarteEvent(Color color, IStrategyCarte strategy){ super(color, ConstValue.EVENTCARTEVALUE); this.strategy = strategy; } }
package com.sky.design.observer; public class StockObserver extends Observer { public StockObserver(String name, Subject sub) { super(name, sub); } @Override void Update() { System.out.println(sub.getSubjectState()+name+"关闭股票详情,继续工作!"); } }
package com.arduino.bluetooth; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; import java.util.Locale; /** * Created by samsung on 2016-11-16. */ public class GpsActivity extends Activity implements LocationListener, TextToSpeech.OnInitListener, View.OnClickListener, SensorEventListener{ TextView textView3; String dbName = "st_file.db"; int dbVersion = 3; private DBManager helper; private SQLiteDatabase db; String tag = "SQLite"; // Log의 tag 로 사용 String tableName = "student"; // DB의 table 명 // Button bSelect; TextView tv; // 결과창 Button button; TextToSpeech tts; boolean init; GoogleMap googleMap; MapFragment fragment; LocationManager lm; Marker marker; private long lastTime; private float speed; private float lastX; private float lastY; private float lastZ; private float x, y, z; private static final int SHAKE_THRESHOLD = 950; private static final int DATA_X = SensorManager.DATA_X; private static final int DATA_Y = SensorManager.DATA_Y; private static final int DATA_Z = SensorManager.DATA_Z; private SensorManager sensorManager; private Sensor accelerormeterSensor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gps); fragment = (MapFragment)getFragmentManager().findFragmentById(R.id.fragment); googleMap = fragment.getMap(); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); textView3 = (TextView)findViewById(R.id.textView3); tv = (TextView)findViewById(R.id.textView4); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); init = false; tts = new TextToSpeech(this, this); sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); accelerormeterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); helper = new DBManager( this, // 현재 화면의 제어권자 dbName, // 데이터베이스 이름 null, // 커서팩토리 - null 이면 표준 커서가 사용됨 dbVersion); // 데이터베이스 버전 try { db = helper.getWritableDatabase(); } catch (SQLiteException e) { e.printStackTrace(); Log.e(tag, "데이터 베이스를 열수 없음"); finish(); } insert ("대한민국 서울특별시 동작구 만양로8길", 250, 20); insert ("대한민국 서울특별시 동작구 노량진1동", 150, 40); insert ("대한민국 서울특별시 동작구 노량진동", 200, 100); insert ("대한민국 경기도 수원시 원천동", 250, 20); insert ("대한민국 경기도 수원시 이의동", 150, 40); } // end of onCreate void insert (String address, int outradius, int innerradius) { ContentValues values = new ContentValues(); // 키,값의 쌍으로 데이터 입력 values.put("address", address); values.put("outradius", outradius); values.put("innerradius", innerradius); long result = db.insert(tableName, null, values); } @Override protected void onStart() { super.onStart(); if(accelerormeterSensor != null) sensorManager.registerListener(this, accelerormeterSensor, SensorManager.SENSOR_DELAY_GAME); } @Override protected void onStop() { super.onStop(); if(sensorManager!=null) sensorManager.unregisterListener(this); } @Override protected void onResume() { super.onResume(); String provider = lm.getBestProvider(new Criteria(), true); if(provider ==null){ Toast.makeText(this, "위치정보를 사용 가능한 상태가 아냐", Toast.LENGTH_SHORT).show(); return; } Location location = lm.getLastKnownLocation(provider); if(location!= null){ onLocationChanged(location); } lm.requestLocationUpdates(provider,1000, 1,this); } @Override protected void onPause() { super.onPause(); lm.removeUpdates(this); } public String getAddress(double lat, double lng){ String address = null; Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> list = null; try { list = geocoder.getFromLocation(lat, lng, 1); if (list.size() > 0){ Address addr = list.get(0); address = addr.getCountryName() + " " + addr.getAdminArea() + " " + addr.getLocality() + " " + addr.getThoroughfare() + " " + addr.getFeatureName(); } } catch (IOException e) { e.printStackTrace(); } return address; } public String getAddress2(double lat, double lng){ String address2 = null; Geocoder geocoder2 = new Geocoder(this, Locale.getDefault()); List<Address> list2 = null; try { list2 = geocoder2.getFromLocation(lat, lng, 1); if (list2.size() > 0){ Address addr2 = list2.get(0); address2 = addr2.getCountryName() + " " + addr2.getAdminArea() + " " + addr2.getLocality() + " " + addr2.getThoroughfare() ; } } catch (IOException e) { e.printStackTrace(); } return address2; } @Override public void onLocationChanged(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); LatLng position = new LatLng(lat, lng); textView3.setText(getAddress(lat, lng)); Cursor c = db.query(tableName, null, null, null, null, null, null); while(c.moveToNext()) { int _id = c.getInt(0); String address = c.getString(1); int outradius = c.getInt(2); int innerradius = c.getInt(3); String re = getAddress2(lat, lng); if (re.equals(address)){ Log.d(tag,"_id:"+_id+", address: "+address +", outradius: "+outradius+", innerradius: "+innerradius); tv.setText("\n" + " address: " + address + "\n" + " outradius: " + outradius + " , innerradius: " + innerradius); } } if(marker == null){ MarkerOptions options = new MarkerOptions(); options.position(position); options.title(getAddress(lat, lng)); options.icon(BitmapDescriptorFactory.fromResource(R.drawable.smallhat)); marker = googleMap.addMarker(options); }else { marker.setPosition(position); marker.setTitle(getAddress(lat, lng)); } CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(position, 18); googleMap.animateCamera(camera); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Toast.makeText(this, provider + " - Status Changed", Toast.LENGTH_SHORT).show(); } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onClick(View v) { if(!init){ Toast.makeText(this, "아직 초기화 되지 않음", Toast.LENGTH_SHORT).show(); return; } String msg = textView3.getText().toString().trim(); if(msg. equals("")){ Toast.makeText(this, "내용입력해라라", Toast.LENGTH_SHORT).show(); return; } Locale loc = Locale.KOREA; int available = tts.isLanguageAvailable(loc); if(available<0){ Toast.makeText(this, "지정되지 않은 언어", Toast.LENGTH_SHORT).show(); return; } tts.setLanguage(loc); tts.setPitch(1); tts.setSpeechRate(1); tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null); } @Override public void onInit(int status) { init = (status == TextToSpeech.SUCCESS); String msg = null; if(init){ msg = "엔진 초기화"; }else { msg = "엔진 초기화에 실패"; } // Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } @Override protected void onDestroy() { super.onDestroy(); if(tts!=null){ tts.stop(); tts.shutdown(); } } @Override public void onSensorChanged(SensorEvent event) { if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ long currentTime = System.currentTimeMillis(); long gabOfTime = (currentTime - lastTime); if(gabOfTime >100){ lastTime = currentTime; x=event.values[SensorManager.DATA_X]; y=event.values[SensorManager.DATA_Y]; z=event.values[SensorManager.DATA_Z]; speed = Math.abs(x + y + z - lastX - lastY - lastZ) / gabOfTime * 10000; if(speed > SHAKE_THRESHOLD){ Toast.makeText(this, "흔들림 감지!", Toast.LENGTH_SHORT).show(); if(!init){ Toast.makeText(this, "아직 초기화 되지 않음", Toast.LENGTH_SHORT).show(); return; } String msg = textView3.getText().toString().trim(); if(msg. equals("")){ Toast.makeText(this, "내용입력해라라", Toast.LENGTH_SHORT).show(); return; } Locale loc = Locale.KOREA; int available = tts.isLanguageAvailable(loc); if(available<0){ Toast.makeText(this, "지정되지 않은 언어", Toast.LENGTH_SHORT).show(); return; } tts.setLanguage(loc); tts.setPitch(1); tts.setSpeechRate(1); tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null); } lastX = event.values[DATA_X]; lastY = event.values[DATA_Y]; lastZ = event.values[DATA_Z]; } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
package com.soa.ws.category.response; import com.soa.domain.categories.Cave; import com.soa.domain.hero.Dragon; import com.soa.ws.hero.response.WSDragonResponse; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Data @NoArgsConstructor public class WSCaveResponse implements Serializable { private Long id; private Integer square; private List<WSDragonResponse> dragons = new ArrayList<>(); public WSCaveResponse(Cave cave) { this.id = cave.getId(); this.square = cave.getSquare(); mapDragons(cave.getDragons()); } private void mapDragons(List<Dragon> dragons) { if(dragons == null) { return; } this.dragons = dragons.stream() .map(WSDragonResponse::new) .collect(Collectors.toList()); } }
package com.tp.basicproject; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class DetailsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); String nom = getIntent().getStringExtra("nom"); String tel = getIntent().getStringExtra("tel"); int img = getIntent().getIntExtra("img", 0); TextView tvNom = (TextView) findViewById(R.id.tvNom); TextView tvtel = (TextView) findViewById(R.id.tvTel); ImageView imgCon = (ImageView) findViewById(R.id.img); tvNom.setText(nom); tvtel.setText(tel); imgCon .setImageResource(img); } }
package net.gupt.ebuy.service; import net.gupt.ebuy.pojo.Customer; /** * 查询用户密码业务接口 * @author glf * */ public interface ForgetPassService { /** * 根据用户名称查找用户信息 * @param name 用户名称 * @return */ public Customer initPass(String name); }
/* * Copyright 2018 YiZheng Huang * * 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.cxxt.mickys.playwithme.view.activity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.cxxt.mickys.playwithme.R; import com.cxxt.mickys.playwithme.view.BasicActivity; import com.cxxt.mickys.playwithme.view.fragment.LoginView; import com.cxxt.mickys.playwithme.view.fragment.RegisterView; import com.ogaclejapan.smarttablayout.SmartTabLayout; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter; import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems; import butterknife.BindView; /** * 登录页面的安卓碎片 * * @author huangyz0918 */ public class LoginActivity extends BasicActivity { @BindView(R.id.iv_login) ImageView imageViewLogin; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_login); super.onCreate(savedInstanceState); Glide.with(this).load(R.drawable.loginimage).into(imageViewLogin); } @Override public void initViews() { super.initViews(); FragmentPagerAdapter adapter = new FragmentPagerItemAdapter( getSupportFragmentManager(), FragmentPagerItems.with(this) .add(R.string.tab_register, RegisterView.class) .add(R.string.tab_login, LoginView.class) .create()); ViewPager viewPager = findViewById(R.id.viewpager); viewPager.setAdapter(adapter); SmartTabLayout viewPagerTab = findViewById(R.id.viewpagertab); viewPagerTab.setViewPager(viewPager); } }
package view.interfaces; public interface ServerStatusInter { public void setIP(String ip); public void setPort(String port); public void setNoConnexion(String no); public void displayError(String mess); }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.explorer.client.button; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.core.client.util.Margins; import com.sencha.gxt.explorer.client.app.ui.ExampleContainer; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.ContentPanel; import com.sencha.gxt.widget.core.client.button.TextButton; import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutData; import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutPack; import com.sencha.gxt.widget.core.client.container.VBoxLayoutContainer; import com.sencha.gxt.widget.core.client.container.VBoxLayoutContainer.VBoxLayoutAlign; import com.sencha.gxt.widget.core.client.event.SelectEvent; import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler; import com.sencha.gxt.widget.core.client.info.Info; @Detail( name = "Button Aligning", category = "Button", icon = "buttonaligning", minHeight = ButtonAlignExample.MIN_HEIGHT, minWidth = ButtonAlignExample.MIN_WIDTH ) public class ButtonAlignExample implements IsWidget, EntryPoint { protected static final int MIN_HEIGHT = 330; protected static final int MIN_WIDTH = 330; private VBoxLayoutContainer panel; public Widget asWidget() { if (panel == null) { SelectHandler selectHandler = new SelectHandler() { @Override public void onSelect(SelectEvent event) { Info.display("Click", ((TextButton) event.getSource()).getText() + " clicked"); } }; ContentPanel panelStart = new ContentPanel(); // Align buttons to the start or left in ltr panelStart.setButtonAlign(BoxLayoutPack.START); // Left panelStart.setHeading("Button Aligning — " + BoxLayoutPack.START); panelStart.addButton(new TextButton("Button 1", selectHandler)); panelStart.addButton(new TextButton("Button 2", selectHandler)); panelStart.addButton(new TextButton("Button 3", selectHandler)); ContentPanel panelCenter = new ContentPanel(); // Align buttons to the center panelCenter.setButtonAlign(BoxLayoutPack.CENTER); // Center panelCenter.setHeading("Button Aligning — " + BoxLayoutPack.CENTER); panelCenter.addButton(new TextButton("Button 1", selectHandler)); panelCenter.addButton(new TextButton("Button 2", selectHandler)); panelCenter.addButton(new TextButton("Button 3", selectHandler)); ContentPanel panelEnd = new ContentPanel(); // Align buttons to the end or right in ltr panelEnd.setButtonAlign(BoxLayoutPack.END); // Right panelEnd.setHeading("Button Aligning — " + BoxLayoutPack.END); panelEnd.addButton(new TextButton("Button 1", selectHandler)); panelEnd.addButton(new TextButton("Button 2", selectHandler)); panelEnd.addButton(new TextButton("Button 3", selectHandler)); BoxLayoutData flex = new BoxLayoutData(new Margins(10, 0, 10, 0)); flex.setFlex(1); panel = new VBoxLayoutContainer(VBoxLayoutAlign.STRETCH); panel.add(panelStart, flex); panel.add(panelCenter, flex); panel.add(panelEnd, flex); } return panel; } @Override public void onModuleLoad() { new ExampleContainer(this) .setMinHeight(MIN_HEIGHT) .setMinWidth(MIN_WIDTH) .doStandalone(); } }
package com.fiume.billingmechine.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import com.fiume.billingmechine.R; import com.fiume.billingmechine.fragments.BillFragment; import com.fiume.billingmechine.fragments.ProductFragment; import com.fiume.billingmechine.fragments.ReportsFragment; import java.util.ArrayList; import java.util.List; /** * Created by Razi on 12/15/2015. */ public class SettingsActivity extends AppCompatActivity { Button btnPrdcts,btnBIlls,btnReports,btnPrinter; private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.settings_activity); toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Eazy Biller"); setSupportActionBar(toolbar); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); // setupTabIcons(); } /* private void setupTabIcons() { TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabOne.setText(" BILLS"); tabLayout.getTabAt(0).setCustomView(tabOne); TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabTwo.setText("PRODUCTS"); tabLayout.getTabAt(1).setCustomView(tabTwo); *//* TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabTwo.setText(" REPORTS "); tabLayout.getTabAt(2).setCustomView(tabThree); *//* TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); tabThree.setText("THREE"); tabLayout.getTabAt(2).setCustomView(tabThree); } */ private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFrag(new BillFragment(), "BILLS"); adapter.addFrag(new ProductFragment(), "PRODUCTS"); adapter.addFrag(new ReportsFragment(), "REPORTS"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } }
package num.grapecity.lab5; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void switchCalendar(View v) { Intent intent = new Intent(this, CalendarEvent.class); startActivity(intent); } public void switchContactList(View v) { Intent intent = new Intent(this, Contact.class); startActivity(intent); } public void switchLab4(View v) { Intent intent = new Intent(this, Lab4_contentPro.class); startActivity(intent); } }
package com.liuyufei.bmc_android.admin; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import com.liuyufei.bmc_android.R; import com.liuyufei.bmc_android.data.BMCContract; import com.liuyufei.bmc_android.utility.DateUtil; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; public class AppointmentCursorAdapter extends CursorAdapter { public AppointmentCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate( R.layout.fragment_appointment, parent, false); } static String TAG = "AppCursorAdapter"; @Override public void bindView(View view, Context context, Cursor cursor) { // TextView description = (TextView) view.findViewById(R.id.appDesc); // TextView staffName = (TextView) view.findViewById(R.id.staff_name); TextView appointmentDate = (TextView) view.findViewById(R.id.appointment_date); TextView appointmentTime = (TextView) view.findViewById(R.id.appointment_time); TextView visitorName = (TextView) view.findViewById(R.id.visitor_name); TextView tvBusinessName = (TextView) view.findViewById(R.id.business_name); TextView tvRemainTime = (TextView) view.findViewById(R.id.remain_time); int textDesc = cursor.getColumnIndex(BMCContract.AppointmentEntry.COLUMN_DESCRIPTION); int textStaffName = cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_NAME); int textVisitorName = cursor.getColumnIndex(BMCContract.VisitorEntry.COLUMN_NAME); int textBusinessName = cursor.getColumnIndex(BMCContract.VisitorEntry.COLUMN_BUSINESS_NAME); int textAppointmentDate = cursor.getColumnIndex(BMCContract.AppointmentEntry.COLUMN_DATETIME); String strStaffName = cursor.getString(textStaffName); String strDescription = cursor.getString(textDesc); String strVisitorName = cursor.getString(textVisitorName); String businessName = cursor.getString(textBusinessName); String strAppointmentDate = cursor.getString(textAppointmentDate); // re-write get needed data to bind view SimpleDateFormat dateFormatFromDb = new SimpleDateFormat(DateUtil.determineDateFormat(strAppointmentDate)); Date dateFromDb = new Date(); try { dateFromDb = dateFormatFromDb.parse(strAppointmentDate); } catch (ParseException e) { e.printStackTrace(); } SimpleDateFormat appTimeFormat = new SimpleDateFormat("h:mm a"); SimpleDateFormat appDateFormat = new SimpleDateFormat("EEEE, MMM d"); String appTimeStr = appTimeFormat.format(dateFromDb); String appDateStr = appDateFormat.format(dateFromDb); // bing view appointmentDate.setText(appDateStr); appointmentTime.setText(appTimeStr); String remainTimeStr = ""; // remaining time try { Hashtable<String,Long> remainTime = DateUtil.getRemainingTime(dateFromDb); if(remainTime.get("day")>=0){ remainTimeStr = remainTime.get("day")+" days"; }else { if(remainTime.get("hour")>=0){ remainTimeStr = remainTime.get("hour")+" hours"; }else{ remainTimeStr = remainTime.get("min")+" mins"; } } } catch (ParseException e) { e.printStackTrace(); } // staffName.setText(strStaffName); // description.setText(strDescription); visitorName.setText(strVisitorName); appointmentDate.setText(appDateStr); tvBusinessName.setText(businessName); tvRemainTime.setText(remainTimeStr); } }
package slimeknights.tconstruct.library.client; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Arrays; import java.util.List; import javax.annotation.Nonnull; /** * Custom renderer based on CoFHs CoFHFontRenderer. * Uses code from CoFHCore. Credit goes to the CoFH team, KingLemming and RWTema. */ @SideOnly(Side.CLIENT) public class CustomFontRenderer extends FontRenderer { private boolean dropShadow; private int state = 0; private int red; private int green; private int blue; public CustomFontRenderer(GameSettings gameSettingsIn, ResourceLocation location, TextureManager textureManagerIn) { super(gameSettingsIn, location, textureManagerIn, true); } @Nonnull @Override public List<String> listFormattedStringToWidth(@Nonnull String str, int wrapWidth) { return Arrays.asList(this.wrapFormattedStringToWidth(str, wrapWidth).split("\n")); } protected String wrapFormattedStringToWidth(String str, int wrapWidth) { int i = this.sizeStringToWidth(str, wrapWidth); if(str.length() <= i) { return str; } else { String s = str.substring(0, i); char c0 = str.charAt(i); boolean flag = c0 == 32 || c0 == 10; String s1 = getCustomFormatFromString(s) + str.substring(i + (flag ? 1 : 0)); return s + "\n" + this.wrapFormattedStringToWidth(s1, wrapWidth); } } public static String getCustomFormatFromString(String text) { String s = ""; int i = 0; int j = text.length(); while((i < j - 1)) { char c = text.charAt(i); // vanilla formatting if(c == 167) { char c0 = text.charAt(i + 1); if(c0 >= 48 && c0 <= 57 || c0 >= 97 && c0 <= 102 || c0 >= 65 && c0 <= 70) { s = "\u00a7" + c0; i++; } else if(c0 >= 107 && c0 <= 111 || c0 >= 75 && c0 <= 79 || c0 == 114 || c0 == 82) { s = s + "\u00a7" + c0; i++; } } // custom formatting else if((int) c >= CustomFontColor.MARKER && (int) c <= CustomFontColor.MARKER + 0xFF) { s = String.format("%s%s%s", c, text.charAt(i + 1), text.charAt(i + 2)); i += 2; } i++; } return s; } @Override public int renderString(@Nonnull String text, float x, float y, int color, boolean dropShadow) { this.dropShadow = dropShadow; return super.renderString(text, x, y, color, dropShadow); } @Override protected float renderUnicodeChar(char letter, boolean italic) { // special color settings through char code // we use \u2700 to \u27FF, where the lower byte represents the Hue of the color if((int) letter >= CustomFontColor.MARKER && (int) letter <= CustomFontColor.MARKER + 0xFF) { int value = letter & 0xFF; switch(state) { case 0: red = value; break; case 1: green = value; break; case 2: blue = value; break; default: this.setColor(1f, 1f, 1f, 1f); return 0; } state = ++state % 3; int color = (red << 16) | (green << 8) | blue | (0xff << 24); if((color & -67108864) == 0) { color |= -16777216; } if(dropShadow) { color = (color & 16579836) >> 2 | color & -16777216; } this.setColor(((color >> 16) & 255) / 255f, ((color >> 8) & 255) / 255f, ((color >> 0) & 255) / 255f, ((color >> 24) & 255) / 255f); return 0; } // invalid sequence encountered if(state != 0) { state = 0; this.setColor(1f, 1f, 1f, 1f); } return super.renderUnicodeChar(letter, italic); } @Override public void onResourceManagerReload(IResourceManager resourceManager) { super.onResourceManagerReload(resourceManager); setUnicodeFlag(Minecraft.getMinecraft().getLanguageManager().isCurrentLocaleUnicode() || Minecraft.getMinecraft().gameSettings.forceUnicodeFont); setBidiFlag(Minecraft.getMinecraft().getLanguageManager().isCurrentLanguageBidirectional()); } }
package ru.atc.wordsTrainer.controllers; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import ru.atc.wordsTrainer.entities.Word; import ru.atc.wordsTrainer.services.WordService; import ru.atc.wordsTrainer.translation.Translator; import ru.atc.wordsTrainer.translation.YandexTranslator; import java.sql.Date; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * Created by VTestova on 03.12.2015. */ @Controller @RequestMapping("translation") public class AddWordController { @Autowired WordService wordService; @Autowired @Qualifier("yandex") Translator translator; @RequestMapping(value = "translatedWord", method = GET) public String translatedWord(ModelMap modelMap) { return "translatedWord"; } @RequestMapping(value = "translate", method = GET) public String enterWord() { return "addWord"; } @RequestMapping(value = "translate", method = POST) public String translate(@ModelAttribute("word") String word, ModelMap modelMap) { System.out.println(word); Word newWord = translator.translate(word); newWord.setAddingDate(new DateTime().toDate()); newWord.setLastTrained(new DateTime().minusDays(100).toDate()); wordService.save(newWord); modelMap.addAttribute("word", newWord); return "translatedWord"; } }
package StudentInformatiomSystem; public class Student extends MedicalReport implements College{ public void studentBio() { System.out.println ("Student Name : Alex Karmokar"); } public void studentGrade() { System.out.println ("A"); } public void studentMedical() { System.out.println (""); } public void studentHobbies() { System.out.println ("Reading book"); } public void studentSports() { System.out.println ("I like Cricket and Football"); } public void absence() { System.out.println (""); } }
package com.mad.cityassignment; import android.database.Cursor; import android.database.CursorWrapper; import com.mad.cityassignment.SettingsSchema.SettingsTable; public class SettingsCursor extends CursorWrapper { public SettingsCursor(Cursor cursor) { super(cursor); } public Settings getSettings(){ String name = getString(getColumnIndex(SettingsTable.Cols.MAP_NAME)); int height = getInt(getColumnIndex(SettingsTable.Cols.HEIGHT)); int width = getInt(getColumnIndex(SettingsTable.Cols.WIDTH)); int money = getInt(getColumnIndex(SettingsTable.Cols.MONEY)); int famSize = getInt(getColumnIndex(SettingsTable.Cols.FAM_SIZE)); int shopSize = getInt(getColumnIndex(SettingsTable.Cols.SHOP_SIZE)); int salary = getInt(getColumnIndex(SettingsTable.Cols.SALARY)); double taxRate = getDouble(getColumnIndex(SettingsTable.Cols.TAX_RATE)); int serviceCost = getInt(getColumnIndex(SettingsTable.Cols.SERVICE_COST)); int resBuilding = getInt(getColumnIndex(SettingsTable.Cols.RES_COST)); int comBuilding = getInt(getColumnIndex(SettingsTable.Cols.COM_COST)); int roadBuilding = getInt(getColumnIndex(SettingsTable.Cols.ROAD_COST)); int miscBuilding = getInt(getColumnIndex(SettingsTable.Cols.MISC_COST)); return new Settings(name, width, height, money, famSize, shopSize, salary, serviceCost, resBuilding, comBuilding, roadBuilding, miscBuilding, taxRate); } }
package com.uchain; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import com.uchain.cryptohash.PrivateKey; import com.uchain.cryptohash.PublicKey; import org.junit.Test; import com.uchain.common.Serializabler; import com.uchain.core.block.BlockHeader; import com.uchain.core.block.BlockHeaderJson; import com.uchain.cryptohash.BinaryData; import akka.http.javadsl.model.DateTime; import lombok.val; public class BlockHeaderTest { @Test public void testSerialize() throws IOException{ val prevBlock = SerializerTest.testHash256("prev"); val merkleRoot = SerializerTest.testHash256("root"); val producer = PublicKey.apply(new BinaryData("022ac01a1ea9275241615ea6369c85b41e2016abc47485ec616c3c583f1b92a5c8")); val timeStamp = DateTime.now().clicks(); val blockHeader = BlockHeader.build(0,timeStamp,merkleRoot,prevBlock,producer,PrivateKey.apply(new BinaryData("efc382ccc0358f468c2a80f3738211be98e5ae419fc0907cb2f51d3334001471"))); val bos = new ByteArrayOutputStream(); val os = new DataOutputStream(bos); Serializabler.write(os, blockHeader); val ba = bos.toByteArray(); val bis = new ByteArrayInputStream(ba); val is = new DataInputStream(bis); val blockHeaderDeserializer = BlockHeader.deserialize(is); assert(blockHeader.getIndex() == blockHeaderDeserializer.getIndex()); assert(blockHeader.getTimeStamp() == blockHeaderDeserializer.getTimeStamp()); assert(blockHeader.getMerkleRoot().toString().equals(blockHeaderDeserializer.getMerkleRoot().toString())); assert(blockHeader.getPrevBlock().toString().equals(blockHeaderDeserializer.getPrevBlock().toString())); assert(blockHeader.getProducer().getPoint().getValue().equals(blockHeaderDeserializer.getProducer().getPoint().getValue())); assert(blockHeader.getProducerSig().getData().equals(blockHeaderDeserializer.getProducerSig().getData())); } @Test public void test() throws IOException{ val prevBlock = SerializerTest.testHash256("prev"); val merkleRoot = SerializerTest.testHash256("root"); val producer = PublicKey.apply(new BinaryData("03b4534b44d1da47e4b4a504a210401a583f860468dec766f507251a057594e682")); val timeStamp = DateTime.now().clicks(); val blockHeader = new BlockHeader(0, timeStamp, merkleRoot, prevBlock, producer, new BinaryData("0000"),0x01,null); val bos = new ByteArrayOutputStream(); val os = new DataOutputStream(bos); Serializabler.write(os, blockHeader); val ba = bos.toByteArray(); val bis = new ByteArrayInputStream(ba); val is = new DataInputStream(bis); val blockHeaderDeserializer = BlockHeader.deserialize(is); String jsonString = BlockHeader.writes(blockHeader); BlockHeaderJson blockHeaderJson = Serializabler.JsonMapperFrom(jsonString, BlockHeaderJson.class); assert(blockHeaderJson.getIndex() == blockHeaderDeserializer.getIndex()); assert(blockHeaderJson.getTimeStamp() == blockHeaderDeserializer.getTimeStamp()); assert(blockHeaderJson.getMerkleRoot().toString().equals(blockHeaderDeserializer.getMerkleRoot().toString())); assert(blockHeaderJson.getPrevBlock().toString().equals(blockHeaderDeserializer.getPrevBlock().toString())); assert(blockHeaderJson.getProducer().toString().equals(blockHeaderDeserializer.getProducer().toString())); assert(blockHeaderJson.getProducerSig().toString().equals(blockHeaderDeserializer.getProducerSig().toString())); } }
package mx.redts.ob3.model; // Generated 03-jun-2014 0:22:34 by Hibernate Tools 3.4.0.CR1 import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * CInvoiceline generated by hbm2java */ @Entity @Table(name = "c_invoiceline", schema = "public") public class CInvoiceline implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; private String CInvoicelineId; private CInvoice CInvoice; private AdOrg adOrg; private CTax CTax; private MProduct MProduct; private CUom CUom; private String adClientId; private char isactive; private Date created; private String createdby; private Date updated; private String updatedby; private String COrderlineId; private String MInoutlineId; private long line; private String description; private char financialInvoiceLine; private String accountId; private BigDecimal qtyinvoiced; private BigDecimal pricelist; private BigDecimal priceactual; private BigDecimal pricelimit; private BigDecimal linenetamt; private String CChargeId; private BigDecimal chargeamt; private String SResourceassignmentId; private BigDecimal taxamt; private String MAttributesetinstanceId; private char isdescription; private BigDecimal quantityorder; private String MProductUomId; private String CInvoiceDiscountId; private String CProjectlineId; private String MOfferId; private BigDecimal pricestd; private Character excludeforwithholding; private Character iseditlinenetamt; private BigDecimal taxbaseamt; private BigDecimal lineGrossAmount; private BigDecimal grossUnitPrice; private BigDecimal periodnumber; private BigDecimal grosspricestd; private String defplantype; private BigDecimal grosspricelist; private char isdeferred; private String CPeriodId; public CInvoiceline() { } public CInvoiceline(String CInvoicelineId, CInvoice CInvoice, AdOrg adOrg, CTax CTax, MProduct MProduct, CUom CUom, String adClientId, char isactive, Date created, String createdby, Date updated, String updatedby, String COrderlineId, String MInoutlineId, long line, String description, char financialInvoiceLine, String accountId, BigDecimal qtyinvoiced, BigDecimal pricelist, BigDecimal priceactual, BigDecimal pricelimit, BigDecimal linenetamt, String CChargeId, BigDecimal chargeamt, String SResourceassignmentId, BigDecimal taxamt, String MAttributesetinstanceId, char isdescription, BigDecimal quantityorder, String MProductUomId, String CInvoiceDiscountId, String CProjectlineId, String MOfferId, BigDecimal pricestd, Character excludeforwithholding, Character iseditlinenetamt, BigDecimal taxbaseamt, BigDecimal lineGrossAmount, BigDecimal grossUnitPrice, BigDecimal periodnumber, BigDecimal grosspricestd, String defplantype, BigDecimal grosspricelist, char isdeferred, String CPeriodId) { this.CInvoicelineId = CInvoicelineId; this.CInvoice = CInvoice; this.adOrg = adOrg; this.CTax = CTax; this.MProduct = MProduct; this.CUom = CUom; this.adClientId = adClientId; this.isactive = isactive; this.created = created; this.createdby = createdby; this.updated = updated; this.updatedby = updatedby; this.COrderlineId = COrderlineId; this.MInoutlineId = MInoutlineId; this.line = line; this.description = description; this.financialInvoiceLine = financialInvoiceLine; this.accountId = accountId; this.qtyinvoiced = qtyinvoiced; this.pricelist = pricelist; this.priceactual = priceactual; this.pricelimit = pricelimit; this.linenetamt = linenetamt; this.CChargeId = CChargeId; this.chargeamt = chargeamt; this.SResourceassignmentId = SResourceassignmentId; this.taxamt = taxamt; this.MAttributesetinstanceId = MAttributesetinstanceId; this.isdescription = isdescription; this.quantityorder = quantityorder; this.MProductUomId = MProductUomId; this.CInvoiceDiscountId = CInvoiceDiscountId; this.CProjectlineId = CProjectlineId; this.MOfferId = MOfferId; this.pricestd = pricestd; this.excludeforwithholding = excludeforwithholding; this.iseditlinenetamt = iseditlinenetamt; this.taxbaseamt = taxbaseamt; this.lineGrossAmount = lineGrossAmount; this.grossUnitPrice = grossUnitPrice; this.periodnumber = periodnumber; this.grosspricestd = grosspricestd; this.defplantype = defplantype; this.grosspricelist = grosspricelist; this.isdeferred = isdeferred; this.CPeriodId = CPeriodId; } public CInvoiceline(String CInvoicelineId, CInvoice CInvoice, AdOrg adOrg, String adClientId, char isactive, Date created, String createdby, Date updated, String updatedby, long line, char financialInvoiceLine, BigDecimal qtyinvoiced, BigDecimal pricelist, BigDecimal priceactual, BigDecimal pricelimit, BigDecimal linenetamt, char isdescription, BigDecimal pricestd, BigDecimal grosspricestd, BigDecimal grosspricelist, char isdeferred) { this.CInvoicelineId = CInvoicelineId; this.CInvoice = CInvoice; this.adOrg = adOrg; this.adClientId = adClientId; this.isactive = isactive; this.created = created; this.createdby = createdby; this.updated = updated; this.updatedby = updatedby; this.line = line; this.financialInvoiceLine = financialInvoiceLine; this.qtyinvoiced = qtyinvoiced; this.pricelist = pricelist; this.priceactual = priceactual; this.pricelimit = pricelimit; this.linenetamt = linenetamt; this.isdescription = isdescription; this.pricestd = pricestd; this.grosspricestd = grosspricestd; this.grosspricelist = grosspricelist; this.isdeferred = isdeferred; } @Column(name = "account_id", length = 32) public String getAccountId() { return this.accountId; } @Column(name = "ad_client_id", nullable = false, length = 32) public String getAdClientId() { return this.adClientId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ad_org_id", nullable = false) public AdOrg getAdOrg() { return this.adOrg; } @Column(name = "c_charge_id", length = 32) public String getCChargeId() { return this.CChargeId; } @Column(name = "chargeamt", precision = 131089, scale = 0) public BigDecimal getChargeamt() { return this.chargeamt; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "c_invoice_id", nullable = false) public CInvoice getCInvoice() { return this.CInvoice; } @Column(name = "c_invoice_discount_id", length = 32) public String getCInvoiceDiscountId() { return this.CInvoiceDiscountId; } @Id @Column(name = "c_invoiceline_id", unique = true, nullable = false, length = 32) public String getCInvoicelineId() { return this.CInvoicelineId; } @Column(name = "c_orderline_id", length = 32) public String getCOrderlineId() { return this.COrderlineId; } @Column(name = "c_period_id", length = 32) public String getCPeriodId() { return this.CPeriodId; } @Column(name = "c_projectline_id", length = 32) public String getCProjectlineId() { return this.CProjectlineId; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "created", nullable = false, length = 29) public Date getCreated() { return this.created; } @Column(name = "createdby", nullable = false, length = 32) public String getCreatedby() { return this.createdby; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "c_tax_id") public CTax getCTax() { return this.CTax; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "c_uom_id") public CUom getCUom() { return this.CUom; } @Column(name = "defplantype", length = 60) public String getDefplantype() { return this.defplantype; } @Column(name = "description", length = 2000) public String getDescription() { return this.description; } @Column(name = "excludeforwithholding", length = 1) public Character getExcludeforwithholding() { return this.excludeforwithholding; } @Column(name = "financial_invoice_line", nullable = false, length = 1) public char getFinancialInvoiceLine() { return this.financialInvoiceLine; } @Column(name = "grosspricelist", nullable = false, precision = 131089, scale = 0) public BigDecimal getGrosspricelist() { return this.grosspricelist; } @Column(name = "grosspricestd", nullable = false, precision = 131089, scale = 0) public BigDecimal getGrosspricestd() { return this.grosspricestd; } @Column(name = "gross_unit_price", precision = 131089, scale = 0) public BigDecimal getGrossUnitPrice() { return this.grossUnitPrice; } @Column(name = "isactive", nullable = false, length = 1) public char getIsactive() { return this.isactive; } @Column(name = "isdeferred", nullable = false, length = 1) public char getIsdeferred() { return this.isdeferred; } @Column(name = "isdescription", nullable = false, length = 1) public char getIsdescription() { return this.isdescription; } @Column(name = "iseditlinenetamt", length = 1) public Character getIseditlinenetamt() { return this.iseditlinenetamt; } @Column(name = "line", nullable = false, precision = 10, scale = 0) public long getLine() { return this.line; } @Column(name = "line_gross_amount", precision = 131089, scale = 0) public BigDecimal getLineGrossAmount() { return this.lineGrossAmount; } @Column(name = "linenetamt", nullable = false, precision = 131089, scale = 0) public BigDecimal getLinenetamt() { return this.linenetamt; } @Column(name = "m_attributesetinstance_id", length = 32) public String getMAttributesetinstanceId() { return this.MAttributesetinstanceId; } @Column(name = "m_inoutline_id", length = 32) public String getMInoutlineId() { return this.MInoutlineId; } @Column(name = "m_offer_id", length = 32) public String getMOfferId() { return this.MOfferId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "m_product_id") public MProduct getMProduct() { return this.MProduct; } @Column(name = "m_product_uom_id", length = 32) public String getMProductUomId() { return this.MProductUomId; } @Column(name = "periodnumber", precision = 131089, scale = 0) public BigDecimal getPeriodnumber() { return this.periodnumber; } @Column(name = "priceactual", nullable = false, precision = 131089, scale = 0) public BigDecimal getPriceactual() { return this.priceactual; } @Column(name = "pricelimit", nullable = false, precision = 131089, scale = 0) public BigDecimal getPricelimit() { return this.pricelimit; } @Column(name = "pricelist", nullable = false, precision = 131089, scale = 0) public BigDecimal getPricelist() { return this.pricelist; } @Column(name = "pricestd", nullable = false, precision = 131089, scale = 0) public BigDecimal getPricestd() { return this.pricestd; } @Column(name = "qtyinvoiced", nullable = false, precision = 131089, scale = 0) public BigDecimal getQtyinvoiced() { return this.qtyinvoiced; } @Column(name = "quantityorder", precision = 131089, scale = 0) public BigDecimal getQuantityorder() { return this.quantityorder; } @Column(name = "s_resourceassignment_id", length = 32) public String getSResourceassignmentId() { return this.SResourceassignmentId; } @Column(name = "taxamt", precision = 131089, scale = 0) public BigDecimal getTaxamt() { return this.taxamt; } @Column(name = "taxbaseamt", precision = 131089, scale = 0) public BigDecimal getTaxbaseamt() { return this.taxbaseamt; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "updated", nullable = false, length = 29) public Date getUpdated() { return this.updated; } @Column(name = "updatedby", nullable = false, length = 32) public String getUpdatedby() { return this.updatedby; } public void setAccountId(String accountId) { this.accountId = accountId; } public void setAdClientId(String adClientId) { this.adClientId = adClientId; } public void setAdOrg(AdOrg adOrg) { this.adOrg = adOrg; } public void setCChargeId(String CChargeId) { this.CChargeId = CChargeId; } public void setChargeamt(BigDecimal chargeamt) { this.chargeamt = chargeamt; } public void setCInvoice(CInvoice CInvoice) { this.CInvoice = CInvoice; } public void setCInvoiceDiscountId(String CInvoiceDiscountId) { this.CInvoiceDiscountId = CInvoiceDiscountId; } public void setCInvoicelineId(String CInvoicelineId) { this.CInvoicelineId = CInvoicelineId; } public void setCOrderlineId(String COrderlineId) { this.COrderlineId = COrderlineId; } public void setCPeriodId(String CPeriodId) { this.CPeriodId = CPeriodId; } public void setCProjectlineId(String CProjectlineId) { this.CProjectlineId = CProjectlineId; } public void setCreated(Date created) { this.created = created; } public void setCreatedby(String createdby) { this.createdby = createdby; } public void setCTax(CTax CTax) { this.CTax = CTax; } public void setCUom(CUom CUom) { this.CUom = CUom; } public void setDefplantype(String defplantype) { this.defplantype = defplantype; } public void setDescription(String description) { this.description = description; } public void setExcludeforwithholding(Character excludeforwithholding) { this.excludeforwithholding = excludeforwithholding; } public void setFinancialInvoiceLine(char financialInvoiceLine) { this.financialInvoiceLine = financialInvoiceLine; } public void setGrosspricelist(BigDecimal grosspricelist) { this.grosspricelist = grosspricelist; } public void setGrosspricestd(BigDecimal grosspricestd) { this.grosspricestd = grosspricestd; } public void setGrossUnitPrice(BigDecimal grossUnitPrice) { this.grossUnitPrice = grossUnitPrice; } public void setIsactive(char isactive) { this.isactive = isactive; } public void setIsdeferred(char isdeferred) { this.isdeferred = isdeferred; } public void setIsdescription(char isdescription) { this.isdescription = isdescription; } public void setIseditlinenetamt(Character iseditlinenetamt) { this.iseditlinenetamt = iseditlinenetamt; } public void setLine(long line) { this.line = line; } public void setLineGrossAmount(BigDecimal lineGrossAmount) { this.lineGrossAmount = lineGrossAmount; } public void setLinenetamt(BigDecimal linenetamt) { this.linenetamt = linenetamt; } public void setMAttributesetinstanceId(String MAttributesetinstanceId) { this.MAttributesetinstanceId = MAttributesetinstanceId; } public void setMInoutlineId(String MInoutlineId) { this.MInoutlineId = MInoutlineId; } public void setMOfferId(String MOfferId) { this.MOfferId = MOfferId; } public void setMProduct(MProduct MProduct) { this.MProduct = MProduct; } public void setMProductUomId(String MProductUomId) { this.MProductUomId = MProductUomId; } public void setPeriodnumber(BigDecimal periodnumber) { this.periodnumber = periodnumber; } public void setPriceactual(BigDecimal priceactual) { this.priceactual = priceactual; } public void setPricelimit(BigDecimal pricelimit) { this.pricelimit = pricelimit; } public void setPricelist(BigDecimal pricelist) { this.pricelist = pricelist; } public void setPricestd(BigDecimal pricestd) { this.pricestd = pricestd; } public void setQtyinvoiced(BigDecimal qtyinvoiced) { this.qtyinvoiced = qtyinvoiced; } public void setQuantityorder(BigDecimal quantityorder) { this.quantityorder = quantityorder; } public void setSResourceassignmentId(String SResourceassignmentId) { this.SResourceassignmentId = SResourceassignmentId; } public void setTaxamt(BigDecimal taxamt) { this.taxamt = taxamt; } public void setTaxbaseamt(BigDecimal taxbaseamt) { this.taxbaseamt = taxbaseamt; } public void setUpdated(Date updated) { this.updated = updated; } public void setUpdatedby(String updatedby) { this.updatedby = updatedby; } }
package projetZoo; public class Lion extends Felin { public Lion(String n, int age) { super(n, age); // TODO Auto-generated constructor stub } }
package za.ac.cput.views.curriculum.scheduledClass; /** * Dinelle Kotze * 219089302 * ScheduledClassMainGUI.java * This is the Main Scheduled Class GUI for the Scheduled Class entity. */ import za.ac.cput.views.MainGUI; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ScheduledClassMainGUI extends JFrame implements ActionListener { private JButton btnView, btnAdd, btnUpdate, btnDelete, btnBack; private JLabel lblHeading; private JPanel panelNorth, panelCenter, panelSouth; private Font headingFont; public ScheduledClassMainGUI() { super("Scheduled Class Main Menu"); panelNorth = new JPanel(); panelCenter = new JPanel(); panelSouth = new JPanel(); btnView = new JButton("View All Scheduled Classes"); btnAdd = new JButton("Add New Scheduled Class"); btnUpdate = new JButton("Update Scheduled Class"); btnDelete = new JButton("Delete Scheduled Class"); btnBack = new JButton("Back"); lblHeading = new JLabel("Scheduled Class", SwingConstants.CENTER); headingFont = new Font("Arial", Font.BOLD, 30); } public void setGUI() { panelNorth.setLayout(new FlowLayout(FlowLayout.CENTER)); panelCenter.setLayout(new GridLayout(4, 1)); panelSouth.setLayout(new GridLayout(1, 1)); this.setPreferredSize(new Dimension(600, 600)); lblHeading.setFont(headingFont); panelNorth.add(lblHeading); panelCenter.add(btnView); panelCenter.add(btnAdd); panelCenter.add(btnUpdate); panelCenter.add(btnDelete); panelSouth.add(btnBack); this.add(panelNorth, BorderLayout.NORTH); this.add(panelCenter, BorderLayout.CENTER); this.add(panelSouth, BorderLayout.SOUTH); btnView.addActionListener(this); btnAdd .addActionListener(this); btnUpdate.addActionListener(this); btnDelete.addActionListener(this); btnBack.addActionListener(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); this.setLocationRelativeTo(null); } @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "View All Scheduled Classes": ViewScheduledClassGUI.main(null); this.setVisible(false); break; case "Add New Scheduled Class": AddScheduledClassGUI.main(null); this.setVisible(false); break; case "Update Scheduled Class": UpdateScheduledClassGUI.main(null); this.setVisible(false); break; case "Delete Scheduled Class": DeleteScheduledClassGUI.main(null); this.setVisible(false); break; case "Back": MainGUI.main(null); this.setVisible(false); break; } } public static void main(String[] args) { new ScheduledClassMainGUI().setGUI(); } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.scope; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.testfixture.beans.ITestBean; import org.springframework.beans.testfixture.beans.TestBean; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.testfixture.SimpleMapScope; import org.springframework.core.io.ClassPathResource; import org.springframework.core.testfixture.io.SerializationTestUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Harrop * @author Juergen Hoeller * @author Chris Beams */ public class ScopedProxyTests { private static final Class<?> CLASS = ScopedProxyTests.class; private static final String CLASSNAME = CLASS.getSimpleName(); private static final ClassPathResource LIST_CONTEXT = new ClassPathResource(CLASSNAME + "-list.xml", CLASS); private static final ClassPathResource MAP_CONTEXT = new ClassPathResource(CLASSNAME + "-map.xml", CLASS); private static final ClassPathResource OVERRIDE_CONTEXT = new ClassPathResource(CLASSNAME + "-override.xml", CLASS); private static final ClassPathResource TESTBEAN_CONTEXT = new ClassPathResource(CLASSNAME + "-testbean.xml", CLASS); @Test // SPR-2108 public void testProxyAssignable() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(MAP_CONTEXT); Object baseMap = bf.getBean("singletonMap"); boolean condition = baseMap instanceof Map; assertThat(condition).isTrue(); } @Test public void testSimpleProxy() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(MAP_CONTEXT); Object simpleMap = bf.getBean("simpleMap"); boolean condition1 = simpleMap instanceof Map; assertThat(condition1).isTrue(); boolean condition = simpleMap instanceof HashMap; assertThat(condition).isTrue(); } @Test public void testScopedOverride() throws Exception { GenericApplicationContext ctx = new GenericApplicationContext(); new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(OVERRIDE_CONTEXT); SimpleMapScope scope = new SimpleMapScope(); ctx.getBeanFactory().registerScope("request", scope); ctx.refresh(); ITestBean bean = (ITestBean) ctx.getBean("testBean"); assertThat(bean.getName()).isEqualTo("male"); assertThat(bean.getAge()).isEqualTo(99); assertThat(scope.getMap().containsKey("scopedTarget.testBean")).isTrue(); assertThat(scope.getMap().get("scopedTarget.testBean").getClass()).isEqualTo(TestBean.class); } @Test public void testJdkScopedProxy() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(TESTBEAN_CONTEXT); bf.setSerializationId("X"); SimpleMapScope scope = new SimpleMapScope(); bf.registerScope("request", scope); ITestBean bean = (ITestBean) bf.getBean("testBean"); assertThat(bean).isNotNull(); assertThat(AopUtils.isJdkDynamicProxy(bean)).isTrue(); boolean condition1 = bean instanceof ScopedObject; assertThat(condition1).isTrue(); ScopedObject scoped = (ScopedObject) bean; assertThat(scoped.getTargetObject().getClass()).isEqualTo(TestBean.class); bean.setAge(101); assertThat(scope.getMap().containsKey("testBeanTarget")).isTrue(); assertThat(scope.getMap().get("testBeanTarget").getClass()).isEqualTo(TestBean.class); ITestBean deserialized = SerializationTestUtils.serializeAndDeserialize(bean); assertThat(deserialized).isNotNull(); assertThat(AopUtils.isJdkDynamicProxy(deserialized)).isTrue(); assertThat(bean.getAge()).isEqualTo(101); boolean condition = deserialized instanceof ScopedObject; assertThat(condition).isTrue(); ScopedObject scopedDeserialized = (ScopedObject) deserialized; assertThat(scopedDeserialized.getTargetObject().getClass()).isEqualTo(TestBean.class); bf.setSerializationId(null); } @Test public void testCglibScopedProxy() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(LIST_CONTEXT); bf.setSerializationId("Y"); SimpleMapScope scope = new SimpleMapScope(); bf.registerScope("request", scope); TestBean tb = (TestBean) bf.getBean("testBean"); assertThat(AopUtils.isCglibProxy(tb.getFriends())).isTrue(); boolean condition1 = tb.getFriends() instanceof ScopedObject; assertThat(condition1).isTrue(); ScopedObject scoped = (ScopedObject) tb.getFriends(); assertThat(scoped.getTargetObject().getClass()).isEqualTo(ArrayList.class); tb.getFriends().add("myFriend"); assertThat(scope.getMap().containsKey("scopedTarget.scopedList")).isTrue(); assertThat(scope.getMap().get("scopedTarget.scopedList").getClass()).isEqualTo(ArrayList.class); ArrayList<?> deserialized = (ArrayList<?>) SerializationTestUtils.serializeAndDeserialize(tb.getFriends()); assertThat(deserialized).isNotNull(); assertThat(AopUtils.isCglibProxy(deserialized)).isTrue(); assertThat(deserialized.contains("myFriend")).isTrue(); boolean condition = deserialized instanceof ScopedObject; assertThat(condition).isTrue(); ScopedObject scopedDeserialized = (ScopedObject) deserialized; assertThat(scopedDeserialized.getTargetObject().getClass()).isEqualTo(ArrayList.class); bf.setSerializationId(null); } }
package lesson13; public class Main1 { public static void main(String[] args) { Table table1 = new Table(12, 4, 67); Table table3 = table1; Table table2 = new Table(12, 4, 67); boolean res = table1.equals(table2); System.out.println(res); System.out.println(table1.equals(table3)); System.out.println(table1); String text = "djhjkfd"; text = "qqqqqqqq"; } }
package com.atguigu.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 购买电脑的人 * * @author qmwh * @create 2019-05-31 16:41 */ public class Customer { public static void main(String[] args) { final Producer pro = new Producer(); IProducer ipo = (IProducer) Proxy.newProxyInstance(pro.getClass().getClassLoader(), pro.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //进行方法的增强 Object returnValue = null; System.out.println("这个"+args[0]); //代理商从中赚取差价 Double money = (Double)args[0]; //double money = 20000; //2.判断当前方法是不是销售 if("sale".equals(method.getName())) { returnValue = method.invoke(pro, money*0.8); } return returnValue; } }); ipo.sale(10000); } }
import java.util.ArrayList; import java.util.List; /** * Created by andrefedorenko on 09.07.17. */ public class Manager { private List<Person> listPerson; private List<LV> listLV; private List<Student> studentList; public void initPerson(){ listPerson = new ArrayList<>(); for(int i=0; i < 10; i++ ){ //Person p = new Person(i,String.valueOf(i) + "idkName", String.valueOf(i) + "idkLastName"); listPerson.add(new Person(i,String.valueOf(i) + "idkName", String.valueOf(i) + "idkLastName")); } } public void initLV(){ listLV = new ArrayList<>(); for(int i=0; i < 100; i++ ){ LV lv = new LV(); lv.setLvid(i); lv.setLvName(String.valueOf(i) + "idkLvName"); listLV.add(lv); } } public void initStudent(){ studentList = new ArrayList<>(); for(int i=0; i < 100; i++ ){ Student student = new Student(i,String.valueOf(i) + "idkName", String.valueOf(i) + "idkLastName"); student.setMatNr(i+100); for(LV lv : listLV){ if(i%2 == 0){ student.setLvs(listLV); } } } } public List<Person> getPerson(){ return listPerson; } public List<LV> getLV(){ return listLV; } public List<Student> getStudent(){ return studentList; } }
package cn.kgc.service; import cn.kgc.domain.Member; import cn.kgc.domain.User; import java.util.List; public interface VEditService { public boolean editphone(String phone); public List balanceedit(float balance, String username); public boolean insertV(Member member); List<Member> findAll(); List<User> findUser(); }
package io.chark.food.domain.thread; import com.fasterxml.jackson.annotation.JsonBackReference; import io.chark.food.domain.BaseEntity; import io.chark.food.domain.authentication.account.Account; import io.chark.food.domain.comment.Comment; import io.chark.food.domain.thread.category.ThreadCategory; import javax.persistence.*; import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; @Entity public class Thread extends BaseEntity { //TODO Add title column to entities diagram @ManyToOne private Account account; @Column(nullable = false) private String title; @Size(max = DEFAULT_LONG_LENGTH) @Column(length = DEFAULT_LONG_LENGTH) private String description; private String threadLink; @Column(nullable = false) private Date creationDate = new Date(); private Date editDate = new Date(); private int currentlyViewing; private int viewCount; private boolean registrationRequired; @ManyToOne(fetch = FetchType.EAGER) private ThreadCategory threadCategory; @OneToMany @OrderBy("rating DESC") private List<Comment> comments; public Thread() { } public Date getEditDate() { return editDate; } public void removeComment(Comment comment) { this.comments.remove(comment); } public int getCurrentlyViewing() { return currentlyViewing; } public int getViewCount() { return viewCount; } public void setViewCount(int viewCount) { this.viewCount = viewCount; } public Thread(Account account, String title, String description, boolean registrationRequired, ThreadCategory threadCategory) { this.account = account; this.title = title; this.description = description; this.registrationRequired = registrationRequired; this.threadCategory = threadCategory; this.comments = new ArrayList<>(); } public void setComments(List<Comment> comments) { this.comments = comments; } public void setDescription(String description) { this.description = description; } public void setTitle(String title) { this.title = title; } public void setThreadLink(String threadLink) { this.threadLink = threadLink; } public void setAccount(Account account) { this.account = account; } public void setRegistrationRequired(boolean registrationRequired) { this.registrationRequired = registrationRequired; } public void setThreadCategory(ThreadCategory threadCategory) { this.threadCategory = threadCategory; } public void setEditDate(Date editDate) { this.editDate = editDate; } public Account getAccount() { return account; } public Date getCreationDate() { return creationDate; } public String getDescription() { return description; } public String getMonthYear(){ Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(this.creationDate.getTime()); return cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.YEAR); } public void addComment(Comment c){ comments.add(c); } public boolean isRegistrationRequired() { return registrationRequired; } public String getThreadLink() { return threadLink; } public List<Comment> getComments() { return comments; } public String getTitle() { return title; } public int incremenetViewCount(){ return ++this.viewCount; } public ThreadCategory getThreadCategory() { return threadCategory; } }
package main.api.util.date; import java.sql.SQLOutput; import java.util.Date; public class Test01 { public static void main(String[] args) { // java.util.Data // - 생성자 Deprecated가 많다 : Y2K 때문 Date a = new Date(); System.out.println(a); // 연월일을 설정하는 생성자 (Depreciate) Date b = new Date(2020, 10, 23); // 경고 + 표식이 나온다. // 여러 문제점으로 앞으로 쓰지 말것을 권장 - 사라질 수 있다. System.out.println(b); // Tue Nov 23 00:00:00 KST 3920 // 문제점 : 시간이 한국인 정서에 맞지 않게 나온다. // 해결책 : 시간 형식을 설정하는 클래스를 찾아서 사용 } }
package com.example.ecoleenligne.model; public class Subscription { private int id; private String price; private Subject subject; private Level level; public Subscription(int id, Subject subject) { this.id = id; this.subject = subject; } public Subscription(int id, Subject subject, String price, Level level) { this.id = id; this.subject = subject; this.price = price; this.level = level; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Subject getSubject() { return subject; } public void setSUbject(Subject subject) { this.subject = subject; } public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } }
class Fancy { void print(String str) { str = str.replace(" ", " 🎇 "); str = "🎇 " + str + " 🎇"; System.out.println(str); } } public class Main { public static void main(String[] args) { Fancy fancy = new Fancy(); String str = "This is a fancy project."; fancy.print(str); } }
package com.teamdev.persistence.repository; import com.teamdev.persistence.UserRepository; import com.teamdev.persistence.dom.User; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @Repository public class UserRepositoryImpl implements UserRepository { private Map<Long, User> users = new HashMap<>(); private AtomicLong id = new AtomicLong(1); public UserRepositoryImpl() { } public User findById(long id) { return users.get(id); } public User findByMail(String mail) { User user = users.values().stream().filter(x -> x.getEmail().equals(mail)).findFirst().orElse(null); return user; } public Collection<User> findAll() { return users.values(); } public int userCount() { return users.size(); } public void update(User user) { if (user.getId() == 0) { user.setId(id.getAndIncrement()); } users.put(user.getId(), user); } public void delete(long id) { users.remove(id); } }
package net.mv.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestDoSomething { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationcontext.xml"); DoSomething ds = (DoSomething)ctx.getBean("doStuff"); ds.method(); System.out.println("<---------------->"); ds.method2(); } }
package de.cm.osm2po.snapp; public interface AppListener { void onGpsSignal(double lat, double lon, float bearing); void onPathPositionChanged(double lat, double lon, float bearing); void onModeChanged(); void onRouteChanged(); void onRouteLost(); }
package com.sunny.concurrent.concurrenttool; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * <Description> CountDownLatch的构造函数接收一个int类型的参数作为计数器,如果你想等待N个点完成, * 这里就传入N。当我们调用CountDownLatch的countDown方法时,N就会减1,CountDownLatch的await方法会阻塞当前线程, * 直到N变成零。由于countDown方法可以用在任何地方,所以这里说的N个点,可以是N个线程,也可以是1个线程里的N个执行步骤。 * 用在多个线程时,只需要把这个CountDownLatch的引用传递到线程里即可。<br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/08/10 10:08 <br> * @see com.sunny.concurrent.concurrenttool <br> */ public class CountDownLatchTest { static CountDownLatch c = new CountDownLatch(2); public static void main(String[] args) throws InterruptedException { new Thread(() -> { System.out.println(1); c.countDown(); System.out.println(2); c.countDown(); }).start(); //Thread.sleep(10000); TimeUnit.MILLISECONDS.sleep(10000); System.out.println(3); } }
package za.ac.cput.chapter5assignment.factorymethod; /** * Created by student on 2015/03/12. */ public class Dog implements Animal{ @Override public String sound() { return "woof"; } }
//package com.grandsea.ticketvendingapplication.activity; // //import android.app.Instrumentation; //import android.app.PendingIntent; //import android.content.BroadcastReceiver; //import android.content.Context; //import android.content.Intent; //import android.content.IntentFilter; //import android.hardware.usb.UsbDevice; //import android.hardware.usb.UsbManager; //import android.os.Bundle; //import android.support.annotation.Nullable; //import android.support.v7.app.AppCompatActivity; //import android.support.v7.widget.LinearLayoutManager; //import android.support.v7.widget.RecyclerView; //import android.util.Log; //import android.view.KeyEvent; //import android.view.View; //import android.widget.Button; //import android.widget.TextView; //import android.widget.Toast; // //import com.google.gson.Gson; //import com.grandsea.ticketvendingapplication.R; //import com.grandsea.ticketvendingapplication.adapter.GsonAdapter; //import com.grandsea.ticketvendingapplication.adapter.PassengerAdapter; //import com.grandsea.ticketvendingapplication.constant.IntentKey; //import com.grandsea.ticketvendingapplication.constant.UrlConstant; //import com.grandsea.ticketvendingapplication.constant.DefaultConfig; //import com.grandsea.ticketvendingapplication.dao.PassengerDao; //import com.grandsea.ticketvendingapplication.model.bean.OrderInfo; //import com.grandsea.ticketvendingapplication.model.bean.Passenger; //import com.grandsea.ticketvendingapplication.activity.third_party.HIDTestNoUse.ShowIDCardPicDialog; //import com.grandsea.ticketvendingapplication.util.BasicUtil; //import com.grandsea.ticketvendingapplication.util.DealStrSubUtil; //import com.zhy.http.okhttp.OkHttpUtils; //import com.zhy.http.okhttp.callback.StringCallback; // //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // //import okhttp3.Call; //import okhttp3.MediaType; // ///** // * 乘客 // * */ //public class PassengerActivity extends AppCompatActivity implements GsonAdapter,View.OnClickListener { // // private static final String TAG = "PassengerActivity"; // private OrderInfo orderInfo /*= new OrderInfo()*/; // private RecyclerView passengerRecyclerView; // private TextView shiftNameTextView; // private Button btPassengerBack; // private Button btAddPassenger; // private TextView tvTotalPrice; // private Button btPay; // private PassengerAdapter passengerAdapter; // private List<Passenger> passengers = new ArrayList<>(); //// private Shift shift = new Shift(); // // //读取身份证所需字段 // private TextView mTextView; //提示字段 // private boolean mSecondCard; // private UsbDevice mDevice; // private iDRHIDDev mHIDDev; // private UsbManager mUsbManager; // private ShowIDCardPicDialog mShowIDCardPicDialog; // private iDRHIDDev.SecondIDInfo sIDInfo; // private static final String ACTION_USB_PERMISSION = "com.Routon.HIDTest.USB_PERMISSION"; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_passenger); // // //获取数据 // Intent i = getIntent(); // orderInfo = (OrderInfo)i.getSerializableExtra(IntentKey.EXTRA_SHIFT_TO_PASSENGER_OBJ); // // if(orderInfo == null){ // orderInfo = new OrderInfo(); // } // shiftNameTextView = (TextView)findViewById(R.id.shift_name_txt); // passengerRecyclerView = (RecyclerView)findViewById(R.id.passenger_recycler_view_id); // btPassengerBack = (Button) findViewById(R.id.bt_passenger_back); // btAddPassenger = (Button) findViewById(R.id.bt_add_passenger); // tvTotalPrice =(TextView) findViewById(R.id.tv_total_price); // btPay =(Button) findViewById(R.id.bt_pay); // mTextView = (TextView) findViewById(R.id.textView1); // mTextView.setText("身份证阅读程序:"); // // btAddPassenger.setOnClickListener(this); //添加乘车人 // // shiftNameTextView.setText(orderInfo.getGetOnStation() +" --> " + orderInfo.getTakeOffStation() +" "); // // passengerRecyclerView.setLayoutManager(new LinearLayoutManager(PassengerActivity.this)); // // btPassengerBack.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // new Thread() { // public void run() { // try { // Instrumentation inst = new Instrumentation(); // inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); // } catch (Exception e) { // Log.e("Exception when sendKeyDownUpSync", e.toString()); // } // } // }.start(); // } // }); // // // // passengers = PassengerDao.getPassenger(); //// passengers = new ArrayList<>(); // passengerAdapter = new PassengerAdapter(passengers,orderInfo); // passengerRecyclerView.setAdapter(passengerAdapter); // //初始化价格 // if(passengers != null || passengers.size() >0){ // updateTotalPrice(passengers.size()); // // } // // // passengerAdapter.setOnItemClickListener(new PassengerAdapter.OnItemClickListener() { // @Override // public void onItemClick(int position) { // // Toast.makeText(PassengerActivity.this,"移除用户:"+passengers.get(position).getName(),Toast.LENGTH_LONG).show(); // passengers.remove(position); // // passengerAdapter.notifyDataSetChanged(); // } // }); // // // //跳转支付页面:下单 // btPay.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Toast.makeText(PassengerActivity.this,"点击支付。。",Toast.LENGTH_LONG).show(); // Intent intent = new Intent(PassengerActivity.this,PayActivity.class); // int status = submitOrder(orderInfo,passengers); // intent.putExtra(IntentKey.ORDER_INFO,orderInfo); //// if(status >0 ){ //// startActivity(intent); //// } // startActivity(intent); // } // }); // // // //*******************身份证读取功能******************************************************************** //// PosUtil.setRfidPower(PosUtil.RFID_POWER_ON); // // initialize card idInfo // mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); // mDevice = null; // mHIDDev = new iDRHIDDev(); // // initialize card idInfo // mSecondCard = true; //// clearSecondCardInfo(); //// clearTypeACardInfo(); // // // listen for new devices // IntentFilter filter = new IntentFilter(); // filter.addAction(ACTION_USB_PERMISSION); // filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); // registerReceiver(mUsbReceiver, filter); // // // 检查USB设备是否插入 // for (UsbDevice device : mUsbManager.getDeviceList().values()) { // // Log.e(TAG, "vid: " + device.getVendorId() + " pid:" + device.getProductId()); // if (device.getVendorId() == 1061 && device.getProductId() == 33113) { // Intent intent = new Intent(ACTION_USB_PERMISSION); // PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, intent, 0); // mUsbManager.requestPermission(device, mPermissionIntent); // Log.d(TAG, "usb device: checked"); // appendLog("发现读卡设备"); // } // } // // mShowIDCardPicDialog = new ShowIDCardPicDialog(this); // } // // //更新总价 // private void updateTotalPrice(int size) { // tvTotalPrice.setText(orderInfo.getPrice()*size + ""); // } // // private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { // @Override // public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); // // if (ACTION_USB_PERMISSION.equals(action)) { // synchronized (this) { // UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); // // if (mDevice != null) { // mHIDDev.closeDevice(); // mDevice = null; // } // // if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { // if (device != null) { // // call method to set up device communication // // final int ret = mHIDDev.openDevice(mUsbManager, device); // Log.i(TAG, "open device:" + ret); // if (ret == 0) { // mDevice = device; // appendLog("usb device: 已授权"); // } else { // mDevice = null; // appendLog("usb device: 授权失败"); // } // } // } else { // Log.d(TAG, "permission denied for device " + device); // appendLog("usb device: 未授权"); // finish(); // } // } // } // } // }; // // private void appendLog(String log) { // log = mTextView.getText() + "\n" + log; // //// Toast.makeText(this,"log:"+log,Toast.LENGTH_LONG).show(); // mTextView.setText(log); // } // private int submitOrder(OrderInfo orderInfo, List<Passenger> passengers) { // int status = 0; // Passenger passenger = passengers.get(0); // orderInfo.setName(passenger.getName()); // orderInfo.setPhone(passenger.getPhone()); // orderInfo.setIdCard(passenger.getIdCard()); // orderInfo.setTicketNum(passengers.size()); // orderInfo.setTotalPrice(orderInfo.getPrice()*passengers.size()); // orderInfo.setPassengers(gson.toJson(passengers)); //// Log.d(TAG,gson.toJson(orderInfo)); // // Map<String,Object> paramMap = new HashMap(); // paramMap.put("orderInfo",orderInfo); // String requestContent =new Gson().toJson(BasicUtil.buildPostData("58ff4eddda0e83185baa7eb7cc4fc5d1","13588888888",paramMap)) ; // Log.d(TAG,requestContent); // OkHttpUtils // .postString() // .url(UrlConstant.ORDER_TICKET) // .mediaType(MediaType.parse("application/json; charset=utf-8")) // .content(requestContent) // .build() // .execute(new StringCallback(){ // // @Override // public void onError(Call call, Exception e, int i) { // Toast.makeText(PassengerActivity.this,"网络异常,请重新刷新", Toast.LENGTH_LONG).show(); // e.printStackTrace(); // } // // @Override // public void onResponse(String s, final int i) { // Log.d(TAG,s); // Toast.makeText(PassengerActivity.this,"s:"+s,Toast.LENGTH_LONG).show(); // //// GsonObject dataGson = new GsonObject(gson.fromJson(s, JsonObject.class)); //对数据转换成json后进行对象封装 // // // } // // }); //// status=1; // // return status; // } // // // @Override // public void onClick(View v) { // if(v == btAddPassenger){ //添加乘车人功能 // /* new Handler().postDelayed(new Runnable() { // @Override // public void run() { // getIDInfo(); // } // },3000);*/ // getIDInfo(); // } // } // // public void getIDInfo() { // if(passengers.size() >= DefaultConfig.MAX_PASSENGER_COUNT){ // Toast.makeText(PassengerActivity.this, // "Sorry,最多能添加"+ DefaultConfig.MAX_PASSENGER_COUNT +"位乘客",Toast.LENGTH_LONG).show(); // return; // } //// String iDInfo = "姓 名:杨声劲\n" + //// 性 别:男\n" + //// 名 族:汉\n" + //// 生 日:1994****\n" + //// 住 址:广东省汕尾市" + //// 身份证号:441501********5051\n" + //// 发证机关:汕尾市公安局********\n" + //// 有效日期:20121203-20221203\n"; // //// // int ret = findCard(); // if(ret < 0){ // int i=0; // while(i<=8){ // try { // Thread.sleep(500); // i++; // ret = findCard(); // if(ret > 0){ // break; // } // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // } // Passenger passenger = null; // if (ret >= 0) // 找到卡 // { // // 读卡 // sIDInfo = mHIDDev.new SecondIDInfo(); // byte[] fingerPrint = new byte[1024]; // // // ret = mHIDDev.ReadBaseMsg(sIDInfo); // ret = mHIDDev.ReadBaseFPMsg(sIDInfo, fingerPrint); // // if (ret < 0) { // appendLog("读卡失败:"); // return; // } // appendLog(sIDInfo.fingerPrint == 1024 ? "有指纹" : "无指纹"); // // 设置蜂鸣器和LED灯 // ret = mHIDDev.BeepLed(true, true, 500); // // passenger = new Passenger(); // String iDInfo = sIDInfo.getFormatIDCardText(); // String name = DealStrSubUtil.getSubUtilSimple(iDInfo,"姓 名:(.*?)\n"); //返回第一个符合的数据 // String idCard = DealStrSubUtil.getSubUtilSimple(iDInfo,"身份证号:(.*?)\n"); //返回第一个符合的数据 // passenger.setName(name); // passenger.setIdCard(idCard); // // 刷新显示 //// invalidate(); //// Toast.makeText(this,"身份证信息"+sIDInfo.getFormatIDCardText(),Toast.LENGTH_LONG).show(); // } else // 未找到卡 // { // iDRHIDDev.MoreAddrInfo mAddr = mHIDDev.new MoreAddrInfo(); // // 通过读追加地址来判断卡是否在机具上。 // ret = mHIDDev.GetNewAppMsg(mAddr); // if (ret < 0) // 机具上没有放卡 // appendLog("请放卡:"); // else // 机具上的卡已读过一次 // appendLog("请重新放卡:"); // return ; // } // // // 读卡号, 注意不要放在读身份证信息前面,否则会读身份证信息失败 // byte data[] = new byte[32]; // int www = mHIDDev.getIDCardCID(data); // if (www < 0) { // appendLog("读卡号失败:" + www); // } else { // String cardID = String.format("%s %02x%02x%02x%02x%02x%02x%02x%02x", "卡体号:", data[0], data[1], data[2], // data[3], data[4], data[5], data[6], data[7]); // appendLog(cardID); // } // if(passenger !=null ){ // if(!passengers.contains(passenger)){ // passengers.add(passenger); // updateTotalPrice(passengers.size()); // } // } // passengerAdapter.notifyDataSetChanged(); //// return IDInfo; // } // // private int findCard() { // //TODO 下面是实现读取身份证外设接口 // Passenger passenger = null; //// passenger.setIdCard("44888**************8889"); //// passenger.setName("从康007"); // // mTextView.setText("读二代证:"); // mSecondCard = true; //// clearSecondCardInfo(); // // if (mDevice == null) { // appendLog("请插入读卡器!"); // return 0; // } // // int ret; // // // 读安全模块的状态 // ret = mHIDDev.GetSamStaus(); // if (ret < 0) { // appendLog("读卡器未准备好!"); // return ret; // } // // iDRHIDDev.SamIDInfo samIDInfo = mHIDDev.new SamIDInfo(); // // // 读安全模块号 // ret = mHIDDev.GetSamId(samIDInfo); // appendLog("samid: " + samIDInfo.samID); // // // 找卡 // ret = mHIDDev.Authenticate(); // return ret; // } //}
package com.esum.comp.dbm.table; import java.io.File; import java.util.Hashtable; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import com.esum.comp.dbm.DBCode; import com.esum.comp.dbm.DBConfig; import com.esum.comp.dbm.DBMException; import com.esum.framework.common.util.SysUtil; import com.esum.framework.jdbc.SqlParameterValue; import com.esum.framework.jdbc.SqlParameterValues; /** * DB TriggerInfo * - DB Trigger 정보를 관리하기 위한 클래스 * * Copyright(c) eSum Technologies., inc. All rights reserved. */ public class TriggerInfo { public static final int DEFAULT_TRIGGER_UPDATE = 1; public static final int USER_TRIGGER_UPDATE = 2; public static final int NO_UPDATE = 0; private static Hashtable<String, TriggerInfo> triggerInfoList = new Hashtable<String, TriggerInfo>(); private int selectStmtFetchSize = 300; private int maxThreadCnt = 5; private int triggerInterval = 5000; private String triggerSchedule; private String triggerSql; /** Trigger Update Mode setup : 1 (Update internal interface-table) or 2 (Use update query) or 0 (None) */ private int triggerUpdateMode = NO_UPDATE; private String triggerInterfaceTable; private String triggerSuccessUpdateSql; private String triggerErrorUpdateSql; /** * getInstance() * - 입력받은 triggerId 에 대하여 이미 생성되어 있는 TriggerInfo 를 반환한다. * - 생성되어 있는 TriggerInfo 가 없는 경우, 새로 생성하여 반환한다. */ public static synchronized TriggerInfo getInstance(String triggerId) throws DBMException { if(!triggerInfoList.containsKey(triggerId)) return newInstance(triggerId); return (TriggerInfo) triggerInfoList.get(triggerId); } /** * newInstance() * - 입력받은 triggerId 에 대하여 * 기존에 생성되어 있는 TriggerInfo 를 삭제하고 새로 만들어서 반환한다. * 물론, 없는 경우도 새로 만들어서 반환한다. * - Trigger properties 의 값이 갱신되었을 경우 그 값을 Trigger 시작시점에 반영하게 하기 위해 사용한다. */ public static synchronized TriggerInfo newInstance(String triggerId) throws DBMException { TriggerInfo triggerInfo = null; if(triggerInfoList.containsKey(triggerId)) { triggerInfo = removeInstance(triggerId); triggerInfo = null; } triggerInfo = new TriggerInfo(triggerId); triggerInfoList.put(triggerId, triggerInfo); return triggerInfo; } public static synchronized TriggerInfo removeInstance(String triggerId) { return (TriggerInfo) triggerInfoList.remove(triggerId); } private TriggerInfo(String triggerId) throws DBMException { Properties p = new Properties(); try { if(StringUtils.isEmpty(DBConfig.DBM_TRIGGER_PROP_PATH)) { DBConfig.DBM_TRIGGER_PROP_PATH = System.getProperty("xtrus.home")+"/conf/dbm/trigger"; } if(StringUtils.isEmpty(DBConfig.DBM_CONNECTION_PROP_PATH)) { DBConfig.DBM_CONNECTION_PROP_PATH = System.getProperty("xtrus.home")+"/conf/dbm/dbconnection"; } String configFileName = DBConfig.DBM_TRIGGER_PROP_PATH + File.separator + triggerId; SysUtil.loadPropertiesWithoutReplaceValue(configFileName, p); /** DB Listener Setting Value */ selectStmtFetchSize = Integer.parseInt(p.getProperty("stmt.fetch.size", "300")); maxThreadCnt = Integer.parseInt(p.getProperty("proc.thread.max.cnt", "5")); /** DB Trigger Setup */ triggerInterval = Integer.parseInt(p.getProperty("trigger.interval", "0")); triggerSchedule = p.getProperty("trigger.schedule", null); if(triggerInterval==0 && triggerSchedule==null) throw new DBMException(DBCode.ERROR_LOAD_TRIGGERINFO, "TriggerInfo()", "Fail to load the trigger properties. check the trigger.interval or trigger.schedule"); triggerSql = p.getProperty("trigger.sql"); /** Trigger Update Mode setup : 1 (Update internal interface-table) or 2 (Use update query) or 0 (None) */ triggerUpdateMode = Integer.parseInt(p.getProperty("trigger.update.mode", "0").trim()); if(triggerUpdateMode == DEFAULT_TRIGGER_UPDATE) { triggerInterfaceTable = p.getProperty("trigger.interface.table", "DBM_IFMST"); } else if(triggerUpdateMode == USER_TRIGGER_UPDATE) { triggerSuccessUpdateSql = p.getProperty("trigger.success.update.sql"); triggerErrorUpdateSql = p.getProperty("trigger.error.update.sql"); } } catch (DBMException e){ throw e; } catch (Exception e) { throw new DBMException(DBCode.ERROR_LOAD_TRIGGERINFO, "TriggerInfo()", "Fail to load the trigger properties file (" + triggerId + ")."); } } public int getSelectStmtFetchSize() { return selectStmtFetchSize; } public int getMaxThreadCnt() { return maxThreadCnt; } public String getTriggerSql() { return triggerSql; } public int getTriggerInterval() { return triggerInterval; } public String getTriggerSchedule() { return triggerSchedule; } public int getTriggerUpdateMode() { return triggerUpdateMode; } public String getTriggerTable() { return triggerInterfaceTable; } public String getTriggerSuccessUpdateSql() { return triggerSuccessUpdateSql; } public String getPreparedTriggerSuccessUpdateSql() { return convertToPreparedSql(triggerSuccessUpdateSql); } public SqlParameterValues getTriggerSuccessUpdateParams(String[] keyValue, Map<String, String> userVariables) { return createSqlParams(triggerSuccessUpdateSql, keyValue, userVariables); } public String getTriggerErrorUpdateSql() { return triggerErrorUpdateSql; } public String getPreparedTriggerErrorUpdateSql() { return convertToPreparedSql(triggerErrorUpdateSql); } public SqlParameterValues getTriggerErrorUpdateParams(String[] keyValue, Map<String, String> userVariables) { return createSqlParams(triggerErrorUpdateSql, keyValue, userVariables); } /** * query의 예약어 부분('${'와 '}'로 둘러싸인 부분)을 '?'로 치환하여 PreparedSQL 형태로 만든다. */ private String convertToPreparedSql(String orgSql) { if (orgSql.indexOf("${") < 0) return orgSql; else { StringBuffer queryBuffer = new StringBuffer(); int offset = 0; int fromIndex = 0, toIndex = 0; while ((fromIndex = orgSql.indexOf("${", offset)) != -1) { if (fromIndex > offset) queryBuffer.append(orgSql.substring(offset, fromIndex)); toIndex = orgSql.indexOf("}", fromIndex); if (toIndex == -1) break; queryBuffer.append("?"); offset = toIndex + 1; } if (offset < orgSql.length()) queryBuffer.append(orgSql.substring(offset)); return queryBuffer.toString(); } } /** * prepared query 에서 사용할 파라메터를 리턴한다. * - ? 에 대해서는 입력받은 keyValue의 값을 순서대로 맵핑하고, * - 예약어(${~})에 대해서는 입력받은 userVariables의 해당 값을 맵핑한다. */ private SqlParameterValues createSqlParams(String query, String[] keyValue, Map<String, String> userVariables) { SqlParameterValues params = new SqlParameterValues(); if (query.indexOf("${") < 0) { int paramLength = StringUtils.countMatches(query, "?"); int index = 1; while (index <= paramLength) { params.add(new SqlParameterValue(keyValue[index-1])); index++; } } else { int keyIdx = 0; int offset = 0; int fromIndex = 0, toIndex = 0; while ((fromIndex = query.indexOf("${", offset)) != -1) { if (fromIndex > offset) { int paramCnt = StringUtils.countMatches(query.substring(offset, fromIndex), "?"); for (int i=0; i<paramCnt; i++, keyIdx++) params.add(new SqlParameterValue(keyValue[keyIdx])); } toIndex = query.indexOf("}", fromIndex); if (toIndex == -1) break; String key = query.substring(fromIndex + 2, toIndex); Object obj = userVariables.get(key); String value = null; if (obj == null) value = ""; else value = (String)obj; params.add(new SqlParameterValue(value)); offset = toIndex + 1; } if (offset < query.length()) { int paramCnt = StringUtils.countMatches(query.substring(offset), "?"); for (int i=0; i<paramCnt; i++, keyIdx++) params.add(new SqlParameterValue(keyValue[keyIdx])); } } return params; } }
package com.mq.starter.mq.starter.resources; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Random; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import javax.jms.Queue; @RestController public class ProducerResource { @Autowired private JmsTemplate jmsTemplate; @Autowired private JmsTemplate jmsTemplate2; @Autowired private Queue reqQueue; @Autowired private Queue resQueue; @GetMapping("/create/{message}") public String publish(@PathVariable("message") final String message) throws ExecutionException, InterruptedException { final String correlationId = UUID.randomUUID().toString(); /*System.out.println(reqQueue.hashCode()+" "+correlationId); int rand = new Random().nextInt(2); if(rand == 0){ jmsTemplate.convertAndSend(reqQueue, message, new CorrelationIdPostProcessor(correlationId)); System.out.println("Published message to request queue of server1 with message "+message+" and correlation Id "+correlationId); }else{ jmsTemplate2.convertAndSend(reqQueue, message, new CorrelationIdPostProcessor(correlationId)); System.out.println("Published message to request queue of server2 with message "+message+" and correlation Id "+correlationId); } jmsTemplate.setReceiveTimeout(4000); jmsTemplate2.setReceiveTimeout(4000); String responseMessage = (String) jmsTemplate .receiveSelectedAndConvert(resQueue, "JMSCorrelationID='" + correlationId + "'"); String responseMessage2 = (String) jmsTemplate2 .receiveSelectedAndConvert(resQueue, "JMSCorrelationID='" + correlationId + "'"); */ Object resp = null; try { resp = new CompletableFutureTest().subscribeAndGet(correlationId, jmsTemplate, jmsTemplate2, reqQueue, resQueue, message); } catch (TimeoutException e) { return "Timed out"; } if(resp == null){ return "No message recieved"; }else{ return "Published OK with message from server: "+resp.toString(); } } /*private class CorrelationIdPostProcessor implements MessagePostProcessor { private final String correlationId; public CorrelationIdPostProcessor(final String correlationId) { this.correlationId = correlationId; } @Override public Message postProcessMessage(final Message msg) throws JMSException { msg.setJMSCorrelationID(correlationId); return msg; } }*/ }
package com.hfjy.framework.message; import java.io.Serializable; public class MessageData implements Cloneable, Serializable { private static final long serialVersionUID = 1L; String name; byte[] data; public MessageData(String name, byte[] data) { this.name = name; this.data = data; } public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } @Override protected MessageData clone() throws CloneNotSupportedException { return (MessageData) super.clone(); } }
package ru.steagle.views; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import ru.steagle.R; import ru.steagle.config.Keys; import ru.steagle.service.SteagleService; /** * Created by bmw on 08.02.14. */ public class SettingsFragment extends PreferenceFragment { private SharedPreferences prefs; private SharedPreferences.OnSharedPreferenceChangeListener listener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); listener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (Keys.AUTO_LOAD.getPrefKey().equals(key)) { boolean autoLoad = prefs.getBoolean(Keys.AUTO_LOAD.getPrefKey(), false); Intent i = new Intent(getActivity(), SteagleService.class); if (autoLoad) { getActivity().startService(i); } else { getActivity().stopService(i); } } } }; prefs.registerOnSharedPreferenceChangeListener(listener); } @Override public void onDestroy() { prefs.unregisterOnSharedPreferenceChangeListener(listener); super.onDestroy(); } }
package com.lesports.albatross.fragment.learning; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.google.gson.reflect.TypeToken; import com.handmark.pulltorefresh.library.ILoadingLayout; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.lesports.albatross.Constants; import com.lesports.albatross.R; import com.lesports.albatross.activity.learning.LearningDetailActivity; import com.lesports.albatross.adapter.learn.TeachingNewsAdapter; import com.lesports.albatross.entity.CommonEntity; import com.lesports.albatross.entity.HttpRespObjectEntity; import com.lesports.albatross.entity.learn.TeachingAlbumEntity; import com.lesports.albatross.fragment.BaseFragment; import com.lesports.albatross.json.GsonHelper; import com.lesports.albatross.utils.NetworkUtil; import com.lesports.albatross.utils.StringUtils; import com.lesports.albatross.utils.UIUtils; import com.lesports.albatross.utils.user.LearningUtils; import org.json.JSONObject; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; /** * 乐学 - 教学 * 比赛相关新闻 --支持下拉刷新 * Created by zhouchenbin on 16/6/8. */ public class LearningNewsFragment extends BaseFragment{ private String TAG = getClass().getName(); private PullToRefreshListView pullToRefreshListView; private int Page = 0, Size = 10; private boolean isMore = false; private LearningDetailActivity activity ; private String teachingId ; private TeachingNewsAdapter teachingNewsAdapter; private final int REFRESH = 102; //执行刷新ui操作的标识 //fragment和activity的消息传递 public Handler newsHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case REFRESH: //执行刷新操作,第一页 Page = 0; getCompetNewsData(msg.getData().getString("videoId")); break; default: break; } } }; @Override public View viewBindLayout(LayoutInflater inflater) { return inflater.inflate(R.layout.learn_news,null); } @Override public void viewBindId(View view) { pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.match_related_news_listview); } @Override public void resourcesInit(Bundle data) { teachingId = LearningUtils.getTeachingId(getActivity()); // adapter = new CompertitionMoreNewsAdapter(getActivity()); teachingNewsAdapter = new TeachingNewsAdapter(getActivity()); } @Override public void viewInit(LayoutInflater inflater) { pullToRefreshListView.setAdapter(teachingNewsAdapter); pullToRefreshListView.setShowIndicator(false); pullToRefreshListView.setPullToRefreshOverScrollEnabled(false); initIndicator(pullToRefreshListView); pullToRefreshListView.setRefreshing(true); if (teachingId!=null){ getCompetNewsData(teachingId); } } @Override public void viewBindListener() { pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG,"position="+position+";id="+id); //position 1开始 id 从0开始 sendMessageToActivity(String.valueOf(teachingNewsAdapter.getItem((int) id).getId()), teachingNewsAdapter.getItem((int) id).getTitle()); } }); pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { //下拉刷新 @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL); label = "上次更新于" + label; refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); Page = 0; isMore = false; try { getCompetNewsData(teachingId); } catch (Exception e) { e.printStackTrace(); } } //上拉 @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { isMore = true; Page++; try { getCompetNewsData(teachingId); } catch (Exception e) { e.printStackTrace(); } } }); } private void initIndicator(PullToRefreshListView pullToRefreshListView) { pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH); ILoadingLayout startLabels = pullToRefreshListView .getLoadingLayoutProxy(true, false); startLabels.setPullLabel("下拉可以刷新");// 刚下拉时,显示的提示 startLabels.setRefreshingLabel("正在刷新数据中...");// 刷新时 startLabels.setReleaseLabel("松开立即刷新");// 下来达到一定距离时,显示的提示 ILoadingLayout endLabels = pullToRefreshListView.getLoadingLayoutProxy( false, true); endLabels.setPullLabel("上拉加载更多的数据"); endLabels.setRefreshingLabel("正在加载更多的数据...");// 刷新时 endLabels.setReleaseLabel("释放加载更多的数据");// 下来达到一定距离时,显示的提示 } /** * 获取资讯列表的数据 */ public void getCompetNewsData(String teachingId) { if (teachingId==null){ teachingId = LearningUtils.getTeachingId(getActivity()); } RequestParams params = new RequestParams(Constants.LEARNING_TEACH_LIST+"/"+teachingId+"/episodes"); params.setAsJsonContent(true); params.setCacheMaxAge(1000 * 300); params.addParameter("page", Page); params.addParameter("size", Size); // params.addParameter("type", "-1");//type 0:富文本新闻 1:视频 2:图文新闻 (新闻类型 x.http().get(params, new Callback.CacheCallback<String>() { @Override public void onSuccess(String result) { Page++; // LogUtil.i("result:" + result); if (result != null) { showNewsData(result); } } @Override public void onError(Throwable ex, boolean isOnCallback) { // Log.i(TAG, getString(R.string.base_request_fail_log)); Log.i(TAG,ex.getMessage().toString()); if (getActivity() != null && !NetworkUtil.isNetworkConnected(getActivity())) { UIUtils.showToast(getActivity(), getResources().getString(R.string.network_unreachable_title)); } } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { if (null != pullToRefreshListView) { pullToRefreshListView.onRefreshComplete(); } } @Override public boolean onCache(String result) { return false; } }); } public void showNewsData(String datas) { try { if (StringUtils.isNotEmpty(datas)) { JSONObject obj = new JSONObject(datas); int status = obj.getInt("code"); if (status == Constants.STATUS_SUCCESS) { // 正确 HttpRespObjectEntity<CommonEntity<TeachingAlbumEntity>> newsEntity = GsonHelper.fromJson(datas, new TypeToken<HttpRespObjectEntity<CommonEntity<TeachingAlbumEntity>>>() { }.getType()); if (isMore) teachingNewsAdapter.add(newsEntity.getData().getContent()); else teachingNewsAdapter.update(newsEntity.getData().getContent()); } } } catch (Exception e) { e.printStackTrace(); } finally { pullToRefreshListView.postDelayed(new Runnable() { @Override public void run() { if (null != pullToRefreshListView) { pullToRefreshListView.onRefreshComplete(); } } }, 500); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context != null) { activity = (LearningDetailActivity) context; } } //上行消息到activity private void sendMessageToActivity(String video_id,String name){ if ((activity=(LearningDetailActivity) getActivity())==null||activity.handler==null) return; Log.i(TAG,"activity!=NULL && video_id="+video_id); Bundle bundle = new Bundle(); bundle.putString("videoId",video_id); bundle.putString("resourceName",name); Message message = Message.obtain(); message.what = activity.CHICKCHANGE; message.setData(bundle); activity.handler.sendMessage(message); } }
package com.sohu.live56.view.login; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.sohu.live56.R; import com.sohu.live56.view.BaseTitleActivity; /** * 联合登录。 */ public class UnitLogin extends BaseTitleActivity implements View.OnClickListener { private EditText unitaccountet; private EditText unitpwdet; private Button loginbtn; @Override protected View onAddContainerView() { View view = View.inflate(getApplicationContext(), R.layout.activity_unit_login, null); initialize(view); return view; } private void initialize(View view) { unitaccountet = (EditText) view.findViewById(R.id.unit_account_et); unitpwdet = (EditText) view.findViewById(R.id.unit_pwd_et); loginbtn = (Button) view.findViewById(R.id.login_btn); unitaccountet.setOnClickListener(this); unitpwdet.setOnClickListener(this); loginbtn.setOnClickListener(this); } @Override protected void onStart() { super.onStart(); setTitletv(getResources().getString(R.string.title_unit_login)); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.unit_account_et: { break; } case R.id.unit_pwd_et: { break; } case R.id.login_btn: { break; } } } }
package mmt.core; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import mmt.core.NewParser; import java.util.Collection; import java.util.ArrayList; import java.io.FileNotFoundException; import java.io.IOException; import mmt.core.exceptions.ImportFileException; import mmt.core.exceptions.InvalidPassengerNameException; import mmt.core.exceptions.NoSuchPassengerIdException; import mmt.core.exceptions.NoSuchServiceIdException; import mmt.core.exceptions.NoSuchStationNameException; import mmt.core.exceptions.BadTimeSpecificationException; import mmt.core.exceptions.BadDateSpecificationException; /** * Facade for handling persistence and other functions. */ public class TicketOffice { /** The object doing most of the actual work. */ private TrainCompany _trainCompany; /** The name of the current file with data associated to this ticket office. */ private String _fileName; /** * Constructor. */ public TicketOffice() { _trainCompany = new TrainCompany(); _fileName = ""; } /** * Resets a TrainCompany, deleting its associated Passengers and Itineraries, * but not its associated Services. */ public void reset() { _trainCompany.deletePassengers(); //_trainCompany.deleteItineraries(); setFileName(""); } /** * Sets a new associated file name. * * @param fileName the new associated file's name. */ public void setFileName(String fileName) { _fileName = fileName; } /** * Returns a String with the this TicketOffice's associated file name. * * @return the associated file's name. */ public String getFileName() { return _fileName; } /** * Returns whether or not this TicketOffice has an associated file. * * @return if the TicketOffice has an associated file, return true; else, return false. */ public boolean hasAssociatedFile() { return _fileName != null && !_fileName.isEmpty(); } /** * Saves the associated TrainCompany's data to a file. * * @param fileName the name of the file to be saved. * @throws IOException if errors occur in file writing. */ public void save(String fileName) throws IOException { /* Opens the given file */ FileOutputStream fileOut = new FileOutputStream(fileName); ObjectOutputStream out = new ObjectOutputStream(fileOut); /* Writes new content */ out.writeObject(_trainCompany); /* Closes the pipe */ out.close(); fileOut.close(); } /** * Loads the new TrainCompany data from a file. * * @param fileName the name of the file from which the data will be loaded. * @throws IOException if errors occur in file reading. * @throws ClassNotFoundException if the file cannot be found. */ public void load(String fileName) throws IOException, ClassNotFoundException { /* Opens the given file */ FileInputStream fileIn = new FileInputStream(fileName); ObjectInputStream in = new ObjectInputStream(fileIn); /* Replaces the TrainCompany */ _trainCompany = (TrainCompany) in.readObject(); /* Closes the pipe */ in.close(); fileIn.close(); } /** * Imports the default Services, Passengers and Itineraries from a file. * * @param fileName the name of the import file. * @throws ImportFileException if the file cannot be properly read. */ public void importFile(String fileName) throws ImportFileException { /* Creates Parser */ NewParser parser = new NewParser(_trainCompany); /* Parses the File */ parser.parseFile(fileName); } /** * Changes a given passenger name. * * @param id of the passenger. * @param newname the new name to give the passenger * @throws NoSuchPassengerIdException if passenger id does not exist. * @throws InvalidPassengerNameException if passenger name is null or an empty String. */ public void changePassengerName(int id, String newname) throws NoSuchPassengerIdException, InvalidPassengerNameException { _trainCompany.changePassengerName(id, newname); } /** * Returns the next passenger's assigned id. * * @return the next passenger's assigned id. */ public int getNextPassengerId() { return _trainCompany.getNextPassengerId(); } /** * Add passenger. * * @param id the new passenger's id. * @param name the new passenger's name. * @throws InvalidPassengerNameException if passenger name is null or an empty String. */ public void addPassenger(int id, String name) throws InvalidPassengerNameException { Passenger p = new Passenger(id, name, _trainCompany); _trainCompany.addPassenger(p); } /** * Returns a collection containing the passengers of the TrainCompany. * * @return the collection of passengers of this TrainCompany ordered by id. */ public Collection<Passenger> getPassengers() { return _trainCompany.getPassengers(); } /** * Returns a passenger's String description, given it's id. * * @param id the passenger's id. * @return passenger String description. * @throws NoSuchPassengerIdException if passenger id does not exist. */ public String getPassengerDescription(int id) throws NoSuchPassengerIdException { return _trainCompany.getPassengerDescription(id); } /** * Returns a collection containing the services of the TrainCompany. * * @return the collection of services of this TrainCompany ordered by id. */ public Collection<Service> getServices() { return _trainCompany.getServices(); } /** * Get a service given its identifier. * * @param id the service's identifier. * @return the service with the given identifier. * @throws NoSuchServiceIdException if the service id does not exist. */ public Service getService(int id) throws NoSuchServiceIdException { return _trainCompany.getService(id); } /** * Looks up a service with a given start station name. * * @param search the station name to look for. * @return the service that has the search start station. * @throws NoSuchStationNameException if station name does not exist. */ public Collection<Service> searchServiceWithStartStation( String search ) throws NoSuchStationNameException { /* Service we are looking for */ return _trainCompany.searchServiceWithStartStation(search); } /** * Looks up a service with a given end station name. * * @param search the station name to look for. * @return the service that has the search end station. * @throws NoSuchStationNameException if station name does not exist. */ public Collection<Service> searchServiceWithEndStation( String search ) throws NoSuchStationNameException { /* Service we are looking for */ return _trainCompany.searchServiceWithEndStation(search); } /** * Looks up all possible itineraries for a given passenger. * * @param passengerId id of the passenger that is looking for the itinerary. * @param departureStation the station where the passenger wants to start his trip. * @param arrivalStation the date when the trip should start. * @param departureDate the time when the trip should start. * @return the possible itineraries for the passenger to buy. * @throws NoSuchStationNameException if station name does not exist. * @throws NoSuchPassengerIdException if the passenger id does not exist. * @throws BadTimeSpecificationException if the time isn't well formatted. * @throws BadDateSpecificationException if the date isn't well formatted. */ public ArrayList<Itinerary> searchItineraries(int passengerId, String departureStation, String arrivalStation, String departureDate, String departureTime) throws NoSuchPassengerIdException, BadTimeSpecificationException, NoSuchStationNameException, BadDateSpecificationException { return _trainCompany.searchItineraries(passengerId, departureStation, arrivalStation, departureDate, departureTime); } /** * Adds an itinerary to a passenger. * * @param id the id of the passenger who bought the itinerary. * @param itinerary the chosen itinerary. * @throws NoSuchPassengerIdException if the passenger id does not exist. */ public void commitItinerary(int passengerId, Itinerary itinerary) throws NoSuchPassengerIdException { _trainCompany.commitItinerary(passengerId, itinerary); } /** * Displays the itineraries bought by a given passenger. * * @param id passenger id to whom the itinaries belong. * @return the itineraries as a string. * @throws NoSuchPassengerIdException if the passenger id does not exist. */ public String showPassengerItineraries(int id) throws NoSuchPassengerIdException { return _trainCompany.showPassengerItineraries(id); } /** * Let's us know if a given passenger has purchased itineraries. * * @param id the id of the passenger. * @return true if the passenger has itineraries, false otherwise. * @throws NoSuchPassengerIdException if the passenger id does not exist. */ public boolean passengerHasItineraries(int id) throws NoSuchPassengerIdException { return _trainCompany.passengerHasItineraries(id); } /** * Looks up all itineraries in the TrainCompany. * * @return all itineraries in the TrainCompany. */ public String showAllItineraries() { return _trainCompany.showAllItineraries(); } /** * Updates all itinerary id's by one. */ public void updateListId(ArrayList<Itinerary> itineraryOptions) { _trainCompany.updateListId(itineraryOptions); } }
package com.redhat.service.bridge.infra.models.actions; import java.util.HashMap; import java.util.Map; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class BaseAction { @NotNull(message = "An Action must have a name") @JsonProperty("name") private String name; @NotNull(message = "An Action Type must be specified") @JsonProperty("type") private String type; @NotEmpty(message = "Action parameters must be supplied") @JsonProperty("parameters") private Map<String, String> parameters = new HashMap<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } }
/* * AlleleDepthBuilder */ package net.maizegenetics.dna.snp.depth; import ch.systemsx.cisd.hdf5.HDF5IntStorageFeatures; import ch.systemsx.cisd.hdf5.IHDF5Reader; import ch.systemsx.cisd.hdf5.IHDF5Writer; import net.maizegenetics.dna.snp.NucleotideAlignmentConstants; import net.maizegenetics.taxa.Taxon; import net.maizegenetics.util.HDF5Utils; import net.maizegenetics.util.SuperByteMatrix; import net.maizegenetics.util.SuperByteMatrixBuilder; import java.util.ArrayList; import java.util.List; /** * Builder to store information on DNA read depths. * * @author Terry Casstevens */ public class AlleleDepthBuilder { private static final HDF5IntStorageFeatures HDF5_FEATURES = HDF5IntStorageFeatures.createDeflation(2); private List<SuperByteMatrix> myDepths = null; private final boolean myIsHDF5; private IHDF5Writer myHDF5Writer = null; private final int myMaxNumAlleles; private final int myNumSites; private int myNumTaxa = 0; private AlleleDepthBuilder(IHDF5Writer writer, int numSites, int maxNumAlleles) { myIsHDF5 = true; myHDF5Writer = writer; myMaxNumAlleles = maxNumAlleles; myNumSites = numSites; // if (!myHDF5Writer.exists(Tassel5HDF5Constants.)) { // myHDF5Writer.createGroup(HapMapHDF5Constants.DEPTH); // } } private AlleleDepthBuilder(int numSites, int maxNumAlleles) { myIsHDF5 = false; myHDF5Writer = null; myMaxNumAlleles = maxNumAlleles; myNumSites = numSites; myDepths = new ArrayList<>(); } private AlleleDepthBuilder(int numTaxa, int numSites, int maxNumAlleles) { myIsHDF5 = false; myHDF5Writer = null; myMaxNumAlleles = maxNumAlleles; myNumSites = numSites; myNumTaxa = numTaxa; myDepths = new ArrayList<>(); for (int i = 0; i < myNumTaxa; i++) { myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles)); } } public static AlleleDepthBuilder getInstance(int numTaxa, int numSites, int maxNumAlleles) { return new AlleleDepthBuilder(numTaxa, numSites, maxNumAlleles); } public static AlleleDepthBuilder getNucleotideInstance(int numTaxa, int numSites) { return new AlleleDepthBuilder(numTaxa, numSites, NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES); } /** * AlleleDepthBuilder is created and depths are stored in a HDF5 file. setDepth methods are used to set the depths. * Finish the building with build() * @param writer * @param numSites * @return */ public static AlleleDepthBuilder getHDF5NucleotideInstance(IHDF5Writer writer, int numSites) { return new AlleleDepthBuilder(writer, numSites, NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES); } /** * AlleleDepth is returned for an immutable HDF5 file * @param reader * @return allele depths */ public static AlleleDepth getExistingHDF5Instance(IHDF5Reader reader) { //TODO is this the right name for this if(HDF5Utils.doesGenotypeDepthExist(reader)==false) return null; return new HDF5AlleleDepth(reader); } /** * Set allele value for taxon, site, and allele. Value will be translated * using AlleleDepthUtil. * * @param taxon taxon * @param site site * @param allele allele * @param depth value * * @return builder */ public AlleleDepthBuilder setDepth(int taxon, int site, byte allele, int depth) { if (myIsHDF5) { throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files."); } myDepths.get(taxon).set(site, allele, AlleleDepthUtil.depthIntToByte(depth)); return this; } /** * Set depth for the all sites and alleles for a taxon simultaneously. * Value will be translated using AlleleDepthUtil. First dimension of depths * is number of alleles (6 for Nucleotide) and second dimension is sites. * * @param taxon Index of taxon * @param depths array[sites][allele] of all values * * @return builder */ public AlleleDepthBuilder setDepth(int taxon, int[][] depths) { if (myIsHDF5) { throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files."); } int numAlleles = depths.length; if (numAlleles != myMaxNumAlleles) { throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of alleles: " + numAlleles + " should have: " + myMaxNumAlleles); } int numSites = depths[0].length; if (numSites != myNumSites) { throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of sites: " + numSites + " should have: " + myNumSites); } for (int a = 0; a < myMaxNumAlleles; a++) { for (int s = 0; s < myNumSites; s++) { setDepth(taxon, s, (byte) a, depths[s][a]); } } return this; } /** * Set depth for the all sites and alleles for a taxon simultaneously. * First dimension of depths * is number of alleles (6 for Nucleotide) and second dimension is sites. * * @param taxon Index of taxon * @param depths array[sites][allele] of all values * * @return builder */ public AlleleDepthBuilder setDepthRangeForTaxon(int taxon, int siteOffset, byte[][] depths) { if (myIsHDF5) { throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files."); } int numAlleles = depths.length; if (numAlleles != myMaxNumAlleles) { throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of alleles: " + numAlleles + " should have: " + myMaxNumAlleles); } for (int a = 0; a < myMaxNumAlleles; a++) { for (int s = 0; s < depths[0].length; s++) { setDepth(taxon, s+siteOffset, (byte) a, depths[a][s]); } } return this; } /** * Set allele value for taxon, site, and allele. Value should have already * been translated using AlleleDepthUtil. * * @param taxon taxon * @param site site * @param allele allele * @param depth value * * @return builder */ public AlleleDepthBuilder setDepth(int taxon, int site, byte allele, byte depth) { if (myIsHDF5) { throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files."); } myDepths.get(taxon).set(site, allele, depth); return this; } /** * Set allele for the all sites and alleles for a taxon simultaneously. * Values should have already been translated using AlleleDepthUtil. First * dimension of depths is number of alleles (6 for Nucleotide) and second * dimension is sites. * * @param taxon Index of taxon * @param depths array[allele][sites] of all values * * @return builder */ public AlleleDepthBuilder setDepth(int taxon, byte[][] depths) { if (myIsHDF5) { throw new IllegalStateException("AlleleDepthBuilder: setDepth: use addTaxon for HDF5 files."); } int numAlleles = depths.length; if (numAlleles != myMaxNumAlleles) { throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of alleles: " + numAlleles + " should have: " + myMaxNumAlleles); } int numSites = depths[0].length; if (numSites != myNumSites) { throw new IllegalArgumentException("AlleleDepthBuilder: setDepth: value number of sites: " + numSites + " should have: " + myNumSites); } for (int a = 0; a < myMaxNumAlleles; a++) { for (int s = 0; s < myNumSites; s++) { setDepth(taxon, s, (byte) a, depths[a][s]); } } return this; } /** * Add taxon and set values for all sites and alleles for that taxon. First * dimension of depths is number of alleles (6 for Nucleotide) and second * dimension is sites. * * @param taxon taxon * @param depths depth values * * @return builder */ public AlleleDepthBuilder addTaxon(Taxon taxon, byte[][] depths) { if (myIsHDF5) { if ((depths == null) || (depths.length != 6)) { throw new IllegalStateException("AlleleDepthBuilder: addTaxon: Set A, C, G, T, -, + at once"); } if (depths[0].length != myNumSites) { throw new IllegalStateException("AlleleDepthBuilder: addTaxon: Number of sites: " + depths[0].length + " should be: " + myNumSites); } synchronized (myHDF5Writer) { //TAS-167 Ed tried to fix this - Terry needs to check with his unit tests once they are written HDF5Utils.writeHDF5GenotypesDepth(myHDF5Writer,taxon.getName(),depths); } myNumTaxa++; } else { myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles)); setDepth(myNumTaxa, depths); myNumTaxa++; } return this; } /** * Add taxon and set values for all sites and alleles for that taxon. First * dimension of depths is number of alleles (6 for Nucleotide) and second * dimension is sites. * * @param taxon taxon * @param depths depth values * * @return builder */ public AlleleDepthBuilder addTaxon(Taxon taxon, int[][] depths) { if (myIsHDF5) { int numAlleles = depths.length; if ((depths == null) || (numAlleles != 6)) { throw new IllegalStateException("AlleleDepthBuilder: addTaxon: Set A, C, G, T, -, + at once"); } if (depths[0].length != myNumSites) { throw new IllegalStateException("AlleleDepthBuilder: addTaxon: Number of sites: " + depths[0].length + " should be: " + myNumSites); } byte[][] result = new byte[numAlleles][myNumSites]; for (int a = 0; a < numAlleles; a++) { for (int s = 0; s < myNumSites; s++) { result[a][s] = AlleleDepthUtil.depthIntToByte(depths[a][s]); } } return addTaxon(taxon, result); } else { myDepths.add(SuperByteMatrixBuilder.getInstance(myNumSites, myMaxNumAlleles)); setDepth(myNumTaxa, depths); myNumTaxa++; } return this; } public AlleleDepth build() { if (myIsHDF5) { IHDF5Reader reader = myHDF5Writer; myHDF5Writer = null; return new HDF5AlleleDepth(reader); } else { SuperByteMatrix[] temp = new SuperByteMatrix[myDepths.size()]; temp = myDepths.toArray(temp); myDepths = null; return new MemoryAlleleDepth(temp, myNumTaxa, myNumSites); } } }
package org.db.ddbserver; public class GDD { String[] publisher = {"publisher.id", "publisher.name", "publisher.nation"}; String[] book = {"book.id", "book.title", "book.authors", "book.publisher_id", "book.copies"}; String[] customer = {"customer.id", "customer.name", "customer.rank"}; String[] customer_rank = {"customer.id", "customer.rank"}; String[] customer_name = {"customer.id", "customer.name"}; String[] orders = {"orders.customer_id", "orders.book_id", "orders.quantity"}; String username = "root"; String password = ""; String[] host = {"this is not used", "jdbc:mysql://localhost:3306/ddb1?useUnicode=true&characterEncoding=utf8", "jdbc:mysql://localhost:3306/ddb2?useUnicode=true&characterEncoding=utf8", "jdbc:mysql://localhost:3306/ddb3?useUnicode=true&characterEncoding=utf8", "jdbc:mysql://localhost:3306/ddb4?useUnicode=true&characterEncoding=utf8" }; public String getKey(String s) { if(s.equals("publisher")) return "publisher.id"; if(s.equals("book")) return "book.id&book.publisher_id"; if(s.equals("customer")) return "customer.id"; if(s.equals("orders")) return "orders.customer_id&orders.book_id"; return null; } public int getSite(String table, String num) { if(table.equals("publisher")) { if(num.equals("1")) return 1; if(num.equals("2")) return 2; if(num.equals("3")) return 3; if(num.equals("4")) return 4; } if(table.equals("book")) { if(num.equals("1")) return 1; if(num.equals("2")) return 2; if(num.equals("3")) return 3; } if(table.equals("customer")) { if(num.equals("1")) return 1; if(num.equals("2")) return 2; } if(table.equals("orders")) { if(num.equals("1")) return 1; if(num.equals("2")) return 2; if(num.equals("3")) return 3; if(num.equals("4")) return 4; } return 0; } public String[] getAllColumn(String s) { // TODO Auto-generated method stub if(s.equals("publisher")) return publisher; if(s.equals("book")) return book; if(s.equals("customer")) return customer; if(s.equals("customer_name")) return customer_name; if(s.equals("customer_rank")) return customer_rank; if(s.equals("orders")) return orders; return null; } public String ordersCustomerId(int id, String f) { if(f.equals(">")) { if(id < 307000) { return "1&2&3&4"; } else { return "3&4"; } } else if(f.equals("=")) { if(id < 307000) { return "1&2"; } else { return "3&4"; } } else if(f.equals("<")) { if(id <= 307000) { return "1&2"; } else { return "1&2&3&4"; } } else if(f.equals("<=")) { if(id < 307000) { return "1&2"; } else { return "1&2&3&4"; } } else if(f.equals(">=")) { if(id < 307000) { return "1&2&3&4"; } else { return "3&4"; } } return ""; } public String ordersBookId(int id, String f) { if(f.equals(">")) { if(id < 215000) { return "1&2&3&4"; } else { return "2&4"; } } else if(f.equals("=")) { if(id < 215000) { return "1&3"; } else { return "2&4"; } } else if(f.equals("<")) { if(id <= 215000) { return "1&3"; } else { return "1&2&3&4"; } } else if(f.equals("<=")) { if(id < 215000) { return "1&3"; } else { return "1&2&3&4"; } } else if(f.equals(">=")) { if(id < 215000) { return "1&2&3&4"; } else { return "2&4"; } } return ""; } public String bookId(int id, String f) { if(f.equals(">")) { if(id < 205000) { return "1&2&3"; } else if(id < 210000){ return "2&3"; } else { return "3"; } } else if(f.equals("=")) { if(id < 205000) { return "1"; } else if(id < 210000){ return "2"; } else { return "3"; } } else if(f.equals("<")) { if(id <= 205000) { return "1"; } else if(id <= 210000){ return "1&2"; } else { return "1&2&3"; } } else if(f.equals(">=")) { if(id < 205000) { return "1&2&3"; } else if(id < 210000){ return "2&3"; } else { return "3"; } } else if(f.equals("<=")) { if(id < 205000) { return "1"; } else if(id < 210000){ return "1&2"; } else { return "1&2&3"; } } return ""; } public String publisherNation(String nation) { if(nation.equals("prc")) { return "1&3"; } else if(nation.equals("usa")) { return "2&4"; } else { return ""; } } public String publisherId(int id, String f) { if(f.equals(">")) { if(id < 104000) { return "1&2&3&4"; } else { return "3&4"; } } else if(f.equals("=")) { if(id < 104000) { return "1&2"; } else { return "3&4"; } } else if(f.equals("<")) { if(id <= 104000) { return "1&2"; } else { return "1&2&3&4"; } } else if(f.equals(">=")) { if(id < 104000) { return "1&2&3&4"; } else { return "1&2"; } } else if(f.equals("<=")) { if(id < 104000) { return "1&2"; } else { return "1&2&3&4"; } } return ""; } }
package com.auro.scholr.home.presentation.view.adapter; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.RecyclerView; import com.auro.scholr.R; import com.auro.scholr.core.application.AuroApp; import com.auro.scholr.core.common.CommonCallBackListner; import com.auro.scholr.core.common.Status; import com.auro.scholr.databinding.QuizDocUploadLayoutBinding; import com.auro.scholr.home.data.model.KYCDocumentDatamodel; import com.auro.scholr.util.AppUtil; import java.util.ArrayList; public class KYCuploadAdapter extends RecyclerView.Adapter<KYCuploadAdapter.ViewHolder> { ArrayList<KYCDocumentDatamodel> mValues; Context mContext; QuizDocUploadLayoutBinding binding; CommonCallBackListner commonCallBackListner; boolean progressStatus; public KYCuploadAdapter(Context context, ArrayList<KYCDocumentDatamodel> values, CommonCallBackListner commonCallBackListner) { this.commonCallBackListner = commonCallBackListner; mValues = values; mContext = context; } public void updateList(ArrayList<KYCDocumentDatamodel> values) { mValues = values; notifyDataSetChanged(); } public void updateProgressValue(boolean progressStatus) { this.progressStatus = progressStatus; } public class ViewHolder extends RecyclerView.ViewHolder { QuizDocUploadLayoutBinding binding; public ViewHolder(QuizDocUploadLayoutBinding binding) { super(binding.getRoot()); this.binding = binding; } public void setData(KYCDocumentDatamodel kycDocumentDatamodel, int position) { this.binding.tvIdHead.setText(kycDocumentDatamodel.getDocumentName()); binding.tvNoFileChoosen.setText(kycDocumentDatamodel.getDocumentFileName()); binding.chooseFile.setText(kycDocumentDatamodel.getButtonText()); if (!kycDocumentDatamodel.isModify() && kycDocumentDatamodel.isDocumentstatus()) { binding.progressBar.setVisibility(View.GONE); binding.chooseFile.setVisibility(View.GONE); binding.tvNoFileChoosen.setVisibility(View.GONE); binding.tvSucessfullyUploaded.setVisibility(View.VISIBLE); binding.chooseFile.setBackgroundColor(AuroApp.getAppContext().getResources().getColor(R.color.rich_electric_blue)); } else { if (progressStatus && kycDocumentDatamodel.isProgress()) { binding.progressBar.setVisibility(View.VISIBLE); } if (progressStatus && !kycDocumentDatamodel.isProgress()) { binding.chooseFile.setEnabled(false); binding.chooseFile.setBackgroundColor(AuroApp.getAppContext().getResources().getColor(R.color.grey_color)); } else { binding.chooseFile.setEnabled(true); binding.chooseFile.setBackgroundColor(AuroApp.getAppContext().getResources().getColor(R.color.blue_color)); } } binding.chooseFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (commonCallBackListner != null) { commonCallBackListner.commonEventListner(AppUtil.getCommonClickModel(position, Status.KYC_BUTTON_CLICK, kycDocumentDatamodel)); } } }); } } @Override public KYCuploadAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.quiz_doc_upload_layout, viewGroup, false); return new ViewHolder(binding); } @Override public void onBindViewHolder(ViewHolder Vholder, int position) { Vholder.setData(mValues.get(position), position); } @Override public int getItemCount() { return mValues.size(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sem_prototype; /** * * @author robotica */ public class Fantasma extends Inimigo { public Fantasma() { tipo = "Fantasma"; } @Override public void ataque() { System.out.println("Fantasma atacando.. BOOO!"); } }
package com.moh.departments.activiteis; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.google.android.material.navigation.NavigationView; import com.moh.departments.R; import com.moh.departments.adapters.ExpandableListAdapter; import com.moh.departments.constants.Controller; import com.moh.departments.dialog.DialogLoding; import com.moh.departments.dialog.DialogMsg; import com.moh.departments.fragment.DepartmentsFragment; import com.moh.departments.fragment.HomeFragment; import com.moh.departments.fragment.PatientFragment; import com.moh.departments.fragment.PieChartFragment; import com.moh.departments.models.MenuModel; import com.moh.departments.models.PrivMenu; import com.moh.departments.models.Screen; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { TextView txth_username, txtdept; ExpandableListAdapter expandableListAdapter; ExpandableListView expandableListView; List<MenuModel> headerList = new ArrayList<>(); HashMap<MenuModel, List<MenuModel>> childList = new HashMap<>(); AlertDialog alertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Controller.LOADER_DIALOG = new DialogLoding(this); Controller.Msg_DIALOG = new DialogMsg(this); expandableListView = findViewById(R.id.expandableListView); prepareMenuData(); populateExpandableList(); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); View headerView = navigationView.getHeaderView(0); txth_username = headerView.findViewById(R.id.txth_username); txtdept = headerView.findViewById(R.id.txtdept); txth_username.setText(Controller.pref.getString("USER_NAME", "")); txtdept.setText(Controller.pref.getString("DEPT_NAME_AR", "")); ImageView pernavimg = (ImageView) headerView.findViewById(R.id.pernavimg); Picasso.with(this) .load(Controller.PERSONAL_IMG + Controller.pref.getString("USER_ID", "")) .into(pernavimg); HomeFragment homeFragment = new HomeFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, homeFragment); HomeActivity homeActivity = new HomeActivity(); ft.commit(); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { finish(); } else super.onBackPressed(); } } public void close_app() { alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setMessage("هل تريد تسجيل الخروج ؟"); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "لا", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { alertDialog.dismiss(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "نعم", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(HomeActivity.this, LoginActivity.class); startActivity(intent); finish(); Controller.editor.putString("LOGIN_MODE", "0"); Controller.editor.commit(); } }); alertDialog.show(); } public void open_icd10() { startActivity(new Intent(this, icd10Activity.class)); } public void show_onboarding() { startActivity(new Intent(this, boardingActivity.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); MenuItem item = menu.findItem(R.id.action_dept); item.setVisible(false); super.onPrepareOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_dept) { DepartmentsFragment departmentsFragment = new DepartmentsFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); departmentsFragment.show(ft, "tag"); } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { //make this method blank return true; } private void prepareMenuData() { MenuModel menuModel; // menuModel = new MenuModel("الرئيسية", true, false, 0); //PrivMenu of Android Tutorial. No sub menus // headerList.add(menuModel); for (int i = 0; i < Controller.PrivMENUS.size(); i++) { String name = Controller.PrivMENUS.get(i).getName(); int menuid = Controller.PrivMENUS.get(i).getId(); menuModel = new MenuModel(name, true, true, menuid); //PrivMenu of Java Tutorials headerList.add(menuModel); if (!menuModel.hasChildren) { childList.put(menuModel, null); } List<MenuModel> childModelsList = new ArrayList<>(); for (int j = 0; j < Controller.PrivMENUS.get(i).getScreens().size(); j++) { String screen = Controller.PrivMENUS.get(i).getScreens().get(j).getName(); int screenid = Controller.PrivMENUS.get(i).getScreens().get(j).getId(); MenuModel childModel = new MenuModel(screen, false, false, screenid); childModelsList.add(childModel); } if (menuModel.hasChildren) { Log.d("API123", "here"); childList.put(menuModel, childModelsList); } } menuModel = new MenuModel("الاستعلام عن icd10", true, false, 1); //PrivMenu of Android Tutorial. No sub menus headerList.add(menuModel); menuModel = new MenuModel("حول التطبيق", true, false, 2); //PrivMenu of Android Tutorial. No sub menus headerList.add(menuModel); menuModel = new MenuModel("تسجيل الخروج", true, false, 3); //PrivMenu of Android Tutorial. No sub menus headerList.add(menuModel); } private void populateExpandableList() { expandableListAdapter = new ExpandableListAdapter(this, headerList, childList); expandableListView.setAdapter(expandableListAdapter); expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { if (headerList.get(groupPosition).isGroup) { if (!headerList.get(groupPosition).hasChildren) { FrameLayout fragment = findViewById(R.id.content_frame); int menuid = headerList.get(groupPosition).getMenuid(); Fragment myfragment = null; Fragment homefragment = new HomeFragment(); switch (menuid) { case 1: open_icd10(); break; case 2: show_onboarding(); break; case 3: close_app(); break; } if (myfragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, homefragment); ft.addToBackStack(null); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); onBackPressed(); } } return false; } }); expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (childList.get(headerList.get(groupPosition)) != null) { PrivMenu menu = Controller.PrivMENUS.get(groupPosition); Screen screen = menu.getScreens().get(childPosition); // Toast.makeText(HomeActivity.this, "screen id:"+screen.getId(), Toast.LENGTH_SHORT).show(); // Log.e( "onChildClick: ","screen id"+screen.getId() ); FrameLayout fragment = findViewById(R.id.content_frame); int screenid = screen.getId(); Fragment myfragment = null; switch (screenid) { case 537: ///spc_dept ///end spc dept myfragment = new PatientFragment(); break; case 765: myfragment = new HomeFragment(); break; case 770: myfragment = new PieChartFragment(); break; } if (myfragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, myfragment); ft.addToBackStack(null); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); onBackPressed(); } return false; } }); } public void setActionBarTitle(String title) { getSupportActionBar().setTitle(title); } @Override protected void onPause() { super.onPause(); } }
package com.Hellel.PSoloid.dao.factory.postgres; import com.Hellel.PSoloid.dao.factory.AccountDao; import com.Hellel.PSoloid.dao.factory.CustomerDao; import com.Hellel.PSoloid.dao.factory.DaoFactory; /** * Created by VSulevskiy on 14.09.2015. */ public class DbDaoFactory extends DaoFactory { @Override public CustomerDao getCustomerDao() { return new DbCustomerDao(); } @Override public AccountDao getAccountDao() { return new DbAccountDao(); } }
package calculate; import methods.*; public class Play { public static void main(String[] args) { test_poly_range1(); test_poly_range2(); test_poly_range3(); test_Hyperbolic_range1(); } final static double start_position_1 = 0.01; final static double start_position_2 = 1.5; final static int [] range_poly_1 = {0,1}; final static int [] range_poly_2 = {1,2}; final static int [] range_poly_3 = {3,4}; final static String input_polynomial = "2 * x ^ 3 - 11.7 * x ^ 2 + 17.7 * x - 5"; final static String input_polynomial_dirv = "6 * x ^ 2 - 23.4 * x + 17.7"; final static int [] range_hype = {120,130}; final static String input_Hyperbolic = "x + 10 - x * cosh ( 50 / x )"; final static String input3_Hyperbolic_dirv = "( 50 * sinh ( 50 / x ) / x ) - cosh ( 50 / x ) + 1"; static void test_poly_range1(){ System.out.println("======================= Test 1 ==========================="); BaseMethod test1_bisection = new Bisection(input_polynomial,input_polynomial_dirv, range_poly_1[0],range_poly_1[1]); System.out.println("Result : "+test1_bisection.getResult()+"\n--------------------------------------------------"); BaseMethod test1_FalsePosition = new FalsePosition(input_polynomial,input_polynomial_dirv, range_poly_1[0],range_poly_1[1]); System.out.println("Result : "+test1_FalsePosition.getResult()+"\n--------------------------------------------------"); BaseMethod test1_NewtonRaphson = new NewtonRaphson(input_polynomial,input_polynomial_dirv, range_poly_1[0]); System.out.println("Result : "+test1_NewtonRaphson.getResult()+"\n--------------------------------------------------"); BaseMethod test1_Secant = new Secant(input_polynomial,input_polynomial_dirv, range_poly_1[0],range_poly_1[1]); System.out.println("Result : "+test1_Secant.getResult()+"\n--------------------------------------------------"); BaseMethod test1_ModifiedSecant = new ModifiedSecant(input_polynomial,input_polynomial_dirv, start_position_1); System.out.println("Result : "+test1_ModifiedSecant.getResult()+"\n--------------------------------------------------"); } static void test_poly_range2(){ System.out.println("======================= Test 2 ==========================="); BaseMethod test1_bisection = new Bisection(input_polynomial,input_polynomial_dirv, range_poly_2[0],range_poly_2[1]); System.out.println("Result : "+test1_bisection.getResult()+"\n--------------------------------------------------"); BaseMethod test1_FalsePosition = new FalsePosition(input_polynomial,input_polynomial_dirv, range_poly_2[0],range_poly_2[1]); System.out.println("Result : "+test1_FalsePosition.getResult()+"\n--------------------------------------------------"); BaseMethod test1_NewtonRaphson = new NewtonRaphson(input_polynomial,input_polynomial_dirv, start_position_2); System.out.println("Result : "+test1_NewtonRaphson.getResult()+"\n--------------------------------------------------"); BaseMethod test1_Secant = new Secant(input_polynomial,input_polynomial_dirv, range_poly_2[0],range_poly_2[1]); System.out.println("Result : "+test1_Secant.getResult()+"\n--------------------------------------------------"); BaseMethod test1_ModifiedSecant = new ModifiedSecant(input_polynomial,input_polynomial_dirv, start_position_2); System.out.println("Result : "+test1_ModifiedSecant.getResult()+"\n--------------------------------------------------"); } static void test_poly_range3(){ System.out.println("======================= Test 3 ==========================="); BaseMethod test1_bisection = new Bisection(input_polynomial,input_polynomial_dirv, range_poly_3[0],range_poly_3[1]); System.out.println("Result : "+test1_bisection.getResult()+"\n--------------------------------------------------"); BaseMethod test1_FalsePosition = new FalsePosition(input_polynomial,input_polynomial_dirv, range_poly_3[0],range_poly_3[1]); System.out.println("Result : "+test1_FalsePosition.getResult()+"\n--------------------------------------------------"); BaseMethod test1_NewtonRaphson = new NewtonRaphson(input_polynomial,input_polynomial_dirv, range_poly_3[0]); System.out.println("Result : "+test1_NewtonRaphson.getResult()+"\n--------------------------------------------------"); BaseMethod test1_Secant = new Secant(input_polynomial,input_polynomial_dirv, range_poly_3[0],range_poly_3[1]); System.out.println("Result : "+test1_Secant.getResult()+"\n--------------------------------------------------"); BaseMethod test1_ModifiedSecant = new ModifiedSecant(input_polynomial,input_polynomial_dirv, range_poly_3[0]); System.out.println("Result : "+test1_ModifiedSecant.getResult()+"\n--------------------------------------------------"); } static void test_Hyperbolic_range1(){ System.out.println("======================= Test 4 ==========================="); BaseMethod test1_bisection = new Bisection(input_Hyperbolic,input3_Hyperbolic_dirv, range_hype[0],range_hype[1]); System.out.println("Result : "+test1_bisection.getResult()+"\n--------------------------------------------------"); BaseMethod test1_FalsePosition = new FalsePosition(input_Hyperbolic,input3_Hyperbolic_dirv, range_hype[0],range_hype[1]); System.out.println("Result : "+test1_FalsePosition.getResult()+"\n--------------------------------------------------"); BaseMethod test1_NewtonRaphson = new NewtonRaphson(input_Hyperbolic,input3_Hyperbolic_dirv, range_hype[0]); System.out.println("Result : "+test1_NewtonRaphson.getResult()+"\n--------------------------------------------------"); BaseMethod test1_Secant = new Secant(input_Hyperbolic,input3_Hyperbolic_dirv, range_hype[0],range_hype[1]); System.out.println("Result : "+test1_Secant.getResult()+"\n--------------------------------------------------"); BaseMethod test1_ModifiedSecant = new ModifiedSecant(input_Hyperbolic,input3_Hyperbolic_dirv, range_hype[0]); System.out.println("Result : "+test1_ModifiedSecant.getResult()+"\n--------------------------------------------------"); } static void test(String input,double value_x){ ShuntingYard s = new ShuntingYard(input,value_x); s.printMyConversion(); System.out.println( ); CalculateResult c = new CalculateResult(s.getFinalConversion()); System.out.println("Result : "+c.getResult()); System.out.println("\n-----------------------------------------------"); } }
package com.uog.miller.s1707031_ct6039.servlets.childclass; import com.uog.miller.s1707031_ct6039.beans.ClassBean; import com.uog.miller.s1707031_ct6039.beans.HomeworkBean; import com.uog.miller.s1707031_ct6039.beans.SubmissionBean; import com.uog.miller.s1707031_ct6039.oracle.ClassConnections; import com.uog.miller.s1707031_ct6039.oracle.HomeworkConnections; import java.io.IOException; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; @WebServlet(name = "DeleteClass") public class DeleteClass extends HttpServlet { static final Logger LOG = Logger.getLogger(DeleteClass.class); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { LOG.debug("Attempting GET class delete"); String classId = request.getParameter("classId"); if(classId != null) { ClassConnections connections = new ClassConnections(); //Remove class DB connections.deleteClass(classId); //Also remove classLinks, as children assigned to class are no longer needed connections.deleteClassLinks(classId); //Must delete HW information when class is deleted HomeworkConnections homeworkConnections = new HomeworkConnections(); List<HomeworkBean> allHomeworkForClass = homeworkConnections.getAllHomeworkForClass(classId); for (HomeworkBean homeworkForClass : allHomeworkForClass) { //Get submissions List<SubmissionBean> allSubmissionsForHomeworkTask = homeworkConnections.getAllSubmissionsForHomeworkTask(homeworkForClass.getEventId()); for (SubmissionBean submissionBean : allSubmissionsForHomeworkTask) { //Delete submission File if(submissionBean.getSubmissionId() != null) { homeworkConnections.deleteSubmissionFile(submissionBean.getSubmissionId()); } //Delete Submission homeworkConnections.deleteSubmission(submissionBean.getEventId(), submissionBean.getEmail()); } //Then delete Homework homeworkConnections.deleteHomework(homeworkForClass.getEventId()); } removeAlerts(request); //Repopulate all Classes request.getSession(true).removeAttribute("allClasses"); addSessionAttributesForClass(request); request.getSession(true).setAttribute("formSuccess", "ClassDeleted."); try { response.sendRedirect(request.getContextPath() + "/jsp/actions/class/viewclass.jsp"); } catch (IOException e) { LOG.error("Unable to redirect back to Class page after db update failure.",e); } } else { //Can't find event without ID LOG.error("Unable to find a class without an ID"); removeAlerts(request); request.getSession(true).setAttribute("formErrors", "Could not find Class to delete."); try { response.sendRedirect(request.getContextPath() + "/jsp/actions/class/editclass.jsp"); } catch (IOException e) { LOG.error("Unable to redirect back to Class edit page.",e); } } } private void removeAlerts(HttpServletRequest request) { request.getSession(true).removeAttribute("formErrors"); request.getSession(true).removeAttribute("formSuccess"); } private void addSessionAttributesForClass(HttpServletRequest request) { String email = (String) request.getSession(true).getAttribute("email"); if(email != null) { ClassConnections connections = new ClassConnections(); List<ClassBean> classFromTeacherEmail = connections.getClassFromTeacherEmail(email); request.getSession(true).setAttribute("allClasses", classFromTeacherEmail); } } }
/* * Copyright (c) 2017 SAbort * * 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.nodomain.sabdevs.expensesmonitor.activities.addcategory; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.view.View; import android.widget.ListView; import com.nodomain.sabdevs.expensesmonitor.R; import com.nodomain.sabdevs.expensesmonitor.activities.BaseSupportActivity; import com.nodomain.sabdevs.expensesmonitor.adapters.CategoriesEditListArrayAdapter; public class EditCategoriesActivity extends BaseSupportActivity { private CategoriesEditListArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_categories); setToolbar(); adapter = new CategoriesEditListArrayAdapter(this, getCategoriesList()); final ListView listview = (ListView) findViewById(R.id.listvieweditcategories); listview.setAdapter(adapter); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabAddCategory); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AddCategoryDialogFragment().show(getFragmentManager(), getResources().getString(R.string.add_new_category)); } }); } public void updateAdapter() { adapter.getData().clear(); adapter.getData().addAll(getCategoriesList()); adapter.notifyDataSetChanged(); } }
package com.oa.asset.controller; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.Vector; public class ProductController { public static void main(String[]args){ List<String> list = new ArrayList<String>(); list = new Vector<String>(); list = new Stack<String>(); list = new LinkedList<String>(); Set<String> set = new HashSet<String>(); } }
package com.proyecto.ui.utils; import java.util.Stack; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Session; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.event.EventQueue; import org.zkoss.zk.ui.event.EventQueues; /** * Session managed redirection class. Do not access the redirection manager object itself, use the static methods provided with this class. * * @version 1.0 */ public class RedirectionManager { /** * Session name used to store the redirection manager. Do not use it to access the redirection manager on the session, use static methods provided * in RedirectionManager. */ private static final String SESSION_NAME = "zk_redirection_manager"; /** * The history stack for visited pages. */ private final Stack<String> historyStack; /** * Do not allow the creation of a redirection manager instance. It may be only one per session and it is class managed. */ private RedirectionManager() { historyStack = new Stack<String>(); } /** * Obtains the redirection manager or creates it if it is not present in the current session. * * @return The ression redirection manager. */ private static final RedirectionManager getRedirectionManager() { final Session session = Sessions.getCurrent(); RedirectionManager redirectionManager = (RedirectionManager) session.getAttribute(SESSION_NAME); if (redirectionManager == null) { redirectionManager = new RedirectionManager(); session.setAttribute(SESSION_NAME, redirectionManager); } return redirectionManager; } /** * Returns the zul page removing the index.zul data that is automatically injected by the browser. * * @return The current page. */ private static final String getCurrentPage() { return Executions.getCurrent().getDesktop().getRequestPath().replace("index.zul", ""); } /** * Checks if the current page is the same as provided as parameter. * * @param page * The page provided. * @return True if the url is the same, false elsewhere. */ public static final boolean isCurrentPage(final String page) { return getCurrentPage().equals(page); } /** * Checks if the current page is part of the initial path, matching the current page. * * @param page * The page provided. * @return True if the url starts with the page provided, false elsewhere. */ public static final boolean isPartOfCurrentPage(final String page) { return getCurrentPage().startsWith(page); } /** * Redirects to the previous page or reloads the current if there is no previous page stored in the stack. */ public static final void goBack() { final RedirectionManager redirectionManager = getRedirectionManager(); String page = redirectionManager.getPrevious(); if (page == null) { page = getCurrentPage(); } Executions.sendRedirect(page); } /** * Make a history managed redirection. * * @param page * The page you want to access. */ public static final void goTo(final String page) { final RedirectionManager redirectionManager = getRedirectionManager(); redirectionManager.add(getCurrentPage()); Executions.sendRedirect(page); } /** * Ir a una pagina, pasando por un objeto por sesion con la intencion de ser usado en dicha pagina. * * @param object * El objeto que se pasa por sesion. * @param objectSessionAttr * El nombre de atributo de sesion usado para el objeto. * @param page * La pagina de destino. */ public static final void goTo(final Object object, final String objectSessionAttr, final String page) { SessionUtil.set(objectSessionAttr, object); goTo(page); } /** * Requires a include element to have the EventChangePageController applied. * * @param page * The page to render. */ public static final void ajaxGoTo(final String page) { final RedirectionManager redirectionManager = getRedirectionManager(); redirectionManager.add(getCurrentPage()); final EventQueue<ChangePageEvent> queue = EventQueues.lookup(EventQueues.DESKTOP); queue.publish(new ChangePageEvent(ChangePageEvent.EVENT_DEFAULT, null, page)); final EventQueue<ReloadScrollComponentEvent> queueScroll = EventQueues.lookup(EventQueues.DESKTOP); queueScroll.publish(new ReloadScrollComponentEvent(ReloadScrollComponentEvent.EVENT_DEFAULT, null, page)); } public static final void clearStack() { final RedirectionManager redirectionManager = getRedirectionManager(); redirectionManager.clear(); } /** * Private get previous page. * * @return The previous page or null if the stack is empty. */ private String getPrevious() { if (historyStack.isEmpty()) { return null; } return historyStack.pop(); } /** * Appends the page to the stack. * * @param page * The page to append. */ private void add(final String page) { historyStack.push(page); } /** * Clear the stack history. */ private void clear() { historyStack.clear(); } }
package com.bruce.composite.jdkdemo; import java.util.HashMap; import java.util.Map; public class Composite { public static void main(String[] args) { //todo more logics Map<Integer, String> hashMap=new HashMap<Integer, String>(); hashMap.put(0, "ÀÏ»¢"); Map<Integer, String> map=new HashMap<Integer, String>(); map.put(1,"ʨ×Ó"); map.put(2,"±ª×Ó"); hashMap.putAll(map); System.out.println(hashMap); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package serverPrgms; /** * * @author Shivam */ public interface TicTaeToeConstants { public static int PLAYER1 = 1; public static int PLAYER2 = 2; public static int PLAYER1_WON = 1; public static int PLAYER2_WON = 2; public static int DRAW = 3; public static int CONTINUE = 4; public static int RESTART = 5; public static int QUIT = 6; }
import org.junit.Assert; import org.junit.Test; import java.io.IOException; public class BruteCollinearPointsTest extends CollinearTest { @Test(expected = NullPointerException.class) public void constructorThrowsNPE() { new BruteCollinearPoints(null); } @Test(expected = NullPointerException.class) public void constructorThrowsNPEWhenPointIsNull() { new BruteCollinearPoints(new Point[]{null}); } @Test(expected = IllegalArgumentException.class) public void constructorThrowsIAEIfPointsAreRepeated() { new BruteCollinearPoints(new Point[]{point(1, 1), point(1, 1), point(1, 1), point(1, 1)}); } @Test public void testInput1() throws IOException { assert (new BruteCollinearPoints(readPoints("input1.txt")).segments().length == 0); } @Test public void testInput2() throws IOException { assert (new BruteCollinearPoints(readPoints("input2.txt")).segments().length == 0); } @Test public void testInput3() throws IOException { Assert.assertEquals(0, new BruteCollinearPoints(readPoints("input3.txt")).segments().length); } @Test public void testInput8() throws IOException { LineSegment[] segments = new BruteCollinearPoints(readPoints("input8.txt")).segments(); assert (segments.length == 2); } }
/** * */ package com.fixit.core.data.mongo; import java.util.Arrays; import org.bson.types.ObjectId; import com.fixit.core.data.DataMapping; /** * @author Kostyantin * @createdAt 2016/12/16 20:22:35 GMT+2 */ public class SearchTag implements MongoModelObject { private ObjectId _id; private String tag; private DataMapping[] mappings; public SearchTag() { } public SearchTag(String tag, DataMapping[] mappings) { this.tag = tag; this.mappings = mappings; } @Override public ObjectId get_id() { return _id; } @Override public void set_id(ObjectId _id) { this._id = _id; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public DataMapping[] getMappings() { return mappings; } public void setMappings(DataMapping[] mappings) { this.mappings = mappings; } @Override public String toString() { return "SearchTag [_id=" + _id + ", tag=" + tag + ", mappings=" + Arrays.toString(mappings) + "]"; } }
package ApiTest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.DynamicTest.stream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.jupiter.api.Test; public class DateTest { @Test void DateToString1(){ final Date d = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); System.out.println(sdf.format(d)); //2020 assertEquals(2020-1900, d.getYear(), "year"); } @Test void DateToString2(){ final Date d = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); System.out.println(sdf.format(d)); final Calendar cal=Calendar.getInstance(); cal.setTime(d); final var year=cal.get(Calendar.YEAR); assertEquals(2020, year ,"year"); } @Test void StringToDate() throws ParseException { final DateFormat df=new SimpleDateFormat("yyyy-MM-dd"); final String str="2012-03-03"; final Date date=df.parse(str); assertEquals(2012-1900, date.getYear(), "year"); } @Test void DateToMath(){ LocalDate myDate=LocalDate.parse("2013-04-04"); myDate=myDate.plusDays(10); myDate=myDate.plusMonths(2); assertEquals(6,myDate.getMonthValue(), "ee"); } }
/* * Fazer um algoritmo que leia os dois lados A e B de um triângulo retângulo e * calcula a hipotenusa do triângulo. Para esse caso, considere que hipotenusa = * √A²+B². Dica: nesse programa, você deve usar a função matemática Math.sqrt().  * Por exemplo, a raiz de 121 ficaria Math.sqrt(121) . */ package ap; import java.util.Scanner; public class Exercicio7 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Escreva lado A do triângulo: "); double A = console.nextDouble(); System.out.print("Escreva lado B do triângulo: "); double B = console.nextDouble(); double hipotenusa = Math.sqrt((A*A)+(B*B)); System.out.println("\nHipotenusa= "+ hipotenusa); } }
/* 打印如下图形 ----* ---* * --* * * -* * * * * * * * * i j k 0 4 1 j = 4-i; k = i+1; 1 3 2 2 2 3 3 1 4 4 0 5 * * * * * * * * * * */ class TestExer1 { public static void main(String[] args) { for(int i = 0;i < 5;i++){ //输出“-” for(int j = 0;j < 4-i;j++){ System.out.print("-"); } //输出“* ” for(int k = 0;k < i+1;k++){ System.out.print("* "); } System.out.println(); } } }
package parameters; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; //import java.util.Random; // //import com.google.common.base.Function; //import com.google.common.base.Predicate; //import com.google.common.base.Predicates; //import com.google.common.collect.Iterables; //import com.google.common.collect.Lists; // //import utils.PathComparator; public class Path { private LinkedList<NodePair> path; private int cost; public Path() { } public Path(LinkedList<NodePair> path, int cost) { this.path = path; this.cost = cost; } public LinkedList<NodePair> getPath() { return path; } public void setPath(LinkedList<NodePair> path) { this.path = path; } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } public List<Edge> getEdges() { List<Edge> edges = new ArrayList<Edge>(); Edge auxEdge; int pathSize = path.size(); for (int i = 1; i < pathSize; i++) { auxEdge = new Edge(path.get(i-1).getName(), path.get(i).getName()); edges.add(auxEdge); } return edges; } public boolean hasEdge(Edge e) { boolean hasLink = false; int pathSize = path.size(); String previousNode = path.get(0).getName(); for (int i = 1; i < pathSize; i++) { // System.out.println("COMPARING: (" + previousNode + "," + path.get(i).getName() + ") WITH (" + e.getSource() + "," + e.getDestination() + ")"); if (e.isEqual(new Edge(previousNode, path.get(i).getName()))) { // System.out.println("IS EQUAL!"); hasLink = true; break; } previousNode = path.get(i).getName(); } return hasLink; } @Override public String toString() { String pathString = "["; int pathSize = path.size(); int last = pathSize - 1; for (int i = 0; i < pathSize; i++) { pathString += path.get(i).getName(); if (i != last) { pathString += ", "; } } pathString += "]"; return pathString; } // public static List<Path> getPathsExamples() { // List<Path> paths = new ArrayList<Path>(); // // LinkedList<NodePair> auxNodePairList; // Path auxPath; // NodePair auxNodePair; // // // Path #1 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("2", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("3", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("4", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // // Path #2 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("2", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("3", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // // Path #3 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("2", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("3", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("4", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("5", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("6", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("7", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("8", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("9", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("10", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // // Path #4 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("2", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("3", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // // Path #5 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("2", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("3", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("4", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("5", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("6", 0); // auxNodePairList.add(auxNodePair); // // auxNodePair = new NodePair("7", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // // Path #6 // auxNodePairList = new LinkedList<NodePair>(); // // auxNodePair = new NodePair("1", 0); // auxNodePairList.add(auxNodePair); // // auxPath = new Path(auxNodePairList, 0); // paths.add(auxPath); // // return paths; // } // static Function<Path, Integer> numberOfHops = new Function<Path, Integer>() { // @Override // public Integer apply(Path p) { // return p.getPath().size(); // } // }; // // public static List<Path> getRCLPaths(List<Path> paths) { // double alpha = 0.3; // // List<Path> sortedPaths = new ArrayList<Path>(paths); // sortedPaths.sort(new PathComparator()); // // System.out.println("################## SORTED PATHS"); // for (Path p : sortedPaths) { // System.out.println(p.toString()); // } // // int qmin = sortedPaths.get(0).getPath().size(); // int qmax = sortedPaths.get(sortedPaths.size() - 1).getPath().size(); // // int costFunctionValue = (int) Math.ceil((double)qmin + alpha * ((double)qmax - (double)qmin)); // // Predicate<Path> rclPathsPredicate = Predicates.compose(Predicates.equalTo(costFunctionValue), numberOfHops); // // Iterable<Path> itRCLPaths = Iterables.filter(sortedPaths, rclPathsPredicate); // // List<Path> rclPaths = Lists.newArrayList(itRCLPaths); // // System.out.println("################## RCL PATHS"); // for (Path p : rclPaths) { // System.out.println(p.toString()); // } // // System.out.println(rclPaths.size()); // // return rclPaths; // } // public static int costFunctionValue = -1; // // static Function<Path, Boolean> numberOfHops = new Function<Path, Boolean>() { // @Override // public Boolean apply(Path p) { // return p.getPath().size() <= costFunctionValue; // } // }; // // public static List<Path> getRCLPaths(List<Path> paths) { // double alpha = 0.3; // // List<Path> sortedPaths = new ArrayList<Path>(paths); // sortedPaths.sort(new PathComparator()); // //// System.out.println("################## SORTED PATHS"); //// for (Path p : sortedPaths) { //// System.out.println(p.toString()); //// } // // int qmin = sortedPaths.get(0).getPath().size(); // int qmax = sortedPaths.get(sortedPaths.size() - 1).getPath().size(); // // costFunctionValue = (int) Math.ceil((double)qmin + alpha * ((double)qmax - (double)qmin)); // // Predicate<Path> rclPathsPredicate = Predicates.compose(Predicates.equalTo(true), numberOfHops); // // Iterable<Path> itRCLPaths = Iterables.filter(sortedPaths, rclPathsPredicate); // // List<Path> rclPaths = Lists.newArrayList(itRCLPaths); // // return rclPaths; // } // // public static Path getRandomPath(List<Path> paths) { // Random random = new Random(); // int randomPos; // // if (paths.size() != 1) { // randomPos = random.nextInt(paths.size() - 1); // } // else { // randomPos = 0; // } // // return paths.get(randomPos); // } // // public static void main(String[] args) { // List<Path> pathss = getPathsExamples(); // List<Path> rclPaths; // Path auxPath; // // while (pathss.size() != 0) { // rclPaths = getRCLPaths(pathss); // auxPath = getRandomPath(rclPaths); // pathss.remove(auxPath); // } // } }
package com.user.auth.server.dao; import com.user.auth.server.model.User; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserDao extends CrudRepository<User, Long> { User findByUsername(String username); }
package json; /** * Created by RENT on 2017-03-22. */ public class Person { String firstName; String lastName; int birthYear; String idNumber; Person(){ } 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 int getBirthYear() { return birthYear; } public void setBirthYear(int birthYear) { this.birthYear = birthYear; } public String getIdNumber() { return idNumber; } public void setIdNumber(String idNumber) { this.idNumber = idNumber; } }
package sb.hackathon.controller; import lombok.extern.slf4j.Slf4j; import net.glxn.qrgen.core.image.ImageType; import net.glxn.qrgen.javase.QRCode; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; /** * schaetzle * <p> * Created by patrick on 13.10.17. * © skix.net 2017 */ @Slf4j @RestController public class SessionController { @Value("${addon.base-url}") private String basePath; @GetMapping(value = "/session/{uuid}/qr", produces = MediaType.IMAGE_PNG_VALUE) public @ResponseBody byte[] getSessionQrCode(@PathVariable("uuid") String uuid) throws IOException { return QRCode.from(basePath + "/session/" + uuid).to(ImageType.PNG).withSize(500, 500).stream() .toByteArray(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lk.vcnet.storemodule.client.user_interfaces; import java.awt.Dimension; import lk.vcnet.storemodule.client.main.ClientMain; /** * * @author user */ public class ChangeInventory extends javax.swing.JInternalFrame { /** * Creates new form ChangeInventory */ public static ChangeInventory instance; public ChangeInventory() { initComponents(); setVisible(true); Dimension dm=this.getSize(); this.setLocation((ClientMain.getDisplaySize().width - dm.width)/2, (ClientMain.getDisplaySize().height - 80 - dm.height)/2); } public static synchronized ChangeInventory getInstance() { if(instance==null) instance=new ChangeInventory(); return instance; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); tInventID = new javax.swing.JTextField(); tQty = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); tProID = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); btUpdt = new javax.swing.JButton(); btDelt = new javax.swing.JButton(); btClear = new javax.swing.JButton(); btBack = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setTitle("SEARCH & CHANGE INVENTORY DETAILS"); jLabel1.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N jLabel1.setText("Inventory ID"); tInventID.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N tQty.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N jLabel2.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N jLabel2.setText("Qty"); tProID.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N jLabel3.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N jLabel3.setText("Product ID"); btUpdt.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N btUpdt.setText("UPDATE"); btDelt.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N btDelt.setText("DELETE"); btDelt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btDeltActionPerformed(evt); } }); btClear.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N btClear.setText("CLEAR"); btBack.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N btBack.setText("BACK"); btBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btBackActionPerformed(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "INVENTRY ID", "QTY", "PRODUCT ID" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(40, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(67, 67, 67) .addComponent(tInventID, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42) .addComponent(btUpdt, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(139, 139, 139) .addComponent(tQty, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42) .addComponent(btDelt, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addGap(83, 83, 83) .addComponent(tProID, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(42, 42, 42) .addComponent(btClear, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btBack, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(176, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 144, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(tInventID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btUpdt)) .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel2)) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(tQty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btDelt)) .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(tProID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btClear)) .addGap(6, 6, 6) .addComponent(btBack) .addGap(0, 7, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btDeltActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeltActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btDeltActionPerformed private void btBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBackActionPerformed }//GEN-LAST:event_btBackActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btBack; private javax.swing.JButton btClear; private javax.swing.JButton btDelt; private javax.swing.JButton btUpdt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField tInventID; private javax.swing.JTextField tProID; private javax.swing.JTextField tQty; // End of variables declaration//GEN-END:variables }
package panel; import javax.swing.*; import java.awt.*; /* * This disabled version of the upload Panel removes the Template Statements and Contact List from address book. * This also, as the name implies, disables all fields inside so they are non editable and display as such. * This is utilised anytime an upload needs to be shown such as in edit Panel and log Panel. */ public class UploadPanelDisabled extends UploadPanel { public UploadPanelDisabled() { super(new JPanel(new CardLayout())); leftPanel.remove(backResetPanel); rightPanel.remove(saveUploadPanel); sp.remove(templateStatement); contactsPanel.remove(searchField); contactsPanel.remove(authorsLabel); contactsListPanel.remove(contactsLabel); contactsListPanel.remove(notAddedContactList); contactsListPanel.remove(contactListScroll); SpringUtilities.makeCompactGrid(contactsListPanel, 2, 1, 0, 0, 5, 5); //Remove the first element as this is displays the info of the drag feature, this is not needed in this view DefaultListModel l = (DefaultListModel) attachedFileList.getModel(); l.remove(0); for (Component com : titlePanel.getComponents()) { com.setEnabled(false); } for (Component com : descPanel.getComponents()) { com.setEnabled(false); } descriptionTextArea.setEnabled(false); //is inside split pane so set false manually for (Component com : filePanel.getComponents()) { com.setEnabled(false); } attachedFileList.setEnabled(false); //is inside scroll pane sp manually set for (Component com : typeDatePanel.getComponents()) { com.setEnabled(false); } for (Component com : contactsPanel.getComponents()) { com.setEnabled(false); } for (Component com : contactsListPanel.getComponents()) { com.setEnabled(false); } addedContactsList.setEnabled(false); for (Component com : servicesPanel.getComponents()) { com.setEnabled(false); } } }
package com.example.sypark9646.item01; public abstract class ShapeFactory { abstract Shape createShape(String name); }
package algorithms.graph.process; import algorithms.graph.Graph; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * Created by Chen Li on 2018/5/6. */ @Getter @Setter @Slf4j public class DegreesOfSeparation { private SymbolGraph symbolGraph; private String sourceVertex; private BreadthFirstPaths paths = new BreadthFirstPaths(); public void report(String target) { if(!symbolGraph.contains(sourceVertex)){ log.info("source vertex not in database."); return; } if(!symbolGraph.contains(target)){ log.info("target vertex not in database."); return; } Graph graph = symbolGraph.getGraph(); paths.init(graph, symbolGraph.index(sourceVertex)); log.info("{}:", sourceVertex); for (Integer v : paths.pathTo(symbolGraph.index(target))) { log.info(" {}", symbolGraph.name(v)); } } }
package jgame; public class Endurance { private static int energy, speed; static { energy = 100; speed = 1; } public static int getEnergy() { return energy; } public static int getSpeed() { System.out.println(speed); return 32 % speed != 0 ? speed - 1 : speed; } public static void deductEnergy() { energy--; } public static void increaseSpeed() { if (speed < 10) speed++; } public static void normalizeSpeed() { if (speed > 1) speed--; } }
class Parent { public void m1()//consider as overriden // public static void m1()//hidding { System.out.println("overriden"); } } class Child extends Parent { public void m1()//consider as overriding // public static void m1()//method hidding { System.out.println("overriding"); } public static void main(String[]args) { Parent p = new Parent(); p.m1(); Child c = new Child(); c.m1(); Parent p1 = new Child(); p1.m1(); } }
package SinglePattern04.exercise.IoDH; import java.util.stream.Stream; /** * IoDH:Initialization Demand Holder结合了懒汉和饿汉模式的优点,克服了它们的缺点. * 使用内部类和类加载来使得jvm保证了实例化时的线程安全性. */ public class Client { public void f(){ System.out.println(IoDHLoadBalancer.getInstance()); } public static void main(String[] args) { Client client = new Client(); Stream.of("t1","t2","t3","t4","t5","t6") .forEach(name->new Thread(()->{ client.f(); System.out.println("当前线程:" +Thread.currentThread().getName()+ "创建实例对象"); },name).start() ); } }
package com.example.sys.entity; import lombok.Data; import java.util.Date; @Data public class User { /** * 用户id */ private Integer id; /** * 用户名称 */ private String username; /** * 用户密码 */ private String password; /** * 创建时间 */ private Date createTime; }
package com.employee.management.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.employee.management.model.Employee; import com.employee.management.repository.EmployeeRepository; // employee service class @Service public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; // fetching all employees public List<Employee> getAllEmployees() { List<Employee> emps = (List<Employee>) employeeRepository.findAll(); return emps; } // fetching employee by id public Employee getEmployee(int id) { return employeeRepository.findById(id).get(); } // inserting employee public void addEmployee(Employee e) { employeeRepository.save(e); } // updating employee by id public void updateEmployee(Employee emp, int id) { if (id == emp.getEmployeeID()) { employeeRepository.save(emp); } } // deleting all employees public void deleteAllEmployees() { employeeRepository.deleteAll(); } // deleting employee by id public void deleteEmployeeByID(int id) { employeeRepository.deleteById(id); } }
import java.util.*; public class cTable { private int[] tab; // class field representing int table private int size; // class field representing table size public cTable() { // TODO Auto-generated constructor stub System.out.println("To jest moja tablica"); } public cTable(int n) { this.size = n; if (size <= 100) { tab= new int[size]; } else { System.out.println("Za duży rozmiar tablicy"); System.exit(0); } } public void generate() // function generate random table { Random rand = new Random(); for(int i=0; i<size; i++) { tab[i] = rand.nextInt(100);//i;//rand.nextInt(100); } } public void manuallyGenerate() { Scanner scan = new Scanner(System.in); for(int i=0; i<size; i++) { tab[i] = scan.nextInt(); } //scan.close(); } public void display() // function display random table { for(int i: tab) { System.out.print(" " + i); } System.out.println(" "); } public int sum() // function calculate sum part of table { int tmp =0; for(int i: tab) { tmp +=i; } return tmp; } public int maxValue() // function calculate max value of table { int max = -10000; for(int i: tab) { if(i > max) { max =i; } } return max; } //FIXME: CAN BE MORE THAN 1 ELEMENT OF TABLE public int indexOfmaxValue() // function calculate max value of table { int max = -10000; int index = 0; for(int i = 0; i< size; i++) { if(tab[i] > max) { max =tab[i]; index = i; } } return index; } // function checks if table contains given number public boolean isInTable(int number, int range) { if (range > size) // check if range fits into the table { System.out.println("Podany zakres wykracza poza rozmiar tablicy"); return false; } for(int i = 0; i < range; i++) { if(tab[i] == number) { return true; } } return false; } // function check if table is multi-valued public boolean isMultiValued() { for (int i = 0; i < size; i++) { for(int j =0; j< size; j++) { if ( i!=j) { if (tab[i] == tab[j]) { return false; } } } } return true; } // function check if table is multi-valued, directly method public boolean isMultiValued2() { for (int i = size-1; i > 0 ; i--) { if( isInTable(tab[i], i) ) { return false; } } return true; } public boolean isMultiValued3() { Set<Integer> set = new HashSet<Integer>(); for(int i : tab) { if(!set.add(i)) { System.out.println("Powtarza sie : " + i ); return false; } } return true; } public void removeNumber(int number) { int howManyOccurence= 0; // calculate occurrence of the number in table for(int i = 0; i < size; i ++) { if(tab[i] == number) { howManyOccurence++ ; } } int[] tmpTab = new int[size - howManyOccurence]; // create temporary table smaller than original table int j = 0; for(int i = 0; i < size; i ++) // copy all elements into temp table except all occurrence of given number { if(tab[i] != number) { tmpTab[j] = tab[i]; j++; } } tab = tmpTab; // assignee temp table to default table size = size-howManyOccurence;// update table size } public void removeRepeating() { for(int i=0; i<size; i++) { for(int j=i+1; j<size; j++) { /* If any duplicate found */ if(tab[i] == tab[j]) { /* Delete the current duplicate element * create variable k and init it with value of j, then move all table elements into left */ for(int k=j; k<size-1; k++) { tab[k] = tab[k + 1]; } /* Decrement size after removing duplicate element */ size--; /* If shifting of elements occur then don't increment j */ j--; } } } //copy valid numbers to new tab, and switch tabs int tmpTab[]= Arrays.copyOf(tab, size); tab = tmpTab; } }
import java.io.*; /** * Created by vszm on 8/3/14. */ class GNYR09F { public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long[][] results = new long[101][91]; results[0][0] = 1; results[1][0] = 2; for (int i = 2; i <= 100; i++) results[i][0] = results[i-1][0] + results[i-2][0]; for (int i = 2; i <= 100 ; i++) { for (int j = 1; j <= 90 ; j++) { results[i][j] = results[i-1][j] + results[i-2][j]- results[i-2][j-1] + results[i-1][j-1] ; } } int caseCount = Integer.parseInt(br.readLine()); while (caseCount-- > 0){ String[] nums = br.readLine().split(" "); int n = Integer.parseInt(nums[1]), k = Integer.parseInt(nums[2]); bw.write(nums[0] + " " + Long.toString(results[n][k])); bw.newLine(); } /* bw.write("row means bitlength n, column means target k\n\n"); for (int i = 0; i <= 16; i++) bw.write("\t\t" +Integer.toString(i) ); bw.newLine(); for (int i = 0; i <= 16; i++) { bw.write(Integer.toString(i)+"\t\t"); for (int j = 0; j <= 16; j++) { bw.write(Integer.toString(results[i][j])+"\t\t"); } bw.newLine(); } bw.write(Integer.toString(calculateAdjBC(20,8))); */ bw.flush(); } private static int calculateAdjBC(int bitLength, int target) { int act, count = 0; for (act = 0; act < Math.pow(2, bitLength); ++act) { String binary = Integer.toBinaryString(act); int value = 0; for (int i = 1; i < binary.length(); ++i) if (binary.charAt(i) == '1' && binary.charAt(i - 1) == '1') value++; if (value == target) count++; } return count; } }
package pl.edu.agh.cyberwej.data.dao.implementations; import org.springframework.stereotype.Repository; import pl.edu.agh.cyberwej.data.dao.interfaces.PaymentItemDAO; import pl.edu.agh.cyberwej.data.objects.PaymentItem; @Repository public class PaymentItemDAOImpl extends DAOBase<PaymentItem> implements PaymentItemDAO { }
package main.java.com.javacore.io_nio.task3.utils; public final class Constants { public static final String DELIMITER = ","; }
package com.ytdsuda.management.mappers; import org.apache.ibatis.annotations.Select; public interface RecentSummaryMapper { }
package test; import java.io.File; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.io.FileHandler; import org.testng.annotations.Test; public class Example { public static WebDriver driver; @Test public void test() throws IOException { System.setProperty("webdriver.chrome.driver", "../TestingTypes/Drivers/chromedriver.exe"); driver=new ChromeDriver(); driver.navigate().to("http://www.google.com"); //Capture full screenshot /*File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(f, new File("..\\TestingTypes\\screenshots\\screenshot.png")); System.out.println("Screenshot Taken Successfully");*/ //Capture a Specific section Screenshot WebElement logo=driver.findElement(By.xpath("//*[@id=\"hplogo\"]")); File frc= logo.getScreenshotAs(OutputType.FILE); File trg=new File("..\\TestingTypes\\screenshots\\sectionscreenshot.png"); FileHandler.copy(frc, trg); System.out.println("Particular Section Screenshot Taken!!!!!"); } }
package com.petclinicspring.com.services; import com.petclinicspring.com.models.Vet; public interface VetService extends CrudService<Vet, Long>{ }
package com.example.priceapp.service; import com.example.priceapp.model.Price; import com.example.priceapp.repository.PriceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Service public class PriceService { @Autowired private PriceRepository priceRepository; public List<Price> getAllPrices() { return priceRepository.findAll().stream() .sorted(Comparator.comparing(Price::getPriority).reversed()).collect(Collectors.toList()); } public Price getPrice(Date date, Long productId, Long brandId) { return priceRepository.findByStartDateLessThanAndEndDateGreaterThanAndProductIdAndBrandId(date, date, productId, brandId). stream().sorted(Comparator.comparing(Price::getPriority).reversed()).findFirst().get(); } }
package cards; import java.util.Scanner; public class House { public void startGame() throws InterruptedException { // Double wager; Scanner kb = new Scanner(System.in); Player player = new Player(); player.setName(" "); Player dealer = new Player(); dealer.setName("Dealer"); Deck d = new Deck(); d.shuffleDeck(); boolean keepGoing = true; boolean playerKeepGoing = true; boolean dealerKeepGoing = true; System.out.println("******************************"); System.out.println("*\u2661\u2666*********************\u2667\u2660*"); System.out.println("******************************"); System.out.println("* Welcome to Star City Casino*"); System.out.println("******************************"); System.out.println("*Take a seat and enjoy a game*"); System.out.println("******************************"); System.out.println("******************************"); System.out.println("***Would you like to play: ***"); System.out.println("******************************"); System.out.println("********Black Jack?***********"); System.out.println("******************************"); System.out.println("******Press 'Y' or 'N'********"); System.out.println("******************************"); System.out.println("******************************"); System.out.println("******************************"); System.out.println("******************************"); System.out.println("*\u2664\u2663*********************\u2662\u2665*"); System.out.println("******************************"); String choice = kb.next(); if (choice.equalsIgnoreCase("y")) { System.out.println("Welcome. What is your name?"); String nm = kb.next(); player.setName(nm); System.out.println("Salutaions for the Semi-Circle."); System.out.println(" \u2662\u2663\u2661\u2660" + player.getName() + "\u2662\u2663\u2661\u2660"); Thread.sleep(1800); System.out.println("Name of the game is BlackJack."); Thread.sleep(1650); System.out.println("Dealer Hits on 16 and Stays on 17."); Thread.sleep(1650); System.out.println("Ready?"); Thread.sleep(1650); System.out.println("Here come the cards."); System.out.println("\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\"); Thread.sleep(3000); } else { System.out.println("Thanks for visiting Star City Casino."); System.exit(66); } d.deal(player); d.deal(dealer); d.deal(player); d.deal(dealer); showHand(player); System.out.println("Total " + player.getPlayerHand().getValueOfHand()); System.out.println("*****************************"); showHand(dealer); System.out.println("Total " + dealer.getPlayerHand().getValueOfHand()); System.out.println("*****************************"); if (player.getPlayerHand().getValueOfHand() == 21 && dealer.getPlayerHand().getValueOfHand() != 21) { System.out.println("BlackJack" + " " + player.getName() + " " + "Wins!"); keepGoing = false; } else if (player.getPlayerHand().getValueOfHand() != 21 && dealer.getPlayerHand().getValueOfHand() == 21) { System.out.println("BlackJack Dealer Wins!!"); keepGoing = false; } else if (player.getPlayerHand().getValueOfHand() == 21 && dealer.getPlayerHand().getValueOfHand() == 21) { System.out.println("Push"); keepGoing = false; } while (keepGoing) { while (playerKeepGoing) { System.out.println("Do you want to hit or stay"); String input = kb.next(); if (input.equalsIgnoreCase("hit")) { System.out.println("*****************************"); d.deal(player); showHand(player); System.out.println("Total " + player.getPlayerHand().getValueOfHand()); System.out.println("*****************************"); showHand(dealer); System.out.println("Total " + dealer.getPlayerHand().getValueOfHand()); if (player.getPlayerHand().getValueOfHand() <= 21) { continue; } else { System.out.println("You Busted! Dealer Wins."); playerKeepGoing = false; dealerKeepGoing = false; } } else { playerKeepGoing = false; } } while (dealerKeepGoing) { if (dealer.getPlayerHand().getValueOfHand() < 17) { d.deal(dealer); showHand(player); System.out.println("Total " + player.getPlayerHand().getValueOfHand()); System.out.println("*****************************"); showHand(dealer); System.out.println("Total " + dealer.getPlayerHand().getValueOfHand()); System.out.println("*****************************"); } else if (dealer.getPlayerHand().getValueOfHand() > 21) { System.out.println("Dealer BUST!"); System.exit(23); } else { checkForWinner(player, dealer); dealerKeepGoing = false; } } kb.close(); } } public static void checkForWinner(Player player, Player dealer) { if (player.getPlayerHand().getValueOfHand() > dealer.getPlayerHand().getValueOfHand()) { System.out.println(player.getName() + " " + "Wins!"); } else if (player.getPlayerHand().getValueOfHand() < dealer.getPlayerHand().getValueOfHand()) { System.out.println("Dealer Wins!"); } else { System.out.println("PUSH!!!"); } } public static void showHand(Player p) { for (Card c : p.getPlayerHand().getHand()) { System.out.println(p.getName() + " " + c.getRank() + " " + c.getSuit()); } } }
import java.io.*; import java.lang.*; import java.util.*; // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // #include<stdbool.h> /* # Author : @RAJ009F # Topic or Type : GFG/Array # Problem Statement : MaxDiff between two elements # Description : # Complexity : ======================= #sample output ---------------------- ======================= */ class MaxDiff { public static void findmaxDiff( int arr[], int n) { int min = arr[0]; int maxdiff = arr[1] -arr[0]; for(int i=1; i<n; i++) { if(arr[i]-min>maxdiff) maxdiff = arr[i] - min; if(min>arr[i]) min = arr[i]; } System.out.println("max diff"+maxdiff); } public static void main(String args[]) { int arr[] = {2, 3, 10, 6, 4, 8, 1}; findmaxDiff(arr, arr.length); } }
package com.coder.model; // Generated Jan 23, 2020 8:11:18 PM by Hibernate Tools 5.0.6.Final import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Orders generated by hbm2java */ @Entity @Table(name = "orders", catalog = "traveldb") public class Orders implements java.io.Serializable { private OrdersId id; private ItemJoinStore itemJoinStore; private OrderLine orderLine; private OrderType orderType; private double subTotal; private int qty; private double deliverlyCost; private double discountRate; public Orders() { } public Orders(OrdersId id, ItemJoinStore itemJoinStore, OrderLine orderLine, OrderType orderType, double subTotal, int qty, double deliverlyCost, double discountRate) { this.id = id; this.itemJoinStore = itemJoinStore; this.orderLine = orderLine; this.orderType = orderType; this.subTotal = subTotal; this.qty = qty; this.deliverlyCost = deliverlyCost; this.discountRate = discountRate; } @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "orderLineId", column = @Column(name = "order_line_id", nullable = false)), @AttributeOverride(name = "itemJoinStoreId", column = @Column(name = "item_join_store_id", nullable = false)), @AttributeOverride(name = "orderTypeId", column = @Column(name = "order_type_id", nullable = false)) }) public OrdersId getId() { return this.id; } public void setId(OrdersId id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "item_join_store_id", nullable = false, insertable = false, updatable = false) public ItemJoinStore getItemJoinStore() { return this.itemJoinStore; } public void setItemJoinStore(ItemJoinStore itemJoinStore) { this.itemJoinStore = itemJoinStore; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_line_id", nullable = false, insertable = false, updatable = false) public OrderLine getOrderLine() { return this.orderLine; } public void setOrderLine(OrderLine orderLine) { this.orderLine = orderLine; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_type_id", nullable = false, insertable = false, updatable = false) public OrderType getOrderType() { return this.orderType; } public void setOrderType(OrderType orderType) { this.orderType = orderType; } @Column(name = "sub_total", nullable = false, precision = 22, scale = 0) public double getSubTotal() { return this.subTotal; } public void setSubTotal(double subTotal) { this.subTotal = subTotal; } @Column(name = "qty", nullable = false) public int getQty() { return this.qty; } public void setQty(int qty) { this.qty = qty; } @Column(name = "deliverly_cost", nullable = false, precision = 22, scale = 0) public double getDeliverlyCost() { return this.deliverlyCost; } public void setDeliverlyCost(double deliverlyCost) { this.deliverlyCost = deliverlyCost; } @Column(name = "discount_rate", nullable = false, precision = 22, scale = 0) public double getDiscountRate() { return this.discountRate; } public void setDiscountRate(double discountRate) { this.discountRate = discountRate; } }
package com.egova.eagleyes.repository; import com.egova.baselibrary.model.BaseResponse; import com.egova.baselibrary.model.Lcee; import com.egova.baselibrary.model.NameTextValue; import com.egova.eagleyes.model.request.SearchCondition; import java.util.List; import androidx.lifecycle.LiveData; /** * 车辆统计 */ public interface VehicleStatisticRepository { //活跃区县 LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> queryPortraitByRegion(SearchCondition searchCondition); //活跃时间 LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> queryPortraitByTime(SearchCondition searchCondition); //活跃卡口 LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> queryPortraitByTollgate(SearchCondition searchCondition); }
/********************************************************************* Purpose/Description: The following solution has the linear complexity using BigInteger numbers in order to print very long numbers without causing an undesired overflow however a subLinear couldn't be found but using a fibbonnacci solution. Author’s Panther ID: 6050200 Certification: I hereby certify that this work is my own and none of it is the work of any other person. The complexity of the algorithm is defined by the size of the sample, meaning that it will have a linear complexity, Big O’h =(n). ********************************************************************/ package p3; import java.math.BigInteger; public class P3 { static BigInteger findLucas(int n) { int a = 2; int b = 1; int c; int i; if (n == 0) return BigInteger.valueOf(a); for (i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return BigInteger.valueOf(b); } public static void main(String[] args) { int n = 9; System.out.print(findLucas(n)+"\n"); } }
package br.com.estore.web.control; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import br.com.estore.web.dao.CustomerDAO; import br.com.estore.web.model.CustomerBean; @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { treatingRequest(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { treatingRequest(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void treatingRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String login, password; CustomerDAO dao = null; CustomerBean user = null; try { if (request.getParameter("txtLogin") != null && request.getParameter("txtPassword") != null) { login = request.getParameter("txtLogin"); password = request.getParameter("txtPassword"); dao = new CustomerDAO(); user = new CustomerBean(login, password); user = dao.get(user); String url = "home"; if (user == null) { request.setAttribute("error", "Credenciais Invalidas"); } else { HttpSession session = request.getSession(true); session.setAttribute("user", user); } RequestDispatcher dispatcher = request .getRequestDispatcher(url); dispatcher.forward(request, response); } else { request.setAttribute("error", "Favor preencher todos os campos."); } } catch (Exception e) { throw e; } } }
package egovframework.adm.com.cmp.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import egovframework.adm.com.cmp.service.SelectCompanyService; import egovframework.com.cmm.EgovMessageSource; @Controller public class SelectCompanyController { /** log */ protected static final Log log = LogFactory.getLog(SelectCompanyController.class); /** EgovMessageSource */ @Resource(name = "egovMessageSource") EgovMessageSource egovMessageSource; /** portalActionMainService */ @Resource(name = "selectCompanyService") SelectCompanyService selectCompanyService; }
/** * */ package ethan.v4.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @since 2013-10-27 * @author ethan * @version $Id$ * ^^固定线程池,缓存线程池,调度线程池 */ public class ThreadPoolTest { public static void main(String[] args) { //使用固定线程数 ExecutorService threadPool = Executors.newFixedThreadPool(3); //使用缓存线程池,线程数不固定,一个任务时使用一个线程,10个任务时使用10个线程 // ExecutorService threadPool = Executors.newCachedThreadPool(); // ExecutorService threadPool = Executors.newSingleThreadExecutor(); for (int i = 1; i <= 10; i++) { final int task = i; threadPool.execute(new Runnable() { @Override public void run() { for (int j = 1; j <= 10; j++) { try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is looping " + j + " for task " + task); } } }); } ScheduledExecutorService schedulePool = Executors.newScheduledThreadPool(3); schedulePool.scheduleAtFixedRate(new Runnable() { @Override public void run() { String name = Thread.currentThread().getName(); System.out.println(name +" bombing!!!"); } }, 5, 2, TimeUnit.SECONDS); // threadPool.shutdown(); // threadPool.shutdownNow(); } }
import java.util.Scanner; public class Middle { public static void main(String[] args) { Scanner in=new Scanner(System.in); int n1,n2,n3; System.out.println("Enter 3 distinct number"); n1=in.nextInt(); n2=in.nextInt(); n3=in.nextInt(); if(n1==n2||n2==n3||n3==n2) System.out.println("Duplicate values found"); else { if(n1<n2 && n1>n3||n1>n2 && n1<n3) System.out.println(n1+" is middle value"); else if(n2<n3 && n2>n1||n2>n3 && n2<n1) System.out.println(n2+" is middle value"); else System.out.println(n3+" is middle value"); } } }