text
stringlengths
10
2.72M
package jp.co.entity_generator.vo; /** * エンティティ情報クラス */ public class EntityInfoVo { /** カラム論理名 */ String psyCalName = ""; /** カラム物理名 */ String lgcCalName = ""; /** 型 */ String type = ""; /** サイズ */ String size = ""; /** 必須 */ boolean requiredFlg = false; /** 初期値 */ String deaule = ""; /** PK */ boolean pkFlg = false; /** * カラム論理名を取得します。 * @return カラム論理名 */ public String getPsyCalName() { return psyCalName; } /** * カラム論理名を設定します。 * @param psyCalName カラム論理名 */ public void setPsyCalName(String psyCalName) { this.psyCalName = psyCalName; } /** * カラム物理名を取得します。 * @return カラム物理名 */ public String getLgcCalName() { return lgcCalName; } /** * カラム物理名を設定します。 * @param lgcCalName カラム物理名 */ public void setLgcCalName(String lgcCalName) { this.lgcCalName = lgcCalName; } /** * 型を取得します。 * @return 型 */ public String getType() { return type; } /** * 型を設定します。 * @param type 型 */ public void setType(String type) { this.type = type; } /** * サイズを取得します。 * @return サイズ */ public String getSize() { return size; } /** * サイズを設定します。 * @param size サイズ */ public void setSize(String size) { this.size = size; } /** * 必須を取得します。 * @return 必須 */ public boolean isRequiredFlg() { return requiredFlg; } /** * 必須を設定します。 * @param requiredFlg 必須 */ public void setRequiredFlg(boolean requiredFlg) { this.requiredFlg = requiredFlg; } /** * 初期値を取得します。 * @return 初期値 */ public String getDeaule() { return deaule; } /** * 初期値を設定します。 * @param deaule 初期値 */ public void setDeaule(String deaule) { this.deaule = deaule; } /** * PKを取得します。 * @return PK */ public boolean isPkFlg() { return pkFlg; } /** * PKを設定します。 * @param pkFlg PK */ public void setPkFlg(boolean pkFlg) { this.pkFlg = pkFlg; } }
package ChatServer; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; public class ClientHandler { // содержит подключение клиента, входящий и выходящий потоки private static final String AUTH_CMD_PREFIX = "/auth"; private static final String OK_CMD_PREFIX = "/enterOk"; private static final String ERR_CMD_PREFIX = "/enterErr"; private static final String PRIVATE_MSG_PREFIX = "/w"; private static final String END_CMD = "/end"; private static final String CLIENT_MSG_PREFIX = "/clientMsg"; private static final String SERVER_MSG_PREFIX = "/serverMsg"; private final MyServer myServer; private final Socket clientSocket; private DataInputStream in; private DataOutputStream out; private String username; public ClientHandler(MyServer myServer, Socket clientSocket) { this.myServer = myServer; this.clientSocket = clientSocket; } public String getUsername() { return username; } public void handle() throws IOException { in = new DataInputStream(clientSocket.getInputStream()); out = new DataOutputStream(clientSocket.getOutputStream()); new Thread(() -> { try { authentification(); readMessage(); } catch (IOException e) { e.printStackTrace(); System.out.println(e.getMessage()); } // reading of messages and waiting }).start(); } private void readMessage() throws IOException { while(true) { String message = in.readUTF(); System.out.println("message | " + username + " : " + message); if(message.startsWith(END_CMD)) { return; } else if (message.startsWith(PRIVATE_MSG_PREFIX)) { //TODO } else { myServer.broadcastMessage(message,this,false); } } } private void authentification() throws IOException { String message = in.readUTF(); while (true) { if (message.startsWith(AUTH_CMD_PREFIX)) { String[] parts = message.split("\\s+", 3); String login = parts[1]; String password = parts[2]; AuthService authService = myServer.getAuthService(); username = authService.GetUserNameByLoginAndPassword(login, password); if (username != null) { if (myServer.isUserBusy(username)) { // проверить свободен ли никнейм out.writeUTF(String.format("%s %s", ERR_CMD_PREFIX, "login is already in use !")); } out.writeUTF(String.format("%s %s", OK_CMD_PREFIX, username)); // send nickname to client // inform all the users about newcomer connection myServer.broadcastMessage(String.format(">>> &s connected to chat", username), this, true); // последнее это флаг серверного сообщениф myServer.subscribe(this); // зарегистрировали клиента break; } else { out.writeUTF(String.format("%s %s", ERR_CMD_PREFIX, "login and password do not match!")); } } else { out.writeUTF(String.format("%s %s", ERR_CMD_PREFIX, "Error of authorization !")); } } } public void sendMessage (String sender, String message) throws IOException { if (sender == null) { out.writeUTF(String.format("%s %s", SERVER_MSG_PREFIX, message)); } else { out.writeUTF(String.format("%s %s %s", CLIENT_MSG_PREFIX, sender, message)); } } }
package com.pybeta.daymatter.widget; import com.pybeta.daymatter.DayMatter; import com.pybeta.daymatter.R; import com.pybeta.daymatter.WidgetInfo; import com.pybeta.daymatter.core.DataManager; import com.pybeta.daymatter.db.DatabaseManager; import com.pybeta.daymatter.ui.LockBaseActivity; import com.pybeta.daymatter.ui.MatterListAdapter; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; public class WidgetConfigureHuge extends LockBaseActivity implements OnItemClickListener{ private ListView list; private MatterListAdapter adapter; private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(RESULT_CANCELED); setContentView(R.layout.activity_appwidget_configure); list = (ListView) findViewById(R.id.view_list); adapter = new MatterListAdapter(this); adapter.setItems(DatabaseManager.getInstance(this).queryAll(0).toArray()); list.setAdapter(adapter); list.setOnItemClickListener(this); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { finish(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Context context = WidgetConfigureHuge.this; DataManager dataMgr = DataManager.getInstance(context); DayMatter dayMatter = adapter.getItem(position); WidgetInfo info = dataMgr.getWidgetInfoByWidgetId(mAppWidgetId); if (info == null) { WidgetInfo widgetInfo = new WidgetInfo(); widgetInfo.dayMatterId = dayMatter.getUid(); widgetInfo.type = WidgetInfo.WIDGET_TYPE_HUGE; widgetInfo.widgetId = mAppWidgetId; dataMgr.addWidgetInfo(widgetInfo); } else { info.dayMatterId = dayMatter.getUid(); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); WidgetProviderHuge.updateAppWidget(context, appWidgetManager, mAppWidgetId, dayMatter.getUid()); Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); setResult(RESULT_OK, resultValue); finish(); } }
package com.tencent.mm.plugin.wenote.model.nativenote.spans; import com.tencent.mm.plugin.wenote.model.nativenote.manager.e; public final class n extends e { final boolean qsT; public final boolean qsU; public n(int i, int i2, boolean z, boolean z2) { super(i, i2); this.qsT = z; this.qsU = z2; } public final boolean a(e eVar) { if (eVar == null) { return false; } if (eVar.isEmpty()) { boolean z; if (eVar.Tw < this.Tw || eVar.tK >= this.tK) { z = false; } else { z = true; } boolean z2; if (eVar.Tw < this.Tw || eVar.tK > this.tK) { z2 = false; } else { z2 = true; } if (z || (z2 && this.qsU)) { return true; } return false; } else if (Math.max(this.Tw, eVar.Tw) < Math.min(this.tK, eVar.tK)) { return true; } else { return false; } } public final int caK() { return Math.abs(this.tK - this.Tw); } }
package org.lenskit.mooc.svd; import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.longs.LongSet; import org.apache.commons.math3.linear.RealVector; import org.codehaus.groovy.runtime.powerassert.SourceText; import org.grouplens.lenskit.util.statistics.MeanAccumulator; import org.lenskit.LenskitRecommender; import org.lenskit.api.Recommender; import org.lenskit.eval.traintest.AlgorithmInstance; import org.lenskit.eval.traintest.DataSet; import org.lenskit.eval.traintest.TestUser; import org.lenskit.eval.traintest.metrics.MetricColumn; import org.lenskit.eval.traintest.metrics.MetricResult; import org.lenskit.eval.traintest.metrics.TypedMetricResult; import org.lenskit.eval.traintest.recommend.ListOnlyTopNMetric; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.inject.Inject; import java.io.IOException; import java.util.HashMap; import java.io.FileWriter; import java.util.Map; import java.util.Scanner; public class ListPopularityMetric extends ListOnlyTopNMetric<ListPopularityMetric.Context> { // private HashMap<Double, SVDModel> modelMap; private final String freqFileName = "something.csv"; private static final String FILE_HEADER = "MovieId,Popularity,PopularityWeight,RecFrequency"; private static final String NEW_LINE_SEPARATOR = "\n"; private static final String COMMA_DELIMITER = ","; // private SVDModel model = null; @Inject public ListPopularityMetric() { super(ListPopularityMetric.UserResult.class, ListPopularityMetric.AggregateResult.class); } @Nullable @Override public Context createContext(AlgorithmInstance algorithm, DataSet dataSet, Recommender recommender) { return new Context(dataSet.getAllItems(), (LenskitRecommender) recommender); } @Nonnull @Override synchronized public MetricResult getAggregateMeasurements(ListPopularityMetric.Context context) { return new ListPopularityMetric.AggregateResult(context); } @Nonnull @Override public MetricResult measureUser(TestUser user, int targetLength, LongList recommendations, Context context) { SVDModel model = context.recommender.get(SVDModel.class); Double listPopularity = 0.0; for(Long item : recommendations){ listPopularity += Math.pow(model.getItemPopularity(item), 2); } ListPopularityMetric.UserResult result = new ListPopularityMetric.UserResult(listPopularity); context.addUser(result); return result; } public static class UserResult extends TypedMetricResult { @MetricColumn("ListPopularity") public final Double listPopularity; public UserResult(Double val) { listPopularity = val; } public Double getIlsValue() { return listPopularity; } } public static class AggregateResult extends TypedMetricResult { @MetricColumn("ListPopularity") public final Double listPopularity; public AggregateResult(ListPopularityMetric.Context accum) { this.listPopularity = accum.allMean.getMean(); } } public static class Context { private final LongSet universe; private final MeanAccumulator allMean = new MeanAccumulator(); private final LenskitRecommender recommender; Context(LongSet universe, LenskitRecommender recommender) { this.universe = universe; this.recommender = recommender; } void addUser(ListPopularityMetric.UserResult ur) { allMean.add(ur.getIlsValue()); } } }
package com.example.elvisapp; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class VollyActivity extends AppCompatActivity { EditText cajaId, cajaNombre, cajaDireccion; Button botonGuardar, botonBuscar; TextView datos; RecyclerView recyclerViewAlumno; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_volly); } private void cargarDatos(){ cajaId = findViewById(R.id.txtIdAlumnoVolly); cajaNombre = findViewById(R.id.txtNombreAlumnoVolly); cajaDireccion = findViewById(R.id.txtDireccionAlumnoVolly); botonGuardar = findViewById(R.id.btnInsertarVolly); botonBuscar = findViewById(R.id.btnBuscarVolly); datos = findViewById(R.id.lblDAtosAlumnoVolly); } }
package pl.ark.chr.buginator.ext.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.ark.chr.buginator.domain.core.Application; import pl.ark.chr.buginator.domain.auth.Company; import pl.ark.chr.buginator.ext.service.ApplicationResolver; import pl.ark.chr.buginator.repository.core.ApplicationRepository; import pl.ark.chr.buginator.repository.auth.CompanyRepository; import pl.ark.chr.buginator.util.ValidationUtil; import java.util.Optional; /** * Created by Arek on 2017-04-03. */ @Service @Transactional public class ApplicationResolverImpl implements ApplicationResolver { private static final Logger logger = LoggerFactory.getLogger(ApplicationResolverImpl.class); @Autowired private CompanyRepository companyRepository; @Autowired private ApplicationRepository applicationRepository; @Override public Application resolveApplication(String uniqueKey, String token, String applicationName) { Company company = getCompany(uniqueKey, token); return getApplication(company, applicationName); } private Company getCompany(String uniqueKey, String token) { validateEmptyString(uniqueKey, "uniqueKey"); validateEmptyString(token, "token"); Optional<Company> company = companyRepository.findByTokenAndUniqueKey(token, uniqueKey); if (!company.isPresent()) { logger.error("No company found for unique key: " + uniqueKey + " and token: " + token); throw new IllegalArgumentException("Company not found"); } return company.get(); } private Application getApplication(Company company, String applicationName) { validateEmptyString(applicationName, "applicationName"); Optional<Application> application = applicationRepository.findByNameAndCompany(applicationName, company); if (!application.isPresent()) { logger.error("No application found for name: " + applicationName + " and company: " + company.getId()); throw new IllegalArgumentException("Application not found"); } return application.get(); } private void validateEmptyString(String predicate, String key) { if (ValidationUtil.isBlank(predicate)) { logger.error(key + " is empty"); throw new IllegalArgumentException(key + " is empty"); } } }
import java.util.*; public class State_Of_Wakanda { public static void main(String args[]){ Scanner scn=new Scanner(System.in); int nr=scn.nextInt(); int nc=scn.nextInt(); int mat[][]=new int[nr][nc]; for(int i=0;i<nr;i++){ for(int j=0;j<nc;j++){ mat[i][j]=scn.nextInt(); } } System.out.println("Answer is from here"); for(int j=0;j<nc;j++){ if(j%2==0){ for(int i=0;i<=nr-1;i++){ System.out.println(mat[i][j]); } } else{ for(int i=nr-1;i>=0;i--){ System.out.println(mat[i][j]); } } } scn.close(); } }
package com.example.lo52_project; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.DisplayMetrics; /** * * Class of the background grid * This class is important because it gives the indexes values of pieces. * Cannot dissociated to SimpleSurfaceView that implement it * @author Lois Aubree & Lucie Boutou * */ public class MapDrawable { public final static int NB_DEFAULT_ROWS = 8; public final static int NB_DEFAULT_COLS = 5; private int mRows = 8; private int mCols = 5; public final static int _X = 200; public final static int _Y = 200; private float centerX = 0; private float centerY = 0; public Paint mPaint = new Paint(); private Rect[][] mTabCase = new Rect[NB_DEFAULT_ROWS][NB_DEFAULT_COLS]; /** * @constructor * @param Context of the application */ public MapDrawable(Context context) { /** * get Screen size */ DisplayMetrics disp = context.getResources().getDisplayMetrics(); centerX = disp.widthPixels/2; centerY = disp.heightPixels/2; mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); float startX = centerX-(NB_DEFAULT_ROWS*Piece.PIECE_WIDTH)/2; float startY = centerY-(NB_DEFAULT_COLS*Piece.PIECE_HEIGHT)/2; for (int i = 0 ; i < NB_DEFAULT_ROWS ; i++ ) for(int j = 0; j < NB_DEFAULT_COLS ; j++) { mTabCase[i][j] = new Rect((int)startX+i*Piece.PIECE_WIDTH,(int)startY+j*Piece.PIECE_HEIGHT, (int)startX+(i+1)*Piece.PIECE_WIDTH,(int)startY+(j+1)*Piece.PIECE_HEIGHT); } } public Rect getCase(int i,int j){return mTabCase[i][j];} /** * Drawing function of the grid * @param canvas */ public void draw(Canvas canvas) { for (int i = 0 ; i < mRows ; i++ ) for(int j = 0; j < mCols ; j++) { canvas.drawRect(mTabCase[i][j], mPaint); //canvas.drawCircle(centerX, centerY, 3, mPaint); } } public Rect getBoundCase(int i, int j) { return mTabCase[i][j]; } /** * Resize the grid to allow adding of more pieces to the world * @param new width value * @param new height value */ public void resize(int x , int y) { mRows = x; mCols = y; mTabCase = new Rect[mRows][mCols]; float startX = centerX-(x*Piece.PIECE_WIDTH)/2; float startY = centerY-(y*Piece.PIECE_HEIGHT)/2; for (int i = 0 ; i < mRows ; i++ ) for(int j = 0; j < mCols ; j++) { mTabCase[i][j] = new Rect((int)startX+i*Piece.PIECE_WIDTH,(int)startY+j*Piece.PIECE_HEIGHT, (int)startX+(i+1)*Piece.PIECE_WIDTH,(int)startY+(j+1)*Piece.PIECE_HEIGHT); } } }
package de.codingmechanic.business; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.swing.DefaultListModel; import org.apache.struts2.ServletActionContext; import org.apache.tiles.preparer.PreparerException; import org.apache.tiles.preparer.ViewPreparer; import org.apache.tiles.context.TilesRequestContext; import org.apache.tiles.AttributeContext; import org.apache.tiles.Attribute; import org.apache.tiles.ListAttribute; import com.opensymphony.xwork2.ActionContext; /** * Tiles Preparer-Klasse zur Zusammenstellung des tagTargetBody.jsp-Inhalts in Abhaengigkeit vom Request-Parameter * @author Henning Richter */ public class TagTargetViewPreparer implements ViewPreparer { public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext) throws PreparerException { ArrayList<String> content = new ArrayList<String>(); HttpServletRequest request = ServletActionContext.getRequest(); String currentLocale = ActionContext.getContext().getLocale().toString(); //bereinige die Lokale von den Laender-Postfixes int delimiterPos = currentLocale.indexOf("_"); if(delimiterPos>0) currentLocale= currentLocale.substring(0, delimiterPos); String queryVal = ""; //hole Wert des tag-Parameters vom Html-Request String directQueryVal = request.getParameterValues("tag")[0]; String[] whitelist = {"jsp", "java", "struts", "css", "ux", "webcard", "page-speed", "responsive", "seo", "photoShop", "illustrator", "tdd", "ria", "effects", "animations", "softwareDev", "webEng", "design", "ci", "cross-browser", "social", "oop", "i18n", "quality", "ajax", "jquery", "svg", "tag-cloud"}; if(inArray(whitelist,directQueryVal)) queryVal = directQueryVal; TagCollectionLoader tagCollectionLoader = new TagCollectionLoader(); //referenziere die tag-Zuordnungsdatei durch Zugriff ueber den class-Code (unabhaengig vom Pfad, in dem die Datei liegt) Map<String,ArrayList<String>> tagMap = tagCollectionLoader.loadAllObjects(new File(TagTargetViewPreparer.class.getClassLoader().getResource("tags.xml").getFile())); Properties prop = new Properties(); try { //lade die properties-Datei prop.load(TagTargetViewPreparer.class.getClassLoader().getResourceAsStream("content_"+currentLocale+".properties")); } catch (IOException ex) { ex.printStackTrace(); } //hole Content aus properties-Dateien fuer Ueberschrift und Beschreibungstext als Einleitung fuer TagTarget-Seite String tagTargetHeader = prop.getProperty("tagTarget.caption.header."+queryVal); String caption = prop.getProperty("tagTarget.caption.body."+queryVal); //stelle die Attribute zusammen, die im body der Tag-Ergebnisseite angezeigt werden sollen ListAttribute tiles = new ListAttribute(); tiles.setRenderer("template"); try { content = tagMap.get(queryVal); for(String fragment : content) tiles.add(new Attribute(fragment)); } catch (Exception e) { e.printStackTrace(); } //schreibe die Attribute in den Kontext, um diese in der jsp / tile verfuegbar zu machen attributeContext.putAttribute("tagTargetHeader", new Attribute(tagTargetHeader)); attributeContext.putAttribute("tagQuery", new Attribute(queryVal)); attributeContext.putAttribute("caption", new Attribute(caption)); attributeContext.putAttribute("bodies", tiles, true); } public static boolean inArray(String[] haystack, String needle) { for(int i=0;i<haystack.length;i++) { if(haystack[i].toString().equals(needle)) { return true; } } return false; } } //PRIO-c: in tuckey spezifische Seitennamen fuer Tag-Targets definieren
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.canvas.dom.client; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import org.gwtproject.core.client.JavaScriptObject; /** * HTML 5 Canvas text metrics. * * @see <a href="http://www.w3.org/TR/2dcontext/#textmetrics">HTML Canvas 2D TextMetrics</a> */ @JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL) public class TextMetrics extends JavaScriptObject { protected TextMetrics() {} /** * Return the width of the rendered text. * * @return the width of the text */ @JsProperty public final native double getWidth(); }
package com.hiwes.cores.thread.thread2.Thread0218; import java.util.concurrent.atomic.AtomicLong; /** * 但是原子类也并不完全安全: * 在具有有逻辑性的情况下的输出结果也是随机性的。 * 打印顺序出错,应该每加一次100,再加一次1。 */ public class MyThread11 extends Thread { private MyService11 service; public MyThread11(MyService11 service) { super(); this.service = service; } @Override public void run() { service.addNum(); } } class MyService11 { public static AtomicLong aiRef = new AtomicLong(); // public void addNum() { // 不使用synchronized同步就会出现顺序错误 synchronized public void addNum() { System.out.println(Thread.currentThread().getName() + "加了100之后的值是: " + aiRef.addAndGet(100)); aiRef.addAndGet(1); } } class Run11 { public static void main(String[] args) { try { MyService11 service = new MyService11(); MyThread11[] array = new MyThread11[5]; for (int i = 0; i < array.length; i++) { array[i] = new MyThread11(service); } for (int i = 0; i < array.length; i++) { array[i].start(); } Thread.sleep(1000); System.out.println(service.aiRef.get()); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.android.deskclock; import java.util.Calendar; import java.util.HashSet; import com.android.deskclock.provider.Alarm; import android.app.Dialog; import android.content.Context; import android.graphics.Color; import android.text.Editable; import android.text.TextWatcher; import android.text.format.DateFormat; import android.text.format.Time; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class AlarmDialogDelete { private final int[] DAY_ORDER = new int[] { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, }; private static final int DAYSUMMUNTIME = 24*60; private Dialog dialog; private Button b_h_up; private Button b_h_down; private EditText edit_hour; private Button b_ampm; private Button b_m_up; private Button b_m_down; private EditText edit_minute; private ToggleButton b_sun; private ToggleButton b_mon; private ToggleButton b_tue; private ToggleButton b_wed; private ToggleButton b_thr; private ToggleButton b_fri; private ToggleButton b_sat; private TextView text_after_alarm; private CheckBox checkbox_every_week; private Button b_sure; private Button b_delete; private Button b_mend; private Button b_cancel; private int hour_count; private int minute_count; private int hour_move_count; private AlarmClockFragment alarmClockFragment; private Alarm deleteAlarm; private View adapterItemView; private Context mContext; private boolean isAM ; public AlarmDialogDelete(Context context, Alarm alarm ,View view) { super(); mContext = context; deleteAlarm = alarm; adapterItemView = view; dialog = new Dialog(context, R.style.Dialog_notitle); dialog.setContentView(R.layout.dialog_new); dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失 initDialogView(); hideAndShowSettingButton(deleteAlarm); initData(alarm.hour,alarm.minutes); initDialogViewEvent(); } public void showDialog(){ if(dialog != null) { dialog.show(); } } private void hideAndShowSettingButton(Alarm alarm){ //b_h_up.setVisibility(View.GONE); //b_h_down.setVisibility(View.GONE); //b_m_up.setVisibility(View.GONE); //b_m_down.setVisibility(View.GONE); /* b_h_up.setBackgroundColor(Color.TRANSPARENT); b_h_up.setText(""); b_h_down.setBackgroundColor(Color.TRANSPARENT); b_h_down.setText(""); b_m_up.setBackgroundColor(Color.TRANSPARENT); b_m_up.setText(""); b_m_down.setBackgroundColor(Color.TRANSPARENT); b_m_down.setText(""); */ b_sure.setVisibility(View.GONE); b_delete.setVisibility(View.VISIBLE); b_mend.setVisibility(View.VISIBLE); HashSet<Integer> setDays = alarm.daysOfWeek.getSetDays(); checkbox_every_week.setChecked(true); if(setDays.size() >0){ for (int i = 0; i < 7; i++) { if (setDays.contains(DAY_ORDER[i])) { switch(i){ case 0: b_sun.setChecked(true); break; case 1: b_mon.setChecked(true); break; case 2: b_tue.setChecked(true); break; case 3: b_wed.setChecked(true); break; case 4: b_thr.setChecked(true); break; case 5: b_fri.setChecked(true); break; case 6: b_sat.setChecked(true); break; default: break; } } } } //checkbox_every_week.setEnabled(false); //setDisableToggleButton(); //edit_hour.setEnabled(false); //edit_minute.setEnabled(false); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); } private void initData(int hour,int minute) { Time time = new Time(); time.setToNow(); isAM = false; if(is24DateFormate()) b_ampm.setText(""); hour_count = hour; if(is24DateFormate()) edit_hour.setText("" + hour_count); else { if(hour_count == 12){ hour_count = hour_count + 0; edit_hour.setText("" + hour_count); b_ampm.setText(R.string.dialog_pm); isAM = false; } if(hour_count == 0){ hour_count = hour_count +12; edit_hour.setText("" + hour_count); b_ampm.setText(R.string.dialog_am); isAM = true; } if(hour_count > 0 && hour_count < 12){ hour_count = hour_count ; edit_hour.setText("" + hour_count); b_ampm.setText(R.string.dialog_am); isAM = true; } if(hour_count > 12 && hour_count <= 23){ hour_count = hour_count - 12; edit_hour.setText("" + hour_count); b_ampm.setText(R.string.dialog_pm); isAM = false; } } minute_count = minute; if(minute_count >=0 && minute_count<= 9) edit_minute.setText(""+"0"+minute_count); else edit_minute.setText("" + minute_count); hour_move_count = 0; if(!checkbox_every_week.isChecked()) setDisableToggleButton(); caculaterAlarmLeftTime(); } private void initDialogView() { if (dialog != null) { b_h_up = (Button) dialog.findViewById(R.id.button_dialog_hour_up); b_h_down = (Button) dialog .findViewById(R.id.button_dialog_hour_down); edit_hour = (EditText) dialog .findViewById(R.id.edittext_dialog_hour); b_ampm = (Button)dialog.findViewById(R.id.button_dialog_ampm); b_m_up = (Button) dialog.findViewById(R.id.button_dialog_minute_up); b_m_down = (Button) dialog .findViewById(R.id.button_dialog_minute_down); edit_minute = (EditText) dialog .findViewById(R.id.edittext_dialog_minute); b_sun = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_sun); b_mon = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_mon); b_tue = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_tue); b_wed = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_wed); b_thr = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_thr); b_fri = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_fri); b_sat = (ToggleButton) dialog .findViewById(R.id.togglebutton_dialog_sat); text_after_alarm = (TextView) dialog .findViewById(R.id.text_dialog_after_time_alarm); checkbox_every_week = (CheckBox) dialog .findViewById(R.id.checkbox_dialog_every_week); b_sure = (Button) dialog.findViewById(R.id.button_dialog_sure); b_delete = (Button) dialog.findViewById(R.id.button_dialog_delete); b_mend = (Button) dialog.findViewById(R.id.button_dialog_mend); b_cancel = (Button) dialog.findViewById(R.id.button_dialog_cancel); } } private void setDisableToggleButton(){ b_sun.setEnabled(false); b_mon.setEnabled(false); b_tue.setEnabled(false); b_wed.setEnabled(false); b_thr.setEnabled(false); b_fri.setEnabled(false); b_sat.setEnabled(false); } private void setEnableToggleButton(){ b_sun.setEnabled(true); b_mon.setEnabled(true); b_tue.setEnabled(true); b_wed.setEnabled(true); b_thr.setEnabled(true); b_fri.setEnabled(true); b_sat.setEnabled(true); } private void caculaterAlarmLeftTime(){ Time time = new Time(); time.setToNow(); int currentTime = time.hour * 60 + time.minute; int tempTime =0; if(is24DateFormate()) tempTime= hour_count *60 + minute_count; else{ if(isAM && hour_count == 12) tempTime = (hour_count-12)*60 + minute_count; if(isAM && 1<= hour_count && hour_count <= 11) tempTime= hour_count *60 + minute_count; if(!isAM && hour_count == 12) tempTime = (hour_count)*60 + minute_count; if(!isAM && 1<= hour_count && hour_count <= 11) tempTime= (hour_count +12 )*60 + minute_count; } int temp_left_time = 0; final Calendar c = Calendar.getInstance(); int currentDaysofWeek = c.get(Calendar.DAY_OF_WEEK); int tempDaysofWeek = 0; int days[] = getDaysofWeek(); int i= 0; int isCheckedCount = 0; boolean flag = false; for(;i< 7 ;i++) if(days[i]!= 0) isCheckedCount = isCheckedCount + 1; if(checkbox_every_week.isChecked()&& isCheckedCount > 0){ if(days[currentDaysofWeek-1]!=0 && isCheckedCount == 1 ){ tempDaysofWeek = c.get(Calendar.DAY_OF_WEEK); }else { for(int m = currentDaysofWeek-1;m <=6;m++) { if(days[m]!=0){ tempDaysofWeek = days[m]; flag = true; break; } } if(!flag){ for(int n = 0;n <=currentDaysofWeek -1;n++){ if(days[n]!=0) { tempDaysofWeek = days[n]; break; } } } } if(tempDaysofWeek == currentDaysofWeek && isCheckedCount == 1){ if(tempTime > currentTime) temp_left_time = tempTime - currentTime; else { temp_left_time = 7*DAYSUMMUNTIME - (currentTime - tempTime); } }else{ if(tempDaysofWeek == currentDaysofWeek){ if(tempTime > currentTime) temp_left_time = tempTime - currentTime; else { //temp_left_time = 7*DAYSUMMUNTIME - (currentTime - tempTime); flag = false; for(int m = currentDaysofWeek;m <=6;m++) { if(days[m]!=0){ tempDaysofWeek = days[m]; flag = true; break; } } if(!flag){ for(int n = 0;n <=currentDaysofWeek -2;n++){ if(days[n]!=0) { tempDaysofWeek = days[n]; break; } } } } } if(tempDaysofWeek < currentDaysofWeek){ if(tempTime > currentTime ) temp_left_time = ( 7 - (currentDaysofWeek - tempDaysofWeek ))*DAYSUMMUNTIME + (tempTime -currentTime); else temp_left_time =( 7 - (currentDaysofWeek - tempDaysofWeek ))*DAYSUMMUNTIME - (currentTime - tempTime); } if( tempDaysofWeek > currentDaysofWeek){ if(tempTime > currentTime) temp_left_time = (tempDaysofWeek - currentDaysofWeek)*DAYSUMMUNTIME +(tempTime - currentTime); else temp_left_time = (tempDaysofWeek - currentDaysofWeek)*DAYSUMMUNTIME - (currentTime - tempTime); } } }else{ if(tempTime > currentTime) temp_left_time = tempTime - currentTime; else temp_left_time = 1*DAYSUMMUNTIME - (currentTime - tempTime); } int DAY = temp_left_time/DAYSUMMUNTIME; int HOUR = (temp_left_time%DAYSUMMUNTIME)/60; int MINUTE = (temp_left_time%DAYSUMMUNTIME)%60; String sAgeFormat1 = mContext.getResources().getString(R.string.dialog_setting_show_alarm); String sFinal1 = String.format(sAgeFormat1, DAY+"",HOUR+"",MINUTE+""); text_after_alarm.setText(sFinal1); //text_after_alarm.setText("Day:"+ DAY +":Hou:"+ HOUR + ":Min:" + MINUTE ); } private void function_hour_up(){ hour_count++; if(is24DateFormate()){ if (hour_count > 23) hour_count = 0; }else{ if (hour_count > 12){ hour_count = 1; setAmPm(); } } edit_hour.setText("" + hour_count); } private void function_hour_down(){ hour_count--; if(is24DateFormate()){ if (hour_count < 0) hour_count = 23; }else{ if (hour_count < 1){ hour_count = 12; setAmPm(); } } edit_hour.setText("" + hour_count); } private void function_minute_up(){ minute_count++; if (minute_count > 59){ minute_count = 0; function_hour_up(); } if(minute_count >=0 && minute_count<= 9) edit_minute.setText(""+"0"+minute_count); else edit_minute.setText("" + minute_count); } private void function_minute_down(){ minute_count--; if (minute_count < 0){ minute_count = 59; function_hour_down(); } if(minute_count >=0 && minute_count<= 9) edit_minute.setText(""+"0"+minute_count); else edit_minute.setText("" + minute_count); } private void initDialogViewEvent() { b_h_up.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_MOVE) { hour_move_count++; if (hour_move_count > 20) { function_hour_up(); } } if (event.getAction() == MotionEvent.ACTION_UP) { function_hour_up(); hour_move_count = 0; } caculaterAlarmLeftTime(); return false; } }); b_h_down.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_MOVE) { hour_move_count++; if (hour_move_count > 20) { function_hour_down(); } } if (event.getAction() == MotionEvent.ACTION_UP) { function_hour_down(); hour_move_count = 0; } caculaterAlarmLeftTime(); return false; } }); b_m_up.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_MOVE) { hour_move_count++; if (hour_move_count > 20) { function_minute_up(); } } if (event.getAction() == MotionEvent.ACTION_UP) { function_minute_up(); hour_move_count = 0; } caculaterAlarmLeftTime(); return false; } }); b_m_down.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_MOVE) { hour_move_count++; if (hour_move_count > 20) { function_minute_down(); } } if (event.getAction() == MotionEvent.ACTION_UP) { function_minute_down(); hour_move_count = 0; } caculaterAlarmLeftTime(); return false; } }); edit_hour.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub String hour = edit_hour.getText().toString().trim(); if(!hour.equals("")){ if (isNumber(hour)) { int temp_hour_count = Integer.parseInt(hour); if(is24DateFormate()){ if (0 <= temp_hour_count && temp_hour_count <= 23) hour_count = temp_hour_count; else initData(hour_count,minute_count); }else{ if (1 <= temp_hour_count && temp_hour_count <= 12) hour_count = temp_hour_count; else initData(hour_count,minute_count); } } else { initData(hour_count,minute_count); } caculaterAlarmLeftTime(); } } }); edit_hour.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub edit_hour.setCursorVisible(true); return false; } }); edit_minute.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub String hour = edit_minute.getText().toString().trim(); if(!hour.equals("")){ if (isNumber(hour)) { int temp_hour_count = Integer.parseInt(hour); if (0 <= temp_hour_count && temp_hour_count <= 59) minute_count = temp_hour_count; else initData(hour_count,minute_count); } else { initData(hour_count,minute_count); } caculaterAlarmLeftTime(); } } }); edit_minute.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub edit_minute.setCursorVisible(true); return false; } }); b_sure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(alarmClockFragment != null){ if(checkbox_every_week.isChecked()) { alarmClockFragment.setAddNewAlarm(hour_count, minute_count, getDaysofWeek()); }else alarmClockFragment.setAddNewAlarm(hour_count, minute_count); //添加闹钟 } if(dialog != null) dialog.dismiss(); } }); b_mend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(is24DateFormate()) { hour_count = hour_count; }else{ if(isAM && hour_count == 12) hour_count = hour_count-12; if(isAM && 1<= hour_count && hour_count <= 11) hour_count= hour_count ; if(!isAM && hour_count == 12) hour_count = hour_count; if(!isAM && 1<= hour_count && hour_count <= 11) hour_count = hour_count +12 ; } if(alarmClockFragment != null){ alarmClockFragment.updateAlarm(deleteAlarm, hour_count, minute_count, getDaysofWeek()); } if(dialog != null) dialog.dismiss(); } }); b_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(alarmClockFragment != null) alarmClockFragment.asyncDeleteAlarm(deleteAlarm, adapterItemView); if(dialog != null) dialog.dismiss(); } }); b_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(dialog != null) dialog.dismiss(); } }); checkbox_every_week.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(checkbox_every_week.isChecked()) setEnableToggleButton(); else setDisableToggleButton(); } }); b_sun.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_mon.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_tue.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_wed.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_thr.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_fri.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_sat.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub caculaterAlarmLeftTime(); } }); b_ampm.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub setAmPm(); } }); } private void setAmPm(){ isAM = !isAM; if(isAM) b_ampm.setText(R.string.dialog_am); else b_ampm.setText(R.string.dialog_pm); } private int[] getDaysofWeek(){ int days[] = new int[7]; if(!checkbox_every_week.isChecked()){ for(int i=0;i<7;i++) days[i] = 0; return days; } if(b_sun.isChecked()) days[0] = 1; else days[0] = 0; if(b_mon.isChecked()) days[1] = 2; else days[1] = 0; if(b_tue.isChecked()) days[2] = 3; else days[2] = 0; if(b_wed.isChecked()) days[3] = 4; else days[3] = 0; if(b_thr.isChecked()) days[4] = 5; else days[4] = 0; if(b_fri.isChecked()) days[5] = 6; else days[5] = 0; if(b_sat.isChecked()) days[6] = 7; else days[6] = 0; return days; } private boolean isNumber(String str) { if(str.equals("")) return false; java.util.regex.Pattern pattern = java.util.regex.Pattern .compile("[0-9]*"); java.util.regex.Matcher match = pattern.matcher(str); if (match.matches() == false) { return false; } else { return true; } } public void setAlarmClockFragment(AlarmClockFragment malarmClockFragment){ alarmClockFragment = malarmClockFragment; } private boolean is24DateFormate(){ return DateFormat.is24HourFormat(mContext); } }
package td.td3.service2; import td.entities.Author; public class AuthorDAOTest { public static void main(String[] args) { AuthorDAO dao = new AuthorDAO() ; Author a = dao.findById(12); if ( a != null ) { System.out.println("Found " + a); } else { System.out.println("Not found "); } dao.deleteById(888); a = new Author(); a.setId(888); a.setFirstName("Emile"); a.setLastName("Zola"); dao.create(a); Author a2 = dao.findById(888); if ( a2 != null ) { System.out.println("Found " + a2); } else { System.out.println("Not found "); } a = new Author(); a.setId(999); a.setFirstName("Ernest"); a.setLastName("Hemingway"); dao.save(a); Author a3 = dao.findById(999); if ( a3 != null ) { System.out.println("Found " + a3); } else { System.out.println("Not found "); } } }
/** Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively. */ //cpp version : (Recursive) bool isSymmetric(TreeNode* root) { if(!root) return true; else return isMirror(root->left,root->right); } bool isMirror(TreeNode* n1, TreeNode* n2) { if(!n1 || !n2) return n1==n2; return (n1->val == n2->val && isMirror(n1->left,n2->right) && isMirror(n1->right,n2->left)); } //java version : (Non - Recursive) public boolean isSymmetric(TreeNode root) { if (root == null) return true; Stack<TreeNode> stack = new Stack<>(); stack.push(root.left); stack.push(root.right); while (!stack.empty()) { TreeNode n1 = stack.pop(), n2 = stack.pop(); if (n1 == null && n2 == null) continue; if (n1 == null || n2 == null || n1.val != n2.val) return false; stack.push(n1.left); stack.push(n2.right); stack.push(n1.right); stack.push(n2.left); } return true; }
package RMITest2; import java.io.*; import java.net.*; import java.rmi.*; import java.rmi.server.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.naming.NamingException; public class WarehouseClient { public static void main(String[] args) throws Exception { WarehouseClient thisclient=new WarehouseClient(); System.out.println("RMI registry binding:"); String url = "rmi://localhost:1099/central_warehoues"; Warehouse centralWarehouse = (Warehouse) Naming.lookup(url); String descr = "mate7"; double price = centralWarehouse.getPrice(descr); System.out.println(descr + ":" + price); System.out.println("mate8"+":"+centralWarehouse.getPrice("mate8")); centralWarehouse.SendMsg("Client communicating to Server!"); DataSet d=new DataSet(); d.LoadSample(); thisclient.ShowResult(d,new Vector(),false); for(int i=0;i<d.get_size();i++) { System.out.println(d.v.get(i).a+","+d.v.get(i).b); centralWarehouse.SendData(d.v.get(i).a,d.v.get(i).b); } String sv=centralWarehouse.LinearRegression(); Vector v=new Vector(Double.valueOf(sv.substring(0,sv.indexOf("#"))),Double.valueOf(sv.substring(sv.indexOf("#")+1))); System.out.println(v.a+","+v.b); thisclient.ShowResult(d,v,true); Scanner in=new Scanner(System.in); while(in.hasNextLine()) { centralWarehouse.SendMsg(in.nextLine()); } in.close(); } public void showMsg(String msg){ System.out.println(msg); } public void ShowResult(DataSet d,Vector v,boolean flag) { // 创建相框 JFrame jFrame = new JFrame("Client"); // 创建画板 JPanel jpanel = new JPanel() { //序列号(可省略) private static final long serialVersionUID = 1L; // 重写paint方法 @Override public void paint(Graphics graphics) { // 必须先调用父类的paint方法 super.paint(graphics); //graphics.drawOval(100, 70, 30, 30);//画圆形 //graphics.drawRect(105, 100, 20, 30);//画矩形 //graphics.drawLine(200, 0, 0, 120);// 画直线 //graphics.drawLine(0, 0, 150, 0);// 画直线 graphics.drawLine(5,5,250,5); graphics.drawString("x",260,10); graphics.drawLine(5,5,5,250); graphics.drawString("y",10,260); graphics.setColor(Color.RED); for(int i=0;i<d.get_size();i++) { graphics.fillOval((int)d.v.get(i).a+5, (int)d.v.get(i).b+5, 3, 3); } if(flag) { graphics.setColor(Color.black); double x1=0,y1=v.a*x1+v.b,x2=200,y2=v.a*x2+v.b; System.out.println(v.a+","+v.b); System.out.println(x1+","+y1+","+x2+","+y2); graphics.setColor(Color.blue); graphics.drawLine((int)x1+5, (int)y1+5, (int)x2+5, (int)y2+5); graphics.drawString("y="+v.a+"x+"+v.b,40,40); } graphics.setColor(Color.black); } }; //将画板嵌入到相框中 jFrame.add(jpanel); // 设置画框大小(宽度,高度),默认都为0 jFrame.setSize(350, 350); // 将画框展示出来。true设置可见,默认为false隐藏 jFrame.setVisible(true); } }
package com.example.bbarroo.bottombar; import android.content.Intent; import android.support.constraint.ConstraintLayout; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; /** * Created by Bbarroo on 2018-08-03. */ public class SecondFragment extends Fragment { public SecondFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_2, container,false); ListView listview = view.findViewById(R.id.listview2); LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_2,container,false); ListViewAdapter_A adapter = new ListViewAdapter_A() ; listview.setAdapter(adapter); // 첫 번째 아이템 추가. adapter.addItem(ContextCompat.getDrawable(getActivity(),R.drawable.baseline_favorite_black_24)) ; // 두 번째 아이템 추가. adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.baseline_location_on_black_18dp)) ; // 세 번째 아이템 추가. adapter.addItem(ContextCompat.getDrawable(getActivity(), R.drawable.baseline_motorcycle_black_18dp)) ; listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(position == 0) { Intent intent = new Intent(getActivity(), ActivityActivity.class); startActivity(intent); } } }); return view; } }
package fr.cg95.cvq.business.users; /** * Bean used to communication ecitizens creation information. * * @author bor@zenexity.fr * * FIXME : is it used outside unit tests ? */ public class CreationBean { private String login; private Long requestId; private Long homeFolderId; public void setLogin(final String login) { this.login = login; } public String getLogin() { return this.login; } public void setRequestId(final Long requestId) { this.requestId = requestId; } public Long getRequestId() { return this.requestId; } public Long getHomeFolderId() { return homeFolderId; } public void setHomeFolderId(Long homeFolderId) { this.homeFolderId = homeFolderId; } }
package tes.No15; public class Main { public static void main(String[] args) { Persegi k = new Persegi(); k.setSisi(10.0D); System.out.println(k); System.out.println("======================================"); System.out.println("Sisi : " + k.getSisi()); System.out.println("======================================="); System.out.println("Luas Permukaan Kubus : " + k.getLuasPemukaan()); System.out.println("Volume kubus : " + k.getVolume()); System.out.println("Luas Persegi : " + k.getLuasPersegi()); } }
/** * Main class to test the Form project. * * @author Erick de Oliveira Silva * @version 2017.09.23 */ public class Main { public static void main(String[] args) { // create the form repository and add the random forms. repositorioFormas r = new repositorioFormas(); // walks on through the form repository and print. System.out.println( r ); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pack1; /** * * @author gaurav.sharma */ public class Demo { public static void main(String args[]) { System.out.println(""); } }
package de.raidcraft.skillsandeffects.pvp.skills.healing; import de.raidcraft.RaidCraft; import de.raidcraft.api.items.CustomItemStack; import de.raidcraft.api.items.attachments.Consumeable; import de.raidcraft.skills.api.combat.EffectType; import de.raidcraft.skills.api.combat.action.HealAction; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Attribute; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.resource.Resource; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.TriggerHandler; import de.raidcraft.skills.api.trigger.TriggerPriority; import de.raidcraft.skills.api.trigger.Triggered; import de.raidcraft.skills.tables.THeroSkill; import de.raidcraft.skills.trigger.PlayerConsumeTrigger; import de.raidcraft.skillsandeffects.pvp.effects.buffs.generic.AttributeBuff; import de.raidcraft.skillsandeffects.pvp.effects.buffs.healing.ConsumeEffect; import lombok.Data; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; /** * @author Silthus */ @SkillInformation( name = "Consume", description = "Ermöglicht es durch Essen und Trinken Leben und Mana zu regenrieren.", types = {EffectType.HELPFUL, EffectType.BUFF, EffectType.HEALING} ) public class Consume extends AbstractSkill implements Triggered { private int requiredFoodLevel = 19; public Consume(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void load(ConfigurationSection data) { requiredFoodLevel = data.getInt("food-level", 19); } @TriggerHandler(ignoreCancelled = true, priority = TriggerPriority.MONITOR) public void onItemConsume(PlayerConsumeTrigger trigger) throws CombatException { if (getHolder().getPlayer().getFoodLevel() < requiredFoodLevel) { // the player has to have full food level for the regen to kick in return; } if (getHolder().isInCombat()) { trigger.getEvent().setCancelled(true); throw new CombatException("Du kannst im Kampf kein Essen zu dir nehmen."); } CustomItemStack customItem = RaidCraft.getCustomItem(trigger.getEvent().getItem()); if (customItem == null || !(customItem.getItem() instanceof Consumeable)) return; new ConsumeableWrapper((Consumeable) customItem.getItem()).consume(customItem); } @Data public class ConsumeableWrapper { private final Consumeable consumeable; public void consume(ItemStack itemStack) throws CombatException { CustomItemStack customItem = RaidCraft.getCustomItem(itemStack); if (customItem == null) return; if (getConsumeable().getConsumeableType() == Consumeable.Type.RESOURCE && getResource() == null) { throw new CombatException("Dir bringt der Verzehr dieses Gegenstands keine Regeneration."); } if (getConsumeable().getConsumeableType() == Consumeable.Type.ATTRIBUTE && getAttribute() == null) { throw new CombatException("Dir bringt der Verzehr dieses Gegenstands keine Attribut Steigerung."); } if (getConsumeable().isInstant()) { applyRessourceGain(getResourceGain()); } else { if (getType() == Consumeable.Type.ATTRIBUTE) { Consume.this.addEffect(AttributeBuff.class, effect -> { effect.setModifier(getResourceGain()); effect.setAttribute(getAttribute().getName()); if (getConsumeable().getDuration() > 0) effect.setDuration(getConsumeable().getDuration()); }); } else { Consume.this.addEffect(ConsumeEffect.class, effect -> { effect.setConsumeable(this); if (getConsumeable().getDuration() > 0) effect.setDuration(getConsumeable().getDuration()); if (getConsumeable().getInterval() > 0) effect.setInterval(getConsumeable().getInterval()); }); } } if (itemStack.getAmount() > 1) { itemStack.setAmount(itemStack.getAmount() - 1); } else { getHolder().getPlayer().getInventory().remove(itemStack); } } public void applyRessourceGain(double ressourceGain) throws CombatException { switch (getType()) { case HEALTH: new HealAction<>(this, getHolder(), ressourceGain).run(); break; case RESOURCE: Resource resource = getResource(); resource.setCurrent(resource.getCurrent() + ressourceGain); break; case ATTRIBUTE: Attribute attribute = getAttribute(); attribute.updateBaseValue((int) ressourceGain, true); break; } } public Attribute getAttribute() { return getHolder().getAttribute(getConsumeable().getResourceName()); } public Resource getResource() { return getHolder().getResource(getConsumeable().getResourceName()); } public double getResourceGain() { return getConsumeable().getResourceGain(); } public Consumeable.Type getType() { return getConsumeable().getConsumeableType(); } public boolean isPercentage() { return getConsumeable().isPercentage(); } } }
package persistencia; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.ImageIcon; import otros.DAOException; import presentacion.Carta; public class DAOCartasImp implements IDAOCartas { protected ConnectionManager conex; public DAOCartasImp() throws DAOException{ super(); try{ conex = new ConnectionManager(); }catch (ClassNotFoundException e){ throw new DAOException(e); } } @Override public Carta getCarta(int idCarta) { Carta carta = null; try{ conex.connect(); ResultSet rsCarta = conex.queryDB("select tipo, descripcion from Carta where ID="+idCarta); if(rsCarta.next()){ String tipo = rsCarta.getString("tipo"); String descripcion = rsCarta.getString("descripcion"); ImageIcon imagen = new ImageIcon("/imagenes/"+descripcion+".png"); carta = new Carta(descripcion, imagen, tipo); } conex.close(); }catch(Exception e){ System.out.println("Error al recuperar cartas partida"); } return carta; } @Override public java.util.List<Carta> getCartaJugador(int idjugador, int idpartida) { ArrayList<Carta> cartas= new ArrayList<Carta>();// 3 en caso de que sean 6 jugadores try{ conex.connect(); ResultSet cartasjugador = conex.queryDB("select descripcion, tipo from Carta where ID IN (select ID_carta from Jug_Part_Cartas where ID_Jug="+idjugador+" AND ID_Partida="+idpartida+" )"); while(cartasjugador.next()){ //System.out.println(coleccion6jugadores.getString("nombre")); String descripcion = cartasjugador.getString("descripcion"); String tipo = cartasjugador.getString("tipo"); cartas.add(new Carta(descripcion,new ImageIcon(this.getClass().getResource("/imagenes/"+descripcion+".png")),tipo)); } conex.close(); }catch(Exception e){ System.out.println("Error al recuperar cartas partida"); } return cartas; } @Override public Carta[] getAcusacion(int idPArtida) { Carta [] cartasAcusacion = new Carta [3]; try{ conex.connect(); //obtenemos la carta arma ResultSet cartaAcusacion = conex.queryDB("select tipo, descripcion from Carta where descripcion IN ( select arma from Acusacion_Partida where ID="+idPArtida+")"); cartaAcusacion.next(); String descripcion = cartaAcusacion.getString("descripcion"); String tipo = cartaAcusacion.getString("tipo"); cartasAcusacion[0]=new Carta(descripcion,new ImageIcon(this.getClass().getResource("/imagenes/"+descripcion+".png")),tipo); //obtenemos la cartaa asesino cartaAcusacion = conex.queryDB("select tipo, descripcion from Carta where descripcion IN ( select asesino from Acusacion_Partida where ID="+idPArtida+")"); cartaAcusacion.next(); descripcion = cartaAcusacion.getString("descripcion"); tipo = cartaAcusacion.getString("tipo"); cartasAcusacion[1]=new Carta(descripcion,new ImageIcon(this.getClass().getResource("/imagenes/"+descripcion+".png")),tipo); //obtenemos la carta habitacion cartaAcusacion = conex.queryDB("select tipo, descripcion from Carta where descripcion IN ( select habitacion from Acusacion_Partida where ID="+idPArtida+")"); cartaAcusacion.next(); descripcion = cartaAcusacion.getString("descripcion"); tipo = cartaAcusacion.getString("tipo"); cartasAcusacion[2]=new Carta(descripcion,new ImageIcon(this.getClass().getResource("/imagenes/"+descripcion+".png")),tipo); conex.close(); }catch(Exception e){ System.out.println("Error al recuperar cartas partida"); } return cartasAcusacion; } @Override public void setAcusacion(Carta[] cartas) { // TODO Auto-generated method stub } @Override public Carta[] getSolucion() { // TODO Auto-generated method stub return null; } @Override public void setSolucion(Carta[] solucion) { // TODO Auto-generated method stub } @Override public int getIdCarta(String nombreCarta){ int idCarta=-1; try{ conex.connect(); ResultSet rsIdCarta =conex.queryDB("select ID from Carta where descripcion = '"+nombreCarta+"'"); if(rsIdCarta.next()){ //si la consulta contiene alguna fila idCarta = rsIdCarta.getInt("ID"); } conex.close(); }catch(Exception e){ e.printStackTrace(); System.out.println("ERROR SELECT_ID_CARTA"); } return idCarta; } public int[] getIdCarta(String[] nombreCarta){ int res[] = new int [nombreCarta.length]; String query = "SELECT ID FROM Carta WHERE descripcion='" + nombreCarta[0] + "'"; for (int i=1; i<nombreCarta.length; i++){ query+= " OR descripcion= '" + nombreCarta[i] + "'"; } query+=" ORDER BY ID ASC"; try{ conex.connect(); ResultSet rs = conex.queryDB(query); for (int i=0; i<res.length; i++){ rs.next(); res[i] = rs.getInt("ID"); } } catch (Exception e){ e.printStackTrace(); System.out.println("ERROR al sacar los IDs de las cartas"); } return res; } }
package prefeitura.siab.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import prefeitura.siab.persistencia.DoencaDao; import prefeitura.siab.tabela.Doenca; @Component public class DoencaController { private @Autowired DoencaDao dao; @Transactional public void salvarDoenca(Doenca doenca) throws BusinessException{ Doenca auxiliar = dao.searchDoenca(doenca); if(auxiliar != null){ if(auxiliar.getSigla().equals(doenca.getSigla()) && auxiliar.getNome().equals(doenca.getNome())){ throw new BusinessException("Essa Doença/Condição já está cadastrada!"); }else if(auxiliar.getSigla().equals(doenca.getSigla())){ throw new BusinessException("Essa Sigla já está cadastrada!"); }else if(auxiliar.getNome().equals(doenca.getNome())){ throw new BusinessException("O nome: "+ doenca.getNome() + " já está cadastrado!"); } } dao.insert(doenca); } }
package pl.training.shop.product.model; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; public interface ProductsRepository extends JpaRepository<Product, Long> { Optional<Product> getByName(String name); Product getById(Long id); @Query("select p from Product p where p.quantity > 0") List<Product> getAvailableProducts(); @Transactional @Modifying @Query("update Product p set p.quantity = p.quantity - 1 where p.id = :id") void decreaseQuantity(@Param("id") Long id); }
package com.noteshare.questions.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.noteshare.common.filter.XSSFilterUtil; import com.noteshare.common.utils.constant.Constants; import com.noteshare.questions.model.Answer; import com.noteshare.questions.services.AnswerService; import com.noteshare.user.model.User; @Controller @RequestMapping("answer") public class AnswerController { @Resource private AnswerService answerService; /** * 根据笔记id查询笔记评论列表 * @param model * @param noteId 笔记Id * @return */ @RequestMapping("/{questionId}/discussList") public String discussList(@PathVariable Integer questionId,ModelMap model){ List<Answer> discussList = answerService.selectDiscussListByQuestionId(questionId); model.put("discussList", discussList); return "questions/discussList"; } /** * 根据问题id给问题添加评论 * @param model * @param noteId 问题id * @param comment 问题回复 * @return */ @RequestMapping("addDiscuss") @ResponseBody public String addDiscuss(int questionId,String comment,HttpSession session){ //TODO:xss针对特殊字符进行过滤。 comment = XSSFilterUtil.XSSReplace(comment); User user = (User) session.getAttribute(Constants.SESSION_USER); Answer answer = new Answer(); answer.setComment(comment); answer.setQuestionsid(questionId); return answerService.addDiscuss(user,answer); } }
public class AtoZ { public static void main(String[] agrs) { char[] alph = new char[26]; for(char ch = 'A', j = 0; j < alph.length; ch++, j++) { alph[j] = ch; } for(int i = 0; i < alph.length; i++) { System.out.println(alph[i]); } } }
package com.adachina.mqKafka.sample.api; import com.adachina.mqKafka.core.AdaKafkaProducer; import com.adachina.mqKafka.sample.domain.Dog; import org.apache.kafka.clients.producer.RecordMetadata; import java.util.concurrent.Future; /** * Sample for use {@link AdaKafkaProducer} with Java API. * * @author Robert Lee * @since Aug 21, 2015 * */ public class KafkaProducerSample { public static void main(String[] args) throws InterruptedException { AdaKafkaProducer adaKafkaProducer = new AdaKafkaProducer("kafka-producer.properties", "test"); for (int i = 0; i < 10; i++) { Dog dog = new Dog(); dog.setName("Yours " + i); dog.setId(i); Future<RecordMetadata> future = adaKafkaProducer.sendBean2Topic("test", dog); System.out.format(future.toString()+"++++++++++Sending dog: %d \n", i + 1); Thread.sleep(100); } } }
package com.jiaming.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author jmstart * @create 2020-04-25 10:37 */ @RestController public class QuickController01 { @RequestMapping("/quick01") public String quick01() { return "Test SpringBoot Quick Build"; } }
package com.ceiba.parkingceiba.domain; import java.util.Date; import com.ceiba.parkingceiba.model.entity.Parqueadero; import com.ceiba.parkingceiba.util.EnumTipoVehiculo; public interface IControlParqueadero { public boolean validarPlacaIniciaPorLetraA(String placa); public boolean buscarEspacioPorTipoVehiculo(EnumTipoVehiculo tipoVehiculo); public boolean buscarVehiculoEstacionado(String placa); public boolean validarSiPaqueaderoEstaVacio(); public Parqueadero getParqueaderoParaAsignar(String placa); public int generarCobro (EnumTipoVehiculo tipoVehiculo, Date fechaIngreso, Date fechaSalida, int cilindraje); public int calcularCobro(Date fechaIngreso, Date fechaSalida, int valorDia, int valorHora); }
package client.model.database; import client.model.BlackRecord; import client.model.Record; import com.sun.org.apache.regexp.internal.RE; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Александр on 26.09.2017. */ public class RecordTable { private Connection connection; private final static String SQL_DELETE_RECORDS = "DELETE FROM record WHERE id=?"; private final static String SQL_INSERT_RECORD = "INSERT INTO record(mark,model,year,bulk,numberStateRegistration,color,failure,money,date,time,price,pay,paid,idCLient)" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; private final static String SQL_GET_ALL_BY_CLIENT = "SELECT * FROM record WHERE idClient=? ORDER BY date,time"; private final static String SQL_GET_ID_CLIENT_BY_RECORD = "SELECT idCLient FROM record WHERE id=?"; private final static String SQL_GET_OVERDUE_RECORDS = "SELECT idClient,id FROM record WHERE (CURDATE()>date " + "OR (CURDATE()=date AND CURTIME()>time))"; private final static String SQL_DELETE_OVERDUE_RECORDS = "DELETE FROM record WHERE (CURDATE()>date " + "OR (CURDATE()=date AND CURTIME()>time))"; public RecordTable() throws SQLException { connection = ConnectorDB.getConnection(); } /* public Record get(Integer id) throws SQLException { PreparedStatement preparedStatement = this.getPrepareStatement(SQL_GET_RECORD); preparedStatement.setInt(1, (Integer) id); Record record = new Record(); ResultSet resultSet = preparedStatement.getResultSet(); while (resultSet.next()) { record.getCarModel().setMark(resultSet.getString(1)); record.getCarModel().setModel(resultSet.getString(2)); record.getCarModel().setYear(resultSet.getInt(3)); record.getCarModel().setBulk(resultSet.getDouble(4)); record.getCarModel().setNumberStateRegistration(resultSet.getString(5)); record.getCarModel().setColor(resultSet.getString(6)); record.getFailure().setTypeOfFailure(resultSet.getString(7)); record.setDate(resultSet.getDate(8).toLocalDate()); record.setTime(resultSet.getTime(9).toLocalTime()); record.setIdClient(resultSet.getInt(10)); record.setId(resultSet.getInt(11)); } return record; } */ public Boolean delete(Integer id) throws SQLException { PreparedStatement preparedStatement = this.getPrepareStatement(SQL_DELETE_RECORDS); preparedStatement.setInt(1, id); if (preparedStatement.executeUpdate() != 0) return true; return false; } public Integer getIdCLinent(Integer id) throws SQLException { PreparedStatement preparedStatement = this.getPrepareStatement(SQL_GET_ID_CLIENT_BY_RECORD); preparedStatement.setInt(1, id); ResultSet resultSet = preparedStatement.executeQuery(); resultSet.next(); return resultSet.getInt(1); } public Boolean add(Record record) throws SQLException { PreparedStatement preparedStatement = this.getPrepareStatement(SQL_INSERT_RECORD); preparedStatement.setString(1, record.getCarModel().getMark()); preparedStatement.setString(2, record.getCarModel().getModel()); preparedStatement.setInt(3, record.getCarModel().getYear()); preparedStatement.setDouble(4, record.getCarModel().getBulk()); preparedStatement.setString(5, record.getCarModel().getNumberStateRegistration()); preparedStatement.setString(6, record.getCarModel().getColor()); preparedStatement.setString(7, record.getFailure().getTypeOfFailure()); preparedStatement.setInt(8, record.getFailure().getPrice()); preparedStatement.setDate(9, Date.valueOf(record.getDate())); preparedStatement.setTime(10, Time.valueOf(record.getTime())); preparedStatement.setInt(11, record.getPayment().getPrice()); preparedStatement.setInt(12, record.getPayment().getPay()); preparedStatement.setBoolean(13, record.getPayment().getStatus()); preparedStatement.setInt(14, record.getIdClient()); if (preparedStatement.executeUpdate() != 0) return true; return false; } public ArrayList<Record> getAllByIdClient(Integer idClient) throws SQLException { ArrayList<Record> arrayList = new ArrayList<>(); PreparedStatement preparedStatement = this.getPrepareStatement(SQL_GET_ALL_BY_CLIENT); preparedStatement.setInt(1, idClient); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { Record record = new Record(); record.getCarModel().setMark(resultSet.getString(1)); record.getCarModel().setModel(resultSet.getString(2)); record.getCarModel().setYear(resultSet.getInt(3)); record.getCarModel().setBulk(resultSet.getDouble(4)); record.getCarModel().setNumberStateRegistration(resultSet.getString(5)); record.getCarModel().setColor(resultSet.getString(6)); record.getFailure().setTypeOfFailure(resultSet.getString(7)); record.getFailure().setPrice(resultSet.getInt(8)); record.setDate(resultSet.getDate(9).toLocalDate()); record.setTime(resultSet.getTime(10).toLocalTime()); record.getPayment().setPrice(resultSet.getInt(11)); record.getPayment().setPay(resultSet.getInt(12)); record.getPayment().setStatus(resultSet.getBoolean(13)); record.setIdClient(resultSet.getInt(14)); record.setId(resultSet.getInt(15)); arrayList.add(record); } return arrayList; } public ArrayList<BlackRecord> update() throws SQLException { ArrayList<BlackRecord> blackList = new ArrayList<>(); PreparedStatement preparedStatementToGetOverDueRecords = this.getPrepareStatement(SQL_GET_OVERDUE_RECORDS); PreparedStatement preparedStatementToDeleteOverdueRecodrs = this.getPrepareStatement(SQL_DELETE_OVERDUE_RECORDS); ResultSet resultSet = preparedStatementToGetOverDueRecords.executeQuery(); while (resultSet.next()) { BlackRecord blackRecord = new BlackRecord(); blackRecord.setIdClient(resultSet.getInt(1)); blackRecord.setIdRecord(resultSet.getInt(2)); blackList.add(blackRecord); } preparedStatementToDeleteOverdueRecodrs.executeUpdate(); return blackList; } private PreparedStatement getPrepareStatement(String sgl) { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sgl); } catch (SQLException e) { e.printStackTrace(); } return preparedStatement; } }
package ticketWriter; import java.io.IOException; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ticketApi.Ticket; import ticketApi.TicketSink; import ticketApi.TicketSource; @Component public class TicketWriter implements TicketSink { TicketSource ticketSource; private ObjectMapper mapper; private JsonGenerator generator; @Autowired void setTicketSource(TicketSource aSource) { ticketSource = aSource; } // Insert a ticket into the writer public void addTicket(Ticket ticket) { if (generator == null) { startOutput(); } if (generator != null) { try { mapper.writeValue(generator, ticket); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // Close the output public void closeOutput() { try { generator.writeEndArray(); generator.close(); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Initialise the output private void startOutput() { mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); try { generator = f.createJsonGenerator(System.out); generator.useDefaultPrettyPrinter(); generator.writeStartArray(); } catch (JsonGenerationException e) { e.printStackTrace(); mapper = null; generator = null; } catch (IOException e) { e.printStackTrace(); mapper = null; generator = null; } } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.extension.frontend.client.widget.zoho; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.Frame; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.openkm.extension.frontend.client.service.OKMZohoService; import com.openkm.extension.frontend.client.service.OKMZohoServiceAsync; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.constants.ui.UIDialogConstants; import com.openkm.frontend.client.extension.comunicator.GeneralComunicator; /** * ZohoWriter * * @author jllort */ public class ZohoPopup extends DialogBox { private final OKMZohoServiceAsync zohoService = (OKMZohoServiceAsync) GWT.create(OKMZohoService.class); public static final int DEFAULT_WIDTH = 1020; public static final int DEFAULT_HEIGHT = 720; private VerticalPanel vPanel; private Frame frame; private Button close; /** * ZohoWriterPopup */ public ZohoPopup(String title, String url, final String id) { super(false, true); int width = DEFAULT_WIDTH; int height = DEFAULT_HEIGHT; // Calculate size if (Main.get().mainPanel.getOffsetHeight() < height + UIDialogConstants.MARGIN) { height = Main.get().mainPanel.getOffsetHeight() - UIDialogConstants.MARGIN; } if (Main.get().mainPanel.getOffsetWidth() < width + UIDialogConstants.MARGIN) { width = Main.get().mainPanel.getOffsetWidth() - UIDialogConstants.MARGIN; } setText(title); vPanel = new VerticalPanel(); frame = new Frame(url); DOM.setElementProperty(frame.getElement(), "frameborder", "0"); DOM.setElementProperty(frame.getElement(), "marginwidth", "0"); DOM.setElementProperty(frame.getElement(), "marginheight", "0"); frame.setWidth(String.valueOf(width)+"px"); frame.setHeight(String.valueOf(height - UIDialogConstants.FRAME_OFFSET - UIDialogConstants.DIALOG_TOP)+"px"); frame.setStyleName("okm-Popup-text"); close = new Button(GeneralComunicator.i18n("button.close")); close.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { close.setEnabled(false); zohoService.closeZohoWriter(id, new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { hide(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("closeZohoWriter", caught); } }); } }); close.addStyleName("okm-Input"); vPanel.setWidth(String.valueOf(width)+"px"); vPanel.setHeight(String.valueOf(height - UIDialogConstants.DIALOG_TOP)+"px"); vPanel.add(frame); HorizontalPanel hPanel = new HorizontalPanel(); hPanel.add(close); vPanel.add(hPanel); vPanel.setCellHeight(frame, String.valueOf(height - UIDialogConstants.FRAME_OFFSET - UIDialogConstants.DIALOG_TOP)+"px"); vPanel.setCellHeight(hPanel, String.valueOf(UIDialogConstants.BUTTONS_HEIGHT)+"px"); vPanel.setCellHorizontalAlignment(hPanel, HasAlignment.ALIGN_CENTER); vPanel.setCellVerticalAlignment(hPanel, HasAlignment.ALIGN_MIDDLE); setWidget(vPanel); } }
package com.seu.care.bed.model; import java.util.Date; public class Bed { private Integer id; private Date createTime; private String createBy; private String roomNumber; private String bedStatus; private String positionType; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy == null ? null : createBy.trim(); } public String getRoomNumber() { return roomNumber; } public void setRoomNumber(String roomNumber) { this.roomNumber = roomNumber == null ? null : roomNumber.trim(); } public String getBedStatus() { return bedStatus; } public void setBedStatus(String bedStatus) { this.bedStatus = bedStatus == null ? null : bedStatus.trim(); } public String getPositionType() { return positionType; } public void setPositionType(String positionType) { this.positionType = positionType == null ? null : positionType.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } }
package day31JavaReviews; import java.util.Arrays; import java.util.Scanner; public class ArrayReviews1 { public static void main(String[] args) { /* Array: store multiple data to a variable Array's size is fixed */ int num=10; //decleration of Array int [] arr= { 10 };//array size is 1 and fixed==[10] // arr[1]=20; // System.out.println(arr[1]);//out of bound exception //initializing array's size int [] arr2=new int [2];//[0,0],maximum capacity of the Array is 2 System.out.println(arr2[0]);//default value ==0 System.out.println(arr2[1]);//0 default number //exp String[] cars=new String[5];//takes 5 elements //{Tesla, Audi, Toyota, Jeep,Subaru} cars[4]="Subaru"; cars[2]="Toyota"; cars[1]="Audi"; cars[3]="Jeep"; cars[0]="Tesla"; for(int i=0;i<=cars.length-1;i++) { System.out.print(cars[i]+" "); } System.out.println(); System.out.println("++++++++++++++++++"); cars=new String[10]; //{"ford","Honda","BMW","Volvo","Volkswagon"} cars[5]="Ford"; System.out.println(Arrays.toString(cars)); System.out.println("**************"); boolean [] bool= {10>9,"Mikray".equals("Seyfo")}; // true false boolean b1=bool[0]; boolean b2=bool[1]; System.out.println(b1);//true System.out.println(b2);//false //Arrays.toString: converts 1D Array to String System.out.println(bool);//hash code String str=Arrays.toString(bool); System.out.println(str);//[true, false] //Arrays.sort(variablename):it is not return method, just sort the Array, by ascending order, double [] dArray= {1000,900,800,700,600}; System.out.println(Arrays.toString(dArray)); //expected result is {600,700,800,900,1000}; Arrays.sort(dArray);// {600,700,800,900,1000}; System.out.println(Arrays.toString(dArray)); //IQ=exp;print each value of the given array in descending order int [] numbers= {200, 300, 20, 7890, 40, -9,-100}; // sort it first then reverse it by for loop Arrays.sort(numbers);//sorts the array in ascending order System.out.println(Arrays.toString(numbers)); System.out.println("%%%%%%%%%%%%%%%%%"); String result=""; for(int i= numbers.length-1;i>=0;i--) { result+=numbers[i]+", "; } result=result.replace("-100", "-100");//another solution but just for this case result=result.substring(0,result.lastIndexOf(",")); System.out.println(result); // ask user how many numbers want to add then find he maximum an minimum in Array Scanner scan=new Scanner(System.in); System.out.println("how many numbers would you like to add"); int number =scan.nextInt(); int [] arr3=new int [number]; for(int i=0;i<arr3.length;i++) { System.out.println("Enter a number "); arr3[i]=scan.nextInt(); } System.out.println(Arrays.toString(arr3)); Arrays.sort(arr3); System.out.println("min num: "+arr3[0]); System.out.println("max num: "+arr3[arr3.length-1]); } }
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.migrator; import org.slf4j.migrator.line.EmptyRuleSet; import org.slf4j.migrator.line.JCLRuleSet; import org.slf4j.migrator.line.JULRuleSet; import org.slf4j.migrator.line.Log4jRuleSet; import org.slf4j.migrator.line.RuleSet; /** * This class runs Pattern matching with java.util.regex using Patterns defined * in concrete implementations * * @author jean-noelcharpin * */ public abstract class RuleSetFactory { /** * Return matcher implementation depending on the conversion mode * * @param conversionType * @return AbstractMatcher implementation */ public static RuleSet getMatcherImpl(int conversionType) { switch (conversionType) { case Constant.JCL_TO_SLF4J: return new JCLRuleSet(); case Constant.LOG4J_TO_SLF4J: return new Log4jRuleSet(); case Constant.JUL_TO_SLF4J: return new JULRuleSet(); case Constant.NOP_TO_SLF4J: return new EmptyRuleSet(); default: return null; } } }
package com.fleet.zip.util; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipInputStream; /** * Zip 工具类 * * @author April Han */ public class ZipUtil { private final static Logger logger = LoggerFactory.getLogger(ZipUtil.class); /** * 读取 .zip 文件内容 * * @param zipFile 压缩文件 */ public static List<String> read(File zipFile) throws IOException { List<String> list = new ArrayList<>(); InputStream is = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is), Charset.forName("GBK")); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { list.add(zipEntry.getName()); } zis.closeEntry(); is.close(); return list; } /** * 压缩成 .zip 文件 * * @param zipFile 压缩的目标文件 * @param srcFileList 压缩的源文件 */ public static void zip(String zipFile, List<File> srcFileList) throws IOException { if (!zipFile.endsWith(".zip") && !zipFile.endsWith(".ZIP")) { logger.error("file [" + zipFile + "] is not .zip type file"); return; } zip(new File(zipFile), srcFileList); } /** * 压缩成 .zip 文件 * * @param zipFile 压缩的目标文件 * @param srcFileList 压缩的源文件 */ public static void zip(File zipFile, List<File> srcFileList) throws IOException { if (!zipFile.getName().endsWith(".zip") && !zipFile.getName().endsWith(".ZIP")) { logger.error("file [" + zipFile + "] is not .zip type file"); return; } OutputStream os = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(os); zos.setEncoding("GBK"); for (File srcFile : srcFileList) { if (!zipFile.getPath().equals(srcFile.getPath())) { zipFile(zos, srcFile, ""); } } zos.finish(); zos.close(); os.flush(); os.close(); } /** * @param zos 文件流 * @param srcFile 压缩的源文件 * @param path 在 .zip 中的相对路径 * @throws IOException */ private static void zipFile(ZipOutputStream zos, File srcFile, String path) throws IOException { if (!"".equals(path) && !path.endsWith(File.separator)) { path += File.separator; } if (srcFile.isDirectory()) { zos.putNextEntry(new ZipEntry(path + srcFile.getName() + File.separator)); zos.closeEntry(); File[] files = srcFile.listFiles(); if (files != null && files.length != 0) { for (File f : files) { zipFile(zos, f, path + srcFile.getName()); } } } else { InputStream is = new FileInputStream(srcFile); ZipEntry zipEntry = new ZipEntry(path + srcFile.getName()); zos.putNextEntry(zipEntry); byte[] b = new byte[1024]; int len; while ((len = is.read(b)) > 0) { zos.write(b, 0, len); } zos.closeEntry(); is.close(); } } /** * 解压缩 .zip 文件 * * @param zipFile 压缩文件地址 * @param targetDir 解压文件输出的目录 */ public static void unzip(String zipFile, String targetDir) throws IOException { if (!zipFile.endsWith(".zip") && !zipFile.endsWith(".ZIP")) { logger.error("file [" + zipFile + "] is not .zip type file"); return; } unzip(new File(zipFile), targetDir); } /** * 解压缩 .zip 文件 * * @param zipFile 压缩文件 * @param targetDir 解压文件输出的目录 */ public static void unzip(File zipFile, String targetDir) throws IOException { unzip(new ZipFile(zipFile, "GBK"), targetDir); } /** * 解压缩 .zip 文件 * * @param zipFile 压缩文件 * @param targetDir 解压文件输出的目录 */ public static void unzip(ZipFile zipFile, String targetDir) throws IOException { if (!mkdirs(targetDir)) { return; } if (!targetDir.endsWith(File.separator)) { targetDir += File.separator; } Enumeration<ZipEntry> zipEntries = zipFile.getEntries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { mkdirs(targetDir + zipEntry.getName()); } else { File file = new File(targetDir + zipEntry.getName()); File parentFile = file.getParentFile(); mkdirs(parentFile); InputStream is = zipFile.getInputStream(zipEntry); OutputStream os = new FileOutputStream(file); byte[] b = new byte[1024]; int len; while ((len = is.read(b)) > 0) { os.write(b, 0, len); } is.close(); os.flush(); os.close(); } } } public static boolean mkdirs(String dirs) { File fileDirs = new File(dirs); return mkdirs(fileDirs); } public static boolean mkdirs(File fileDirs) { if (fileDirs.exists()) { return fileDirs.isDirectory(); } else { return fileDirs.mkdirs(); } } }
package pages; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class GoogleHomePage { WebDriver driver; @FindBy(how = How.CSS, using = "#lst-ib") public static WebElement searchfield; public void enterSearchItem(String searchitem) { searchfield.sendKeys(searchitem); searchfield.sendKeys(Keys.ENTER); } }
package com.porsche.sell.utils; import com.porsche.sell.vo.ResultVo; /** 方法结果集工具类 * @author XuHao * Email 15229357319@sina.cn * create on 2018/8/10 */ public class ResultUtil { /** * 成功结果(含有数据) * @param obj * @return */ public static ResultVo success(Object obj){ ResultVo resultVo = new ResultVo(); resultVo.setCode(0); resultVo.setMsg("success"); resultVo.setData(obj); return resultVo; } /** * 成功结果 * @return */ public static ResultVo success(){ return success(null); } /** * 失败结果 * @param code * @param msg * @return */ public static ResultVo error(Integer code, String msg){ ResultVo resultVo = new ResultVo(); resultVo.setCode(code); resultVo.setMsg(msg); return resultVo; } }
import javax.swing.JFrame; import java.awt.Color; import javax.swing.JOptionPane; public class GraphicsMain { public static void main(String[] args) { JFrame myFrame = new JFrame("Increment/Decrement"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GraphicsPanel panel1 = new GraphicsPanel(); myFrame.setContentPane(panel1); myFrame.pack(); myFrame.setVisible(true); panel1.drawLine(Color.RED, 100, 100, 200, 100); panel1.drawLine(Color.RED, 100, 100, 100, 200); panel1.drawLine(Color.RED, 100, 200, 200, 200); panel1.drawLine(Color.RED, 200, 200, 200, 100); myFrame.setSize(800,400); } }
/* * created 08.08.2005 * * $Id: ColumnPair.java 3 2005-11-02 03:04:20Z csell $ */ package com.byterefinery.rmbench.views.table; import com.byterefinery.rmbench.model.schema.Column; import com.byterefinery.rmbench.model.schema.ForeignKey; /** * helper class for maintaining a pair of column -> target column in the context of * foreign key/reference views * * @author cse */ class ColumnPair { final Column column; final Column targetColumn; private ColumnPair(Column column, Column targetColumn) { this.column = column; this.targetColumn = targetColumn; } static ColumnPair[] createFrom(ForeignKey key) { Column[] cols = key.getColumns(); ColumnPair[] result = new ColumnPair[cols.length]; for (int i = 0; i < result.length; i++) { result[i] = new ColumnPair(cols[i], key.getTargetColumn(cols[i])); } return result; } }
package Q12; public class Q12 { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder("Duke"); String str1 =sb1.toString(); String str2=str1; System.out.println(str1==str2); } }
package com.root.mssm.ui.home; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.NavController; import androidx.navigation.Navigation; import com.google.android.material.snackbar.Snackbar; import com.root.mssm.Adapter.AdapterBestProduct; import com.root.mssm.Adapter.AdapterBottomSlider; import com.root.mssm.Adapter.AdapterBrands; import com.root.mssm.Adapter.AdapterFeatureProduct; import com.root.mssm.Adapter.AdapterHotProducts; import com.root.mssm.Adapter.AdapterLatestProduct; import com.root.mssm.Adapter.AdapterTopProduct; import com.root.mssm.Adapter.CategoryAdapter; import com.root.mssm.Adapter.SliderAdapterExample; import com.root.mssm.List.List.home.HomeList; import com.root.mssm.R; import com.root.mssm.databinding.FragmentHomeBinding; import com.root.mssm.global.Global; import com.root.mssm.service.ChinniInterface; import com.root.mssm.service.Config; import com.root.mssm.service.Cookies; import com.root.mssm.service.SessionManage; import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType; import com.smarteist.autoimageslider.SliderAnimations; import com.smarteist.autoimageslider.SliderView; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static android.content.ContentValues.TAG; public class HomeFragment extends Fragment { private HomeViewModel homeViewModel; private FragmentHomeBinding binding; NavController navController; ChinniInterface chinniInterface; ProgressDialog dialog; SessionManage sessionManage; Cookies cookies; SliderAdapterExample adapter1; AdapterBottomSlider adapterbottom; CategoryAdapter adapter; AdapterFeatureProduct adapterfeature; AdapterBestProduct adapterbestProduct; AdapterTopProduct adapterTopProduct; AdapterHotProducts adapterHotProducts; AdapterLatestProduct adapterLatestProduct; AdapterBrands adapterBrands; List<HomeList> homeLists= new ArrayList<>(); boolean action= false; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); dialog = new ProgressDialog(getActivity()); dialog.setMessage("Please Wait..."); navController = Navigation.findNavController(view); chinniInterface = Config.getClient().create(ChinniInterface.class); sessionManage = new SessionManage(getActivity()); cookies = new Cookies(); if (((Global) getActivity().getApplicationContext()).getHomeLists().isEmpty()) { homeLists = cookies.getAppdata(getActivity()); Log.e(TAG, "onViewCreated: " + homeLists.isEmpty()); if(homeLists.get(0).getSliders()!=null){ setCategory(); setSlider(); setFeatureProduct(); setBestProduct(); setTopProduct(); setBottomSlider(); setHOTProduct(); setLatestProduct(); setBrands(); FragmentAction(); dialog.cancel(); GetContent(false); }else { GetContent(true); } } else { homeLists = ((Global) getActivity().getApplicationContext()).getHomeLists(); setCategory(); setSlider(); setFeatureProduct(); setBestProduct(); setTopProduct(); setBottomSlider(); setHOTProduct(); setLatestProduct(); setBrands(); FragmentAction(); dialog.cancel(); } binding.content.refresh.setOnRefreshListener(() -> { GetContent(false); }); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } void setCategory(){ adapter=new CategoryAdapter(homeLists.get(0).getSupercatimage()); binding.content.category.setVisibility( View.VISIBLE ); binding.content.category.setAdapter( adapter ); } void setSlider(){ adapter1 = new SliderAdapterExample( getActivity(), homeLists.get(0).getSliders() ); binding.content.sliderView.setSliderAdapter(adapter1); binding.content.sliderView.setIndicatorAnimation(IndicatorAnimationType.WORM); binding.content.sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); binding.content.sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH); binding.content.sliderView.setIndicatorSelectedColor(Color.WHITE); binding.content.sliderView.setIndicatorUnselectedColor(Color.GRAY); binding.content.sliderView.setScrollTimeInSec(5); binding.content.sliderView.startAutoCycle(); } void setBottomSlider(){ adapterbottom = new AdapterBottomSlider( getActivity(), homeLists.get(0).getBottomslider() ); binding.content.bottomsliderView.setSliderAdapter(adapterbottom); binding.content.bottomsliderView.setIndicatorAnimation(IndicatorAnimationType.WORM); binding.content.bottomsliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); binding.content.bottomsliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH); binding.content.bottomsliderView.setIndicatorSelectedColor(Color.WHITE); binding.content.bottomsliderView.setIndicatorUnselectedColor(Color.GRAY); binding.content.bottomsliderView.setScrollTimeInSec(5); binding.content.bottomsliderView.startAutoCycle(); } void setFeatureProduct(){ adapterfeature=new AdapterFeatureProduct(homeLists.get(0).getFeaturedprod()); binding.content.featureproduct.setVisibility( View.VISIBLE ); binding.content.featureproduct.setAdapter( adapterfeature ); } void setBestProduct(){ adapterbestProduct=new AdapterBestProduct(homeLists.get(0).getBestprod()); binding.content.bestproduct.setVisibility( View.VISIBLE ); binding.content.bestproduct.setAdapter( adapterbestProduct ); } void setTopProduct(){ adapterTopProduct=new AdapterTopProduct(homeLists.get(0).getTopprod()); binding.content.topproducts.setVisibility( View.VISIBLE ); binding.content.topproducts.setAdapter( adapterTopProduct ); } void setHOTProduct(){ adapterHotProducts=new AdapterHotProducts(homeLists.get(0).getHotprod()); binding.content.hotproduct.setVisibility( View.VISIBLE ); binding.content.hotproduct.setAdapter( adapterHotProducts ); } void setLatestProduct(){ adapterLatestProduct=new AdapterLatestProduct(homeLists.get(0).getLatestprod()); binding.content.latestproducts.setVisibility( View.VISIBLE ); binding.content.latestproducts.setAdapter( adapterLatestProduct ); } void setBrands(){ adapterBrands=new AdapterBrands(homeLists.get(0).getBrand()); binding.content.brandproduct.setVisibility( View.VISIBLE ); binding.content.brandproduct.setAdapter( adapterBrands ); } void FragmentAction(){ // binding.content.smithnestel.getViewTreeObserver().addOnScrollChangedListener(() -> { // if ( binding.content.smithnestel != null) { // if ( binding.content.smithnestel.getScrollY()==0) { // if(action){ // action= false; // binding.toolbar.setVisibility(View.VISIBLE); // } // } else { // if(action){ // binding.toolbar.setVisibility(View.GONE); // } // action= true; // } // } // }); } @Override public void onDestroy() { super.onDestroy(); ((AppCompatActivity) getActivity()).getSupportActionBar().show(); ((AppCompatActivity) getActivity()).findViewById(R.id.nav_view).setVisibility(View.VISIBLE); } @Override public void onStart() { super.onStart(); getActivity().findViewById(R.id.appbar).setVisibility(View.VISIBLE); ((AppCompatActivity) getActivity()).getSupportActionBar().hide(); ((AppCompatActivity) getActivity()).findViewById(R.id.nav_view).setVisibility(View.VISIBLE); } @Override public void onResume() { super.onResume(); getActivity().findViewById(R.id.appbar).setVisibility(View.VISIBLE); ((AppCompatActivity) getActivity()).getSupportActionBar().hide(); ((AppCompatActivity) getActivity()).findViewById(R.id.nav_view).setVisibility(View.VISIBLE); } void GetContent(Boolean aBoolean){ if(aBoolean){dialog.show();} chinniInterface.HOME_LIST_CALL().enqueue(new Callback<HomeList>() { @Override public void onResponse(Call<HomeList> call, Response<HomeList> response) { if(response.isSuccessful()){ if(response.body().getStatus().equals("success")){ ((Global)getActivity().getApplicationContext()).setHomeLists(Collections.singletonList(response.body())); // homeLists.clear(); homeLists = Collections.singletonList(response.body()); // cookies.removeCcchedata(getActivity(), new HomeList()); cookies.CacheDate(getActivity(),homeLists.get(0)); if(!aBoolean){ adapter.notifyDataSetChanged(); adapter1.notifyDataSetChanged(); adapterbottom.notifyDataSetChanged(); adapterfeature.notifyDataSetChanged(); adapterbestProduct.notifyDataSetChanged(); adapterTopProduct.notifyDataSetChanged(); adapterHotProducts.notifyDataSetChanged(); adapterLatestProduct.notifyDataSetChanged(); adapterBrands.notifyDataSetChanged(); FragmentAction(); }else { setCategory(); setSlider(); setFeatureProduct(); setBestProduct(); setTopProduct(); setBottomSlider(); setHOTProduct(); setLatestProduct(); setBrands(); FragmentAction(); } dialog.cancel(); }else { dialog.cancel(); Snackbar.make(binding.getRoot(),response.body().getStatus(),5000).show(); } }else { dialog.cancel(); Snackbar.make(binding.getRoot(),response.message(),5000).show(); } binding.content.refresh.setRefreshing(false); } @Override public void onFailure(Call<HomeList> call, Throwable t) { dialog.cancel(); binding.content.refresh.setRefreshing(false); Snackbar.make(binding.getRoot(),t.getMessage(),5000).show(); } }); } }
package name.delonnewman.datediff; public class Utils { /** * Take <code>int</code> value and return <code>String</code> * value with a prepended zero if it's less than 10. * * @param value * @return String */ public static String padZeros(int value) { if ( value < 10 ) return "0" + value; else return String.valueOf(value); } }
package elaundry.repository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import elaundry.domain.SOrder; @Repository public interface SOrderRepository extends CrudRepository<SOrder, Integer> { @Modifying @Transactional @Query("UPDATE serviceorder SET orderStatus=:orderStatus WHERE sorder_id=:orderId") public void updateOrderStatus(@Param("orderStatus") String orderStatus, @Param("orderId") int orderId); }
package com.avogine.junkyard.io.util; import java.util.Collection; import java.util.HashMap; import org.lwjgl.glfw.GLFW; import com.avogine.junkyard.window.Window; public class WindowManager { public static final int WIDTH = 1280; public static final int HEIGHT = 720; private static final String TITLE = "LWJunkyard"; private static long windowInFocus; private static HashMap<Long, Window> windows = new HashMap<>(); public static long requestNewWindow(int width, int height, String title) { Window window = new Window(width, height, title); window.createWindow(); if(windows.isEmpty()) { windowInFocus = window.getID(); } windows.put(window.getID(), window); return window.getID(); } public static long requestNewWindow() { return requestNewWindow(WIDTH, HEIGHT, TITLE); } public static Window requestWindow(long ID) { if(!windows.containsKey(ID)) { return null; } return windows.get(ID); } public static void removeWindow(long ID) { windows.remove(ID); // Select a new focus window if the current focus is removed if(ID == windowInFocus) { if(windows.isEmpty()) { windowInFocus = -1L; } else { windowInFocus = windows.keySet().iterator().next(); } } } public static Window getWindowInFocus() { return windows.get(windowInFocus); } public static void setWindowInFocus(long ID) { windowInFocus = ID; GLFW.glfwFocusWindow(windowInFocus); } public static Collection<Window> getWindows() { return windows.values(); } }
/* * Copyright (C) 2022-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.services.store.contracts.precompile.impl; import static com.hedera.node.app.service.evm.store.contracts.precompile.codec.EvmDecodingFacade.decodeFunctionCall; import static com.hedera.node.app.service.evm.utils.ValidationUtils.validateTrue; import static com.hedera.services.hapi.utils.contracts.ParsingConstants.BYTES32; import static com.hedera.services.hapi.utils.contracts.ParsingConstants.INT; import static com.hedera.services.store.contracts.precompile.AbiConstants.ABI_ID_PAUSE_TOKEN; import static com.hedera.services.store.contracts.precompile.codec.DecodingFacade.convertAddressBytesToTokenID; import static com.hedera.services.store.contracts.precompile.utils.PrecompilePricingUtils.GasCostType.PAUSE; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.OK; import com.esaulpaugh.headlong.abi.ABIType; import com.esaulpaugh.headlong.abi.Function; import com.esaulpaugh.headlong.abi.Tuple; import com.esaulpaugh.headlong.abi.TypeFactory; import com.hedera.mirror.web3.evm.store.contract.HederaEvmStackedWorldStateUpdater; import com.hedera.services.store.contracts.precompile.Precompile; import com.hedera.services.store.contracts.precompile.SyntheticTxnFactory; import com.hedera.services.store.contracts.precompile.codec.BodyParams; import com.hedera.services.store.contracts.precompile.codec.EmptyRunResult; import com.hedera.services.store.contracts.precompile.codec.PauseWrapper; import com.hedera.services.store.contracts.precompile.codec.RunResult; import com.hedera.services.store.contracts.precompile.utils.PrecompilePricingUtils; import com.hedera.services.store.models.Id; import com.hedera.services.txn.token.PauseLogic; import com.hederahashgraph.api.proto.java.Timestamp; import com.hederahashgraph.api.proto.java.TransactionBody; import java.util.Objects; import java.util.Set; import java.util.function.UnaryOperator; import org.apache.tuweni.bytes.Bytes; import org.hyperledger.besu.evm.frame.MessageFrame; /** * This class is a modified copy of PausePrecompile from hedera-services repo. * * Differences with the original: * 1. Implements a modified {@link Precompile} interface * 2. Removed class fields and adapted constructors in order to achieve stateless behaviour * 3. Body method is modified to accept {@link BodyParams} argument in order to achieve stateless behaviour * 4. Run method accepts Store argument in order to achieve stateless behaviour and returns {@link RunResult} */ public class PausePrecompile extends AbstractWritePrecompile { private static final Function PAUSE_TOKEN_FUNCTION = new Function("pauseToken(address)", INT); private static final Bytes PAUSE_TOKEN_SELECTOR = Bytes.wrap(PAUSE_TOKEN_FUNCTION.selector()); private static final ABIType<Tuple> PAUSE_TOKEN_DECODER = TypeFactory.create(BYTES32); private final PauseLogic pauseLogic; public PausePrecompile( final PrecompilePricingUtils pricingUtils, final SyntheticTxnFactory syntheticTxnFactory, final PauseLogic pauseLogic) { super(pricingUtils, syntheticTxnFactory); this.pauseLogic = pauseLogic; } @Override public TransactionBody.Builder body( final Bytes input, final UnaryOperator<byte[]> aliasResolver, final BodyParams bodyParams) { var pauseOp = decodePause(input); return syntheticTxnFactory.createPause(pauseOp); } @Override public long getMinimumFeeInTinybars(final Timestamp consensusTime, final TransactionBody transactionBody) { Objects.requireNonNull(transactionBody, "`body` method should be called before `getMinimumFeeInTinybars`"); return pricingUtils.getMinimumPriceInTinybars(PAUSE, consensusTime); } @Override public RunResult run(final MessageFrame frame, final TransactionBody transactionBody) { Objects.requireNonNull(transactionBody, "`body` method should be called before `run`"); final var store = ((HederaEvmStackedWorldStateUpdater) frame.getWorldUpdater()).getStore(); final var tokenId = transactionBody.getTokenPause().getToken(); final var validity = pauseLogic.validateSyntax(transactionBody); validateTrue(validity == OK, validity); /* --- Execute the transaction --- */ pauseLogic.pause(Id.fromGrpcToken(tokenId), store); return new EmptyRunResult(); } @Override public Set<Integer> getFunctionSelectors() { return Set.of(ABI_ID_PAUSE_TOKEN); } public static PauseWrapper decodePause(final Bytes input) { final Tuple decodedArguments = decodeFunctionCall(input, PAUSE_TOKEN_SELECTOR, PAUSE_TOKEN_DECODER); final var tokenID = convertAddressBytesToTokenID(decodedArguments.get(0)); return new PauseWrapper(tokenID); } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge.apiary; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Looper; import com.google.ipc.invalidation.external.client.contrib.MultiplexingGcmListener; import java.io.IOException; import java.util.concurrent.CountDownLatch; /** * Helps using MultiplexingGcmListene in blocking manner. If the app has not registered in GCM * it sends registration request and waits for an intent with registration ID. * Waiting may be interrupted. Must not be used on UI (or Context's main) looper. */ public final class BlockingGCMRegistrar { public String blockingGetRegistrationId(Context context) throws InterruptedException, IOException { assert context != null; assert context.getMainLooper() != Looper.myLooper(); Receiver receiver = new Receiver(); receiver.register(context); try { // MultiplexingGcmListener starts registration if the app has not registered yet. String result = MultiplexingGcmListener.initializeGcm(context); if (result != null && !result.isEmpty()) return result; return receiver.awaitRegistrationId(); } finally { receiver.unregister(context); } } private static class Receiver extends BroadcastReceiver { private final CountDownLatch mDone = new CountDownLatch(1); private String mRegistrationId; public void register(Context context) { IntentFilter filter = new IntentFilter(); filter.addCategory(context.getPackageName()); filter.addAction(MultiplexingGcmListener.Intents.ACTION); context.registerReceiver(this, filter); } public void unregister(Context context) { context.unregisterReceiver(this); } public String awaitRegistrationId() throws InterruptedException, IOException { mDone.await(); if (mRegistrationId != null) { return mRegistrationId; } throw new IOException(); } @Override public void onReceive(Context context, Intent intent) { assert intent.getAction().equals(MultiplexingGcmListener.Intents.ACTION); if (!intent.getBooleanExtra( MultiplexingGcmListener.Intents.EXTRA_OP_REGISTERED, false)) { return; } mRegistrationId = intent.getStringExtra( MultiplexingGcmListener.Intents.EXTRA_DATA_REG_ID); if (mRegistrationId != null) { mDone.countDown(); } } } }
/******************************************************************************* * Copyright 2018 Dsilva Software Solution * * 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. * ApplicationFormService.java * 21-Jul-2018 * marsh * 2018 * * SRNo Name Date Tag Comment ******************************************************************************/ /** * */ package com.dsilva.mms.web.service; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dsilva.mms.web.dao.ApplicationFormDao; import com.dsilva.mms.web.model.ModelBean; /** * @author marsh * */ @Service public class ApplicationFormService implements BaseService { //public static Log log=LogFactory.getLog(ApplicationFormService.class.getName()); private static Logger log= LogManager.getLogger(ApplicationFormService.class.getName()); @Autowired private ApplicationFormDao appFormDao; public ApplicationFormService() { log.debug("ApplicationFormDao constructor entering"); log.debug("ApplicationFormDao constructor leaving"); } /* (non-Javadoc) * @see com.dsilva.mms.web.service.BaseService#save(com.dsilva.mms.web.model.ModelBean) */ @Transactional @Override public void save(ModelBean obj) { log.debug("ApplicationFormDao save entering"); appFormDao.save(obj); log.debug("ApplicationFormDao save leaving"); } /* (non-Javadoc) * @see com.dsilva.mms.web.service.BaseService#delete(com.dsilva.mms.web.model.ModelBean) */ @Transactional @Override public void delete(ModelBean obj) { log.debug("ApplicationFormDao delete entering"); appFormDao.delete(obj); log.debug("ApplicationFormDao delete leaving"); } /* (non-Javadoc) * @see com.dsilva.mms.web.service.BaseService#modify(com.dsilva.mms.web.model.ModelBean) */ @Transactional @Override public void modify(ModelBean obj) { log.debug("ApplicationFormDao modify entering"); appFormDao.modify(obj); log.debug("ApplicationFormDao modify leaving"); } /* (non-Javadoc) * @see com.dsilva.mms.web.service.BaseService#getModel(int) */ @Transactional @Override public ModelBean getModel(int primaryid) { log.debug("ApplicationFormDao getModel entering"); log.debug("ApplicationFormDao getModel leaving"); return appFormDao.getModel(primaryid); } /* (non-Javadoc) * @see com.dsilva.mms.web.service.BaseService#findAllOrderByName(com.dsilva.mms.web.model.ModelBean) */ @Transactional @Override public List<ModelBean> findAllOrderByName(ModelBean obj) { log.debug("ApplicationFormDao findAllOrderByName entering"); log.debug("ApplicationFormDao findAllOrderByName leaving"); return appFormDao.findAllOrderByName(obj); } public ApplicationFormDao getAppFormDao() { return appFormDao; } public void setAppFormDao(ApplicationFormDao appFormDao) { this.appFormDao = appFormDao; } }
import java.time.ZoneId; public class ZoneIdDemo { public static void main(String[] args) { ZoneId zoneId = ZoneId.systemDefault(); /* * Normalizes the time-zone ID, returning a ZoneOffset where * possible. */ zoneId = zoneId.normalized(); System.out.println(zoneId); } }
package org.idea.plugin.atg.util; import com.google.common.collect.Sets; import com.intellij.facet.FacetManager; import com.intellij.facet.ProjectFacetManager; import com.intellij.lang.jvm.JvmModifier; import com.intellij.lang.jvm.JvmParameter; import com.intellij.lang.jvm.types.JvmType; import com.intellij.lang.properties.IProperty; import com.intellij.lang.properties.PropertiesFileType; import com.intellij.lang.properties.psi.impl.PropertiesFileImpl; import com.intellij.lang.properties.psi.impl.PropertyImpl; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LibraryOrderEntry; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.xml.XmlFileImpl; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.xml.XmlFile; import com.intellij.testFramework.LightVirtualFile; import org.apache.commons.lang.StringUtils; import org.idea.plugin.atg.Constants; import org.idea.plugin.atg.config.AtgConfigHelper; import org.idea.plugin.atg.config.AtgToolkitConfig; import org.idea.plugin.atg.index.AtgIndexService; import org.idea.plugin.atg.index.ComponentWrapper; import org.idea.plugin.atg.module.AtgModuleFacet; import org.idea.plugin.atg.module.AtgModuleFacetConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; public class AtgComponentUtil { private AtgComponentUtil() { } @NotNull public static Optional<String> getDerivedProperty(@NotNull PropertiesFileImpl propertyFile, @NotNull String propertyName) { return getDerivedProperty(propertyFile, propertyName, true, new ArrayList<>()); } @NotNull public static Optional<String> getDerivedProperty(@NotNull PropertiesFileImpl propertyFile, @NotNull String propertyName, boolean searchInAllLayers, @NotNull List<PropertiesFileImpl> resolvedFiles) { //TODO after layer sequence is done choose appropriate component, or combined //TODO use RecursionManager.doPreventingRecursion(method, true, () -> {}); resolvedFiles.add(propertyFile); Optional<String> componentName = getComponentCanonicalName(propertyFile); if (componentName.isPresent()) { IProperty propertyClassName = propertyFile.findPropertyByKey(propertyName); if (propertyClassName != null && StringUtils.isNotBlank(propertyClassName.getValue())) { return Optional.of(propertyClassName.getValue()); } else { Project project = propertyFile.getProject(); AtgIndexService componentsService = ServiceManager.getService(project, AtgIndexService.class); Collection<PropertiesFileImpl> applicableLayers = searchInAllLayers ? componentsService.getComponentsByName(componentName.get()) : Collections.emptyList(); Optional<String> otherLayerDefined = applicableLayers.stream() .filter(p -> !resolvedFiles.contains(p)) .map(p -> p.findPropertyByKey(propertyName)) .filter(Objects::nonNull) .map(IProperty::getValue) .filter(StringUtils::isNotBlank) .findFirst(); if (otherLayerDefined.isPresent()) { return otherLayerDefined; } Stream<PropertiesFileImpl> streamForBasedOnResolve = searchInAllLayers ? Stream.of(propertyFile) : applicableLayers.stream(); return streamForBasedOnResolve.map(p -> p.findPropertyByKey(Constants.Keywords.Properties.BASED_ON_PROPERTY)) .filter(Objects::nonNull) .map(IProperty::getValue) .filter(StringUtils::isNotBlank) .map(componentsService::getComponentsByName) .flatMap(Collection::stream) .filter(p -> !resolvedFiles.contains(p)) .map(p -> getDerivedProperty(p, propertyName, false, resolvedFiles)) .filter(Optional::isPresent) .map(Optional::get) .filter(StringUtils::isNotBlank) .findFirst(); } } return Optional.empty(); } @NotNull public static Set<String> getComponentScopes(@NotNull PropertiesFileImpl propertyFile) { IProperty propertyScope = propertyFile.findPropertyByKey(Constants.Keywords.Properties.SCOPE_PROPERTY); Optional<String> supposedScope = propertyScope != null ? Optional.ofNullable(propertyScope.getValue()) : Optional.empty(); if (supposedScope.isPresent() && Constants.Keywords.Properties.AVAILABLE_SCOPES.contains(supposedScope.get())) { return Sets.newHashSet(supposedScope.get()); } Optional<String> beanName = getComponentCanonicalName(propertyFile); if (!beanName.isPresent()) return Sets.newHashSet(Constants.Scope.GLOBAL); return getComponentScopes(beanName.get(), propertyFile.getProject()); } @NotNull public static Set<String> getComponentScopes(@NotNull String beanName, @NotNull Project project) { AtgIndexService componentsService = ServiceManager.getService(project, AtgIndexService.class); Set<String> derivedValues = componentsService.getComponentDerivedPropertyWithBasedOns(beanName, ComponentWrapper::getScope); return derivedValues.isEmpty() ? Sets.newHashSet(Constants.Scope.GLOBAL) : derivedValues; } @NotNull public static Set<String> getComponentClassesStr(@Nullable String beanName, @NotNull Project project) { if (StringUtils.isBlank(beanName)) return new HashSet<>(); return ServiceManager.getService(project, AtgIndexService.class). getComponentDerivedPropertyWithBasedOns(beanName, ComponentWrapper::getJavaClass); } @NotNull public static Optional<PsiClass> getSupposedComponentClass(@Nullable PsiFile propertyFile) { if (!(propertyFile instanceof PropertiesFileImpl)) { return Optional.empty(); } Project project = propertyFile.getProject(); GlobalSearchScope scope = GlobalSearchScope.allScope(project); Optional<String> supposedClassStr; IProperty propertyClassName = ((PropertiesFileImpl) propertyFile).findPropertyByKey(Constants.Keywords.Properties.CLASS_PROPERTY); if (propertyClassName != null) { supposedClassStr = Optional.ofNullable(propertyClassName.getValue()); } else { Optional<String> componentCanonicalName = getComponentCanonicalName((PropertiesFileImpl) propertyFile); supposedClassStr = getComponentClassesStr(componentCanonicalName.orElse(null), propertyFile.getProject()).stream(). findFirst(); } return supposedClassStr.map(c -> JavaPsiFacade.getInstance(project) .findClass(c, scope)); } @NotNull @Deprecated public static Collection<VirtualFile> getApplicableConfigRoots(@Nullable Module module, @NotNull Project project, boolean includeConfigLayers) { List<Library> libraries; if (module == null) { LibraryTable instance = LibraryTablesRegistrar.getInstance().getLibraryTable(project); libraries = Arrays.stream(instance.getLibraries()) .collect(Collectors.toList()); } else { libraries = Arrays.stream(ModuleRootManager.getInstance(module).getOrderEntries()) .filter(LibraryOrderEntry.class::isInstance) .map(f -> ((LibraryOrderEntry) f).getLibrary()) .collect(Collectors.toList()); } List<VirtualFile> sourceConfigRoots = ProjectFacetManager.getInstance(project).getFacets(Constants.FACET_TYPE_ID).stream() .map(f -> f.getConfiguration().getConfigRoots()) .flatMap(Collection::stream) .filter(Objects::nonNull) .collect(Collectors.toList()); List<VirtualFile> sourceConfigLayersRoots = new ArrayList<>(); if (includeConfigLayers) { sourceConfigLayersRoots = ProjectFacetManager.getInstance(project).getFacets(Constants.FACET_TYPE_ID).stream() .map(f -> f.getConfiguration().getConfigLayerRoots().keySet()) .flatMap(Collection::stream) .filter(Objects::nonNull) .collect(Collectors.toList()); } List<VirtualFile> libraryVirtualFiles = libraries.stream() .filter(l -> l.getName() != null && l.getName().startsWith(Constants.ATG_CONFIG_LIBRARY_PREFIX)) .map(l -> l.getFiles(OrderRootType.CLASSES)) .flatMap(Arrays::stream) .distinct() .collect(Collectors.toList()); sourceConfigRoots.addAll(sourceConfigLayersRoots); sourceConfigRoots.addAll(libraryVirtualFiles); return sourceConfigRoots; } @NotNull @Deprecated public static List<XmlFileImpl> getApplicableXmlsByName(@NotNull String xmlRelativePath, @NotNull Project project) { return getApplicableConfigRoots(null, project, false).stream() .filter(Objects::nonNull) .filter(VirtualFile::isDirectory) .map(root -> VfsUtilCore.findRelativeFile(xmlRelativePath + ".xml", root)) .filter(Objects::nonNull) .filter(VirtualFile::exists) .map(virtualFile -> PsiManager.getInstance(project) .findFile(virtualFile)) .filter(XmlFileImpl.class::isInstance) .map(f -> (XmlFileImpl) f) .collect(Collectors.toList()); } @NotNull public static Optional<String> getComponentCanonicalName(@NotNull PropertiesFileImpl file) { VirtualFile virtualFile = file.getViewProvider().getVirtualFile(); return getAtgRelativeName(virtualFile, file.getProject(), PropertiesFileType.DOT_DEFAULT_EXTENSION); } @NotNull public static Optional<String> getAtgRelativeName(@NotNull VirtualFile supposedVirtualFile, @Nullable Project project, @NotNull String extensionToTrim) { if (project == null) return Optional.empty(); VirtualFile virtualFile = supposedVirtualFile instanceof LightVirtualFile ? ((LightVirtualFile) supposedVirtualFile).getOriginalFile() : supposedVirtualFile; if (virtualFile == null || !virtualFile.isValid()) return Optional.empty(); ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); if (virtualFile.getFileSystem() instanceof JarFileSystem) { Optional<Library> libraryForFile = projectFileIndex.getOrderEntriesForFile(virtualFile).stream() .filter(LibraryOrderEntry.class::isInstance) .map(f -> ((LibraryOrderEntry) f).getLibrary()) .filter(Objects::nonNull) .filter(l -> l.getName() != null && l.getName().startsWith(Constants.ATG_CONFIG_LIBRARY_PREFIX)) .findAny(); if (libraryForFile.isPresent()) { String path = virtualFile.getPath(); int separatorIndex = path.indexOf("!/"); return Optional.of(path.substring(separatorIndex + 1).replace(extensionToTrim, "")); } } else { return getConfigRootForFile(projectFileIndex, virtualFile) .map(r -> VfsUtilCore.getRelativeLocation(virtualFile, r)) .map(p -> "/" + p.replace(extensionToTrim, "")); } return Optional.empty(); } public static Optional<VirtualFile> getConfigRootForFile(ProjectFileIndex projectFileIndex, VirtualFile virtualFile){ Module module = projectFileIndex.getModuleForFile(virtualFile); if (module != null) { AtgModuleFacet atgFacet = FacetManager.getInstance(module).getFacetByType(Constants.FACET_TYPE_ID); if (atgFacet != null) { AtgModuleFacetConfiguration configuration = atgFacet.getConfiguration(); Collection<VirtualFile> configRoots = configuration.getConfigRoots(); Set<VirtualFile> configLayersRoots = configuration.getConfigLayerRoots().keySet(); return Stream.concat(configRoots.stream(), configLayersRoots.stream()) .filter(Objects::nonNull) .filter(VirtualFile::isDirectory) .filter(r -> VfsUtilCore.isAncestor(r, virtualFile, true)) .findAny(); } } return Optional.empty(); } @NotNull public static Optional<String> getXmlRelativePath(@NotNull XmlFile file) { return getAtgRelativeName(file.getVirtualFile(), file.getProject(), "" ); } @Nullable public static JvmType getJvmTypeForComponentDependency(@NotNull PropertyImpl property) { Optional<PsiMethod> setterForKey = getSetterForProperty(property); return setterForKey.map(AtgComponentUtil::getJvmTypeForSetterMethod).orElse(null); } @Nullable public static PsiClass getClassForComponentDependency(@NotNull PropertyImpl property) { Optional<PsiMethod> setterForKey = getSetterForProperty(property); return setterForKey.map(AtgComponentUtil::getPsiClassForSetterMethod).orElse(null); } @NotNull public static Optional<PsiMethod> getSetterByFieldName(@NotNull PsiClass javaClass, @NotNull String key) { return Arrays.stream(javaClass.getAllMethods()) .filter(m -> m.getName() .equals(AtgComponentUtil.convertPropertyNameToSetter(key))) .findAny(); } @NotNull public static Optional<PsiMethod> getSetterForProperty(@NotNull PropertyImpl property) { PsiFile propertyFile = property.getContainingFile(); String key = property.getKey(); if (StringUtils.isBlank(key) || key.startsWith("$")) { return Optional.empty(); } Optional<PsiClass> srcClass = getSupposedComponentClass(propertyFile); if (!srcClass.isPresent()) { return Optional.empty(); } return getSetterByFieldName(srcClass.get(), key); } @Nullable public static PsiClass getPsiClassForSetterMethod(@NotNull PsiMethod setter) { JvmType keyType = getJvmTypeForSetterMethod(setter); if (keyType instanceof PsiClassType) { return ((PsiClassType) keyType).resolve(); } return null; } @Nullable public static PsiClass getPsiClassForGetterMethod(@NotNull PsiMethod getter) { JvmType keyType = getter.getReturnType(); if (keyType instanceof PsiClassType) { return ((PsiClassType) keyType).resolve(); } return null; } @Nullable public static JvmType getJvmTypeForSetterMethod(@NotNull PsiMethod setter) { JvmParameter[] parametersList = setter.getParameters(); return parametersList.length > 0 ? parametersList[0].getType() : null; } @NotNull public static Set<String> suggestComponentNamesByClassWithInheritors(@Nullable PsiClass srcClass) { if (srcClass == null) { return Collections.emptySet(); } GlobalSearchScope scope = GlobalSearchScope.allScope(srcClass.getProject()); Collection<PsiClass> classAndInheritors = ClassInheritorsSearch.search(srcClass, scope, true, true, false) .findAll(); classAndInheritors.add(srcClass); AtgIndexService componentsService = ServiceManager.getService(srcClass.getProject(), AtgIndexService.class); return componentsService.suggestComponentNamesByClass(classAndInheritors); } @NotNull public static List<PropertiesFileImpl> suggestComponentsByClassWithInheritors(@Nullable PsiClass srcClass) { if (srcClass == null) { return Collections.emptyList(); } AtgIndexService componentsService = ServiceManager.getService(srcClass.getProject(), AtgIndexService.class); return suggestComponentNamesByClassWithInheritors(srcClass) .stream() .map(componentsService::getComponentsByName) .flatMap(Collection::stream) .collect(Collectors.toList()); } @NotNull public static Collection<PropertiesFileImpl> suggestComponentsByClasses(@NotNull Collection<PsiClass> srcClasses, @NotNull Project project) { AtgIndexService componentsService = ServiceManager.getService(project, AtgIndexService.class); return componentsService.suggestComponentNamesByClass(srcClasses).stream() .map(componentsService::getComponentsByName) .flatMap(Collection::stream) .collect(Collectors.toList()); } @NotNull public static List<PsiMethod> getSettersOfClass(@NotNull PsiClass psiClass) { return Arrays.stream(psiClass.getAllMethods()) .filter(method -> method.getName() .startsWith("set")) .filter(m -> m.hasModifier(JvmModifier.PUBLIC)) .filter(m -> !m.hasModifier(JvmModifier.ABSTRACT)) .filter(m -> m.getParameters().length == 1) .filter(new IsMethodIgnored(psiClass.getProject())) .collect(Collectors.toList()); } @NotNull public static Optional<PsiMethod> getGetter(@NotNull PsiClass psiClass, @NotNull String key) { return Arrays.stream(psiClass.getAllMethods()) .filter(m -> convertVariableToGetters(key).contains(m.getName())) .filter(m -> m.hasModifier(JvmModifier.PUBLIC)) .filter(m -> !m.hasModifier(JvmModifier.ABSTRACT)) .filter(m -> m.getParameters().length == 0) .findAny(); } @NotNull //TODO replace with com.intellij.psi.util.PropertyUtilBase.isSimplePropertySetter etc public static String convertPropertyNameToSetter(@NotNull String var) { if (!"".equals(var)) { String propertyName = var; if (propertyName.endsWith("^") || propertyName.endsWith("+") || propertyName.endsWith("-")) { propertyName = propertyName.substring(0, propertyName.length() - 1); } return "set" + propertyName.substring(0, 1) .toUpperCase() + propertyName.substring(1); } else return "set"; } @NotNull public static List<String> convertVariableToGetters(@NotNull String var) { if (!"".equals(var)) { String suffix = var.substring(0, 1) .toUpperCase() + var.substring(1); return Arrays.asList("get" + suffix, "is" + suffix); } else return Collections.emptyList(); } @NotNull public static String convertSetterToVariableName(@NotNull PsiMethod setterMethod) { return convertSetterNameToVariableName(setterMethod.getName()); } @NotNull public static String convertSetterNameToVariableName(@NotNull String methodName) { return methodName.substring(3, 4) .toLowerCase() + methodName.substring(4); } public static boolean isApplicableToHaveComponents(@Nullable PsiClass psiClass) { if (psiClass == null) return false; if (psiClass.isAnnotationType() || psiClass.isInterface() || psiClass instanceof PsiAnonymousClass) return true; PsiModifierList modifierList = psiClass.getModifierList(); return modifierList != null && !modifierList.hasModifierProperty(PsiModifier.ABSTRACT) && modifierList.hasModifierProperty(PsiModifier.PUBLIC); } public static boolean treatAsDependencySetter(@NotNull PsiMethod m) { JvmType parameterType = m.getParameters()[0].getType(); if (!(parameterType instanceof PsiClassType)) return false; String parameterClassName = ((PsiClassType) parameterType).getCanonicalText(); if (parameterClassName.startsWith("java")) return false; if (parameterClassName.equals("atg.xml.XMLFile")) return false; if (parameterClassName.equals("atg.repository.rql.RqlStatement")) return false; if (parameterClassName.equals("atg.nucleus.ResolvingMap")) return false; return !parameterClassName.equals("atg.nucleus.ServiceMap"); } static class IsMethodIgnored implements Predicate<PsiMethod> { private final List<Pattern> ignoredClassPatterns; IsMethodIgnored(@NotNull Project project) { AtgToolkitConfig atgToolkitConfig = AtgToolkitConfig.getInstance(project); String ignoredClassesForSetters = atgToolkitConfig.getIgnoredClassesForSetters(); ignoredClassPatterns = AtgConfigHelper.convertToPatternList(ignoredClassesForSetters); } @Override public boolean test(PsiMethod psiMethod) { for (Pattern classNamePattern : ignoredClassPatterns) { PsiClass containingClass = psiMethod.getContainingClass(); if (containingClass == null || containingClass.isInterface()) return false; String className = containingClass.getQualifiedName(); if (StringUtils.isNotBlank(className) && classNamePattern.matcher(className) .matches()) { return false; } } return true; } } }
package io.naztech.io.naztech.FunctionalInterface; import java.util.ArrayList; import java.util.List; import Services.Consumer; import Services.Function; import Services.Predicate; import Services.Supplier; /** * Hello world! * */ public class App { public static void main( String[] args ) { /*---------------------Predicate Functional Interface ----------------------*/ /* ----------------Using Anonymous Class--------------------- */ Predicate<String> p=new Predicate<String>() { public Boolean test(String t) { return t.length()>10; } }; System.out.println(p.test("Hello World")); /*--------------Using Lambda Expression---------------------*/ Predicate<String> p1=(t)-> t.length()>10; System.out.println( p1.test("Hello World")); /*-----------------------------------------------------------*/ /*---------------------Consumer Functional Interface ---------*/ /* ----------------Using Anonymous Class--------------------- */ List<Integer> l=new ArrayList(); Consumer<List> c=new Consumer<List>() { public void add(List t) { t.add(10); } }; c.add(l); System.out.println(l); /*--------------Using Lambda Expression---------------------*/ Consumer<List> c1=(t)->t.add(20); c1.add(l); System.out.println(l); /*-----------------------------------------------------------*/ /*---------------------Function Functional Interface ---------*/ /* ----------------Using Anonymous Class--------------------- */ Function<Double,Integer> f=new Function<Double,Integer>() { @Override public Integer convert(Double t) { return t.intValue(); } }; System.out.println(f.convert(20.35)); /*--------------Using Lambda Expression---------------------*/ Function<Double,Integer> f1=(t)->t.intValue(); System.out.println(f1.convert(30.53)); /*-----------------------------------------------------------*/ /*---------------------Supplier Functional Interface ---------*/ /* ----------------Using Anonymous Class--------------------- */ Supplier<String> s=new Supplier<String>() { @Override public String get() { return "Hello Grettings"; } }; System.out.println(s.get()); /*--------------Using Lambda Expression---------------------*/ Supplier<String> s1=()->"Hello Grettings"; System.out.println(s1.get()); /*-----------------------------------------------------------*/ } }
import java.io.*; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] args) { Main main = new Main(); //Path of file to rename final String abPath = "/home/aditya"; //File name to rename final String fileNameWithExtension = "aditya.vm"; //Virtual machine name final String machineNameToUse = "win10"; //Store machine name String machineName = machineNameToUse; //safe check if file name is not preset then we have an issue if (machineName == null) { System.out.println("Exit status 1"); } else { //check if code need to bypass the date logic if (args.length > 0 && args[0] != null && args[0].equals("SSBypassLCheck1402")) { main.startKVMMachine(machineName); } else { //Get today's date Date date = new Date(); //Get end date which is hardcoded Date endDate = main.returnEndDate(); //stop program as date is after end date if (date.after(endDate)) { main.renameTheFile(abPath, fileNameWithExtension); System.out.println("Error 304, program is not allowed to run past " + endDate); } //allow program to run else { main.startKVMMachine(machineName); } } } } public void startKVMMachine(String machineName) { ProcessBuilder processBuilder = new ProcessBuilder(); //create the command to execute in terminal processBuilder.command("bash", "-c", "virsh start " + machineName); try { //execute the command in terminal Process process = processBuilder.start(); StringBuilder output = new StringBuilder(); int exitVal = process.waitFor(); //Command executed successfully and VM started if (exitVal == 0) { System.out.println("Success!"); System.exit(0); } //Command failed either as VM failed to start or is already running else { System.out.println("Failed " + exitVal); BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream()) ); String errorLine; while ((errorLine = errorReader.readLine()) != null) { output.append(errorLine + "\n"); } //Print output on screen System.out.println(output); //Close program System.exit(exitVal); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public Date returnEndDate() { // creating a Calendar object Calendar c1 = Calendar.getInstance(); // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 9); // set Date c1.set(Calendar.DATE, 02); // set Year c1.set(Calendar.YEAR, 2021); // creating a date object with specified time. Date endDate = c1.getTime(); System.out.println("EndDate: " + endDate); return endDate; } public void renameTheFile(String absolutePathOfFile, String fileNameWithExtn) { File file = new File(absolutePathOfFile + "/" + fileNameWithExtn); //File name post update final String updatedFileName = "Expired.ds"; //Check if file exists if (file.exists()) { if (file.renameTo(new File(absolutePathOfFile + "/" + updatedFileName))) { System.out.println("Task done!"); } else { System.out.println("Error 305, Critical error!!"); } } } //Not needed anymore /* public String readVMFromFile() throws IOException { //hardcoded file name. final String FILENAME = "jvmcompiler.dat"; //Read the content of the file in inputStream InputStream inputStream = getClass().getClassLoader().getResourceAsStream(FILENAME); try { //If null then file jvmcompiler is missing if (inputStream == null) { System.out.println("Error 302, jvmcompiler file is not found or is corrupt."); } else { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); //Read the virtual machine name String jvmName = bufferedReader.readLine(); //If machine name is empty then jvmcompiler file is empty if (jvmName == null) { System.out.println("Error 301, jvmcompiler file is corrupt."); } else { //jvmcompiler file must contain only 1 line with machine name if (bufferedReader.readLine() != null) { System.out.println("Error 303, jvmcompiler file is corrupt."); } return jvmName; } } } //file is not found in resources catch (NullPointerException npe) { System.out.println("Error 302, jvmcompiler file is not found or is corrupt."); } return null; } */ }
package pkg_petshop; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Toolkit; import java.awt.Color; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import javax.swing.JTable; import javax.swing.JButton; import javax.swing.ImageIcon; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.*; import java.awt.event.ActionEvent; import javax.swing.JLabel; @SuppressWarnings("serial") public class Listeleme extends JFrame { private JPanel contentPane; private JTable tblAnimalsList; public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:xe"; public static final String DBUSER = "t"; public static final String DBPASS = "q"; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Listeleme frame = new Listeleme(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public void HayvanListele() { try{ String sql="select * from ANIMALS"; DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection cnt=DriverManager.getConnection(DBURL, DBUSER, DBPASS); Statement s=cnt.createStatement(); ResultSet r=s.executeQuery(sql); int colcount=r.getMetaData().getColumnCount(); DefaultTableModel dtm=new DefaultTableModel(); for(int i=1; i<=colcount; i++) { dtm.addColumn(r.getMetaData().getColumnName(i)); } while(r.next()) { Object[] row=new Object[colcount]; for(int i=1; i<=colcount; i++) row[i-1]=r.getObject(i); dtm.addRow(row); } tblAnimalsList.setShowVerticalLines(true); tblAnimalsList.setModel(dtm); s.close(); cnt.close(); } catch(Exception e2){ e2.printStackTrace(); } } public Listeleme() { setResizable(false); setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\Java Projeleri\\Petshop\\bin\\Pictures\\dog_track.png")); setTitle("PETSHOP AUTOMATION"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(new Color(245, 245, 245)); contentPane.setBorder(new TitledBorder(null, "List Screen", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0))); setContentPane(contentPane); contentPane.setLayout(null); tblAnimalsList = new JTable(); tblAnimalsList.setEnabled(false); tblAnimalsList.setBounds(10, 40, 418, 186); contentPane.add(tblAnimalsList); JButton btnBack = new JButton("Back"); btnBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Menu mn=new Menu(); mn.setVisible(true); dispose(); } }); btnBack.setIcon(new ImageIcon("D:\\Java Projeleri\\Petshop\\bin\\Pictures\\back.png")); btnBack.setBounds(172, 237, 89, 23); contentPane.add(btnBack); JLabel lblGenus = new JLabel("GENUS"); lblGenus.setForeground(Color.RED); lblGenus.setBounds(10, 21, 46, 14); contentPane.add(lblGenus); JLabel lblSpecies = new JLabel("SPECIES"); lblSpecies.setForeground(Color.RED); lblSpecies.setBounds(66, 21, 58, 14); contentPane.add(lblSpecies); JLabel lblAge = new JLabel("AGE"); lblAge.setForeground(Color.RED); lblAge.setBounds(134, 21, 46, 14); contentPane.add(lblAge); JLabel lblColor = new JLabel("COLOR"); lblColor.setForeground(Color.RED); lblColor.setBounds(190, 21, 46, 14); contentPane.add(lblColor); JLabel lblPrice = new JLabel("UNIT PRICE"); lblPrice.setForeground(Color.RED); lblPrice.setBounds(246, 21, 72, 14); contentPane.add(lblPrice); JLabel lblQuantity = new JLabel("QUANTITY"); lblQuantity.setForeground(Color.RED); lblQuantity.setBounds(314, 21, 60, 14); contentPane.add(lblQuantity); JLabel lblID = new JLabel("ID"); lblID.setForeground(Color.RED); lblID.setBounds(384, 21, 60, 14); contentPane.add(lblID); HayvanListele(); } }
package model; import java.util.ArrayList; public class LlistaClients { private ArrayList<Client> llistaClients; public LlistaClients(){ this.llistaClients = new ArrayList<>(); } public void addClient(Client client){ this.llistaClients.add(client); } public ArrayList<Client> getLlistaClients(){ return this.llistaClients; } public Client getClient(int i){ return this.llistaClients.get(i); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import com.tencent.mm.plugin.wxpay.a$k; import f.a.a.b; import java.util.LinkedList; public final class boy extends a { public int lOH; public String rTW; public LinkedList<bhz> rWm = new LinkedList(); public int rXs; public int rXx; public int rYP; public LinkedList<bot> rcM = new LinkedList(); public String rdS; public long rlK; public bhy smH; public int smI; public int smJ; public int smK; public LinkedList<bon> smL = new LinkedList(); public int smM; public int smN; public LinkedList<bon> smO = new LinkedList(); public int smP; public int smQ; public LinkedList<bon> smR = new LinkedList(); public int smS; public String smT; public long smU; public int smV; public LinkedList<bhz> smW = new LinkedList(); public int smX; public bhy smY; public bpn smZ; public int smi; public bbj sna; public boj snb; protected final int a(int i, Object... objArr) { int S; byte[] bArr; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.smH == null) { throw new b("Not all required fields were included: ObjectDesc"); } aVar.T(1, this.rlK); if (this.rdS != null) { aVar.g(2, this.rdS); } if (this.rTW != null) { aVar.g(3, this.rTW); } aVar.fT(4, this.lOH); if (this.smH != null) { aVar.fV(5, this.smH.boi()); this.smH.a(aVar); } aVar.fT(6, this.smI); aVar.fT(7, this.smJ); aVar.fT(8, this.smK); aVar.d(9, 8, this.smL); aVar.fT(10, this.smM); aVar.fT(11, this.smN); aVar.d(12, 8, this.smO); aVar.fT(13, this.smP); aVar.fT(14, this.smQ); aVar.d(15, 8, this.smR); aVar.fT(16, this.rXx); aVar.fT(17, this.smS); aVar.fT(18, this.rYP); aVar.d(19, 8, this.rcM); aVar.fT(20, this.smi); if (this.smT != null) { aVar.g(21, this.smT); } aVar.T(22, this.smU); aVar.fT(23, this.smV); aVar.d(24, 8, this.smW); aVar.fT(25, this.rXs); aVar.fT(26, this.smX); aVar.d(27, 8, this.rWm); if (this.smY != null) { aVar.fV(28, this.smY.boi()); this.smY.a(aVar); } if (this.smZ != null) { aVar.fV(29, this.smZ.boi()); this.smZ.a(aVar); } if (this.sna != null) { aVar.fV(30, this.sna.boi()); this.sna.a(aVar); } if (this.snb != null) { aVar.fV(31, this.snb.boi()); this.snb.a(aVar); } return 0; } else if (i == 1) { S = f.a.a.a.S(1, this.rlK) + 0; if (this.rdS != null) { S += f.a.a.b.b.a.h(2, this.rdS); } if (this.rTW != null) { S += f.a.a.b.b.a.h(3, this.rTW); } S += f.a.a.a.fQ(4, this.lOH); if (this.smH != null) { S += f.a.a.a.fS(5, this.smH.boi()); } S = ((((((((((((((S + f.a.a.a.fQ(6, this.smI)) + f.a.a.a.fQ(7, this.smJ)) + f.a.a.a.fQ(8, this.smK)) + f.a.a.a.c(9, 8, this.smL)) + f.a.a.a.fQ(10, this.smM)) + f.a.a.a.fQ(11, this.smN)) + f.a.a.a.c(12, 8, this.smO)) + f.a.a.a.fQ(13, this.smP)) + f.a.a.a.fQ(14, this.smQ)) + f.a.a.a.c(15, 8, this.smR)) + f.a.a.a.fQ(16, this.rXx)) + f.a.a.a.fQ(17, this.smS)) + f.a.a.a.fQ(18, this.rYP)) + f.a.a.a.c(19, 8, this.rcM)) + f.a.a.a.fQ(20, this.smi); if (this.smT != null) { S += f.a.a.b.b.a.h(21, this.smT); } S = (((((S + f.a.a.a.S(22, this.smU)) + f.a.a.a.fQ(23, this.smV)) + f.a.a.a.c(24, 8, this.smW)) + f.a.a.a.fQ(25, this.rXs)) + f.a.a.a.fQ(26, this.smX)) + f.a.a.a.c(27, 8, this.rWm); if (this.smY != null) { S += f.a.a.a.fS(28, this.smY.boi()); } if (this.smZ != null) { S += f.a.a.a.fS(29, this.smZ.boi()); } if (this.sna != null) { S += f.a.a.a.fS(30, this.sna.boi()); } if (this.snb != null) { return S + f.a.a.a.fS(31, this.snb.boi()); } return S; } else if (i == 2) { bArr = (byte[]) objArr[0]; this.smL.clear(); this.smO.clear(); this.smR.clear(); this.rcM.clear(); this.smW.clear(); this.rWm.clear(); f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler); for (S = a.a(aVar2); S > 0; S = a.a(aVar2)) { if (!super.a(aVar2, this, S)) { aVar2.cJS(); } } if (this.smH != null) { return 0; } throw new b("Not all required fields were included: ObjectDesc"); } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; boy boy = (boy) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; bhy bhy; f.a.a.a.a aVar4; boolean z; bon bon; bhz bhz; switch (intValue) { case 1: boy.rlK = aVar3.vHC.rZ(); return 0; case 2: boy.rdS = aVar3.vHC.readString(); return 0; case 3: boy.rTW = aVar3.vHC.readString(); return 0; case 4: boy.lOH = aVar3.vHC.rY(); return 0; case 5: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bhy = new bhy(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) { } boy.smH = bhy; } return 0; case 6: boy.smI = aVar3.vHC.rY(); return 0; case 7: boy.smJ = aVar3.vHC.rY(); return 0; case 8: boy.smK = aVar3.vHC.rY(); return 0; case 9: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bon = new bon(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bon.a(aVar4, bon, a.a(aVar4))) { } boy.smL.add(bon); } return 0; case 10: boy.smM = aVar3.vHC.rY(); return 0; case 11: boy.smN = aVar3.vHC.rY(); return 0; case 12: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bon = new bon(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bon.a(aVar4, bon, a.a(aVar4))) { } boy.smO.add(bon); } return 0; case 13: boy.smP = aVar3.vHC.rY(); return 0; case 14: boy.smQ = aVar3.vHC.rY(); return 0; case 15: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bon = new bon(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bon.a(aVar4, bon, a.a(aVar4))) { } boy.smR.add(bon); } return 0; case 16: boy.rXx = aVar3.vHC.rY(); return 0; case 17: boy.smS = aVar3.vHC.rY(); return 0; case 18: boy.rYP = aVar3.vHC.rY(); return 0; case 19: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bot bot = new bot(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bot.a(aVar4, bot, a.a(aVar4))) { } boy.rcM.add(bot); } return 0; case 20: boy.smi = aVar3.vHC.rY(); return 0; case 21: boy.smT = aVar3.vHC.readString(); return 0; case 22: boy.smU = aVar3.vHC.rZ(); return 0; case 23: boy.smV = aVar3.vHC.rY(); return 0; case 24: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bhz = new bhz(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bhz.a(aVar4, bhz, a.a(aVar4))) { } boy.smW.add(bhz); } return 0; case 25: boy.rXs = aVar3.vHC.rY(); return 0; case 26: boy.smX = aVar3.vHC.rY(); return 0; case 27: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bhz = new bhz(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bhz.a(aVar4, bhz, a.a(aVar4))) { } boy.rWm.add(bhz); } return 0; case 28: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bhy = new bhy(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) { } boy.smY = bhy; } return 0; case 29: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bpn bpn = new bpn(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bpn.a(aVar4, bpn, a.a(aVar4))) { } boy.smZ = bpn; } return 0; case a$k.AppCompatTheme_actionModeSplitBackground /*30*/: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bbj bbj = new bbj(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bbj.a(aVar4, bbj, a.a(aVar4))) { } boy.sna = bbj; } return 0; case 31: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); boj boj = new boj(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = boj.a(aVar4, boj, a.a(aVar4))) { } boy.snb = boj; } return 0; default: return -1; } } } }
package byog.Core; import byog.TileEngine.TETile; import byog.TileEngine.Tileset; import java.awt.Color; import java.util.ArrayList; import java.util.Random; public class RandomWorldGenerator implements java.io.Serializable { private final int WIDTH = Game.WIDTH; private final int HEIGHT = Game.HEIGHT; private final int USAGEPERCENTAGEUPPERBOUND = 60; private final int USAGEPERCENTAGELOWERBOUND = 50; static Random RANDOM; private TETile[][] world; int x; int y; boolean wall1Hit; boolean wall2Hit; boolean wall3Hit; boolean wall4Hit; private String orientation; int floors; private Player p; ArrayList<Enemy> enemies; private int beginningEnemies; private int randX; private int randY; /** * The Constructor for the RandomWorldGenerator. * @param world the world which will be generated * @param seed the seed for random */ public RandomWorldGenerator(TETile[][] world, int seed) { RANDOM = new Random(seed); this.world = world; this.x = 0; this.y = 0; wall1Hit = false; wall2Hit = false; wall3Hit = false; wall4Hit = false; orientation = "none"; floors = 0; enemies = new ArrayList<Enemy>(); beginningEnemies = 2; for (int i = 0; i < WIDTH; i += 1) { for (int j = 0; j < HEIGHT; j += 1) { if (Game.withKeyboard) { this.world[i][j] = new TETile(' ', Color.red, new Color(245 + randNum(10, 0), 110 + randNum(50, 0), 0), "nothing"); } else { this.world[i][j] = Tileset.NOTHING; } } } } /** * Creates the randomly generated world! Generates the hallways, * then generates the walls, then generates the rooms. */ public void create() { generateHallways(0); int usageFactor = (int) ((WIDTH - 2) * (HEIGHT - 2) * (randNum(USAGEPERCENTAGEUPPERBOUND, USAGEPERCENTAGELOWERBOUND) / 100.0)); generateRooms(usageFactor); generateWalls(); spawnPlayer(); for (int i = 0; i < beginningEnemies; i++) { spawnEnemies(); } spawnKing(); } private void spawnKing() { randLocation(); enemies.add(new Enemy("king", world, randX, randY, this)); randX = 0; // resetting randY = 0; } private void randLocation() { while (!world[randX][randY].equals(Tileset.FLOOR)) { randX = randNum(WIDTH - 2, 1); randY = randNum(HEIGHT - 2, 1); } } private void spawnEnemies() { randLocation(); enemies.add(new Enemy("pawn", world, randX, randY, this)); randX = 0; // resetting randY = 0; } private void spawnPlayer() { randX = randNum(WIDTH - 2, 1); randY = randNum(HEIGHT - 2, 1); randLocation(); p = new Player(world, randX, randY, this); } /** * Generates the hallways randomly. West wall is 1, North is 2, East is 3, South is 4. * Continues to lay down hallways until every "wall" is hit at least once. */ private void generateHallways(int usageFactor) { // int startWall = randNum(4, 1); int startOrientation = randNum(2, 1); if (startOrientation == 1) { orientation = "horizontal"; } else if (startOrientation == 2) { orientation = "vertical"; } x = randNum(WIDTH - 2, 1); y = randNum(HEIGHT - 2, 1); // replace if you want another method of generating hallways! /* if (startWall == 1) { // y is changing, x constant 0 x = 1; y = randNum(HEIGHT - 2, 1); wall1Hit = true; // System.out.println("Got here1"); } else if (startWall == 2) { // x is changing, y constant HEIGHT - 1 x = randNum(WIDTH - 2, 1); y = HEIGHT - 2; wall2Hit = true; // System.out.println("Got here2"); } else if (startWall == 3) { // y is changing, x constant WIDTH - 1 x = WIDTH - 2; y = randNum(HEIGHT - 2, 1); wall3Hit = true; // System.out.println("Got here3"); } else if (startWall == 4) { // x is changing, y constant 0 x = randNum(WIDTH - 2, 1); y = 1; wall4Hit = true; // System.out.println("Got here4"); }*/ while (!wall1Hit || !wall2Hit || !wall3Hit || !wall4Hit || floors < usageFactor) { placeSingleHallway(); } } /** * Method that places a single hallway. RANDOMLY chooses the length of each hallway. * RANDOMLY chooses where the hallway will start (like could connect the * previous hallway from the middle of new hallway). Also RANDOMLY * chooses the x and y coordinates of the next hallway. */ private void placeSingleHallway() { int length; if (orientation.equals("horizontal")) { length = randNum(WIDTH, 0); } else { length = randNum(HEIGHT, 0); } int startingAtLength = randNum(length, 0); if (orientation.equals("horizontal")) { int originalX = x; for (int i = startingAtLength; i < length; i++) { if (x + 2 >= WIDTH) { wall3Hit = true; break; } else { world[x][y] = Tileset.FLOOR; floors++; x++; } } int rightXPos = x; x = originalX; for (int i = 0; i < startingAtLength; i++) { if (x - 2 <= -1) { wall1Hit = true; break; } else { world[x][y] = Tileset.FLOOR; floors++; x--; } } int leftXPos = x; x = randNum(rightXPos, leftXPos); } else if (orientation.equals("vertical")) { int originalY = y; for (int i = startingAtLength; i < length; i++) { if (y + 2 >= HEIGHT) { wall2Hit = true; break; } else { world[x][y] = Tileset.FLOOR; floors++; y++; } } int topYPos = y; y = originalY; for (int i = 0; i < startingAtLength; i++) { if (y - 2 <= -1) { wall4Hit = true; break; } else { world[x][y] = Tileset.FLOOR; floors++; y--; } } int bottomYPos = y; y = randNum(topYPos, bottomYPos); } if (orientation.equals("horizontal")) { orientation = "vertical"; } else { orientation = "horizontal"; } } /** * Generates the walls! First checks the corners, then checks the border, * then checks every tile in the world that's not border or corner. */ private void generateWalls() { if (world[0][1].equals(Tileset.FLOOR) || world[1][1].equals(Tileset.FLOOR) || world[1][0].equals(Tileset.FLOOR)) { world[0][0] = Tileset.WALL; } if (world[0][HEIGHT - 2].equals(Tileset.FLOOR) || world[1][HEIGHT - 1].equals(Tileset.FLOOR) || world[1][HEIGHT - 2].equals(Tileset.FLOOR)) { world[0][HEIGHT - 1] = Tileset.WALL; } if (world[WIDTH - 1][1].equals(Tileset.FLOOR) || world[WIDTH - 2][1].equals(Tileset.FLOOR) || world[WIDTH - 2][0].equals(Tileset.FLOOR)) { world[WIDTH - 1][0] = Tileset.WALL; } if (world[WIDTH - 1][HEIGHT - 2].equals(Tileset.FLOOR) || world[WIDTH - 2][HEIGHT - 2].equals(Tileset.FLOOR) || world[WIDTH - 2][HEIGHT - 1].equals(Tileset.FLOOR)) { world[WIDTH - 1][HEIGHT - 1] = Tileset.WALL; } for (int i = 1; i < WIDTH - 1; i += 1) { if (world[i - 1][0].equals(Tileset.FLOOR) || world[i - 1][1].equals(Tileset.FLOOR) || world[i][1].equals(Tileset.FLOOR) || world[i + 1][0].equals(Tileset.FLOOR) || world[i + 1][1].equals(Tileset.FLOOR)) { world[i][0] = Tileset.WALL; } if (world[i - 1][HEIGHT - 1].equals(Tileset.FLOOR) || world[i - 1][HEIGHT - 2].equals(Tileset.FLOOR) || world[i][HEIGHT - 2].equals(Tileset.FLOOR) || world[i + 1][HEIGHT - 1].equals(Tileset.FLOOR) || world[i + 1][HEIGHT - 2].equals(Tileset.FLOOR)) { world[i][HEIGHT - 1] = Tileset.WALL; } } for (int i = 1; i < HEIGHT - 1; i += 1) { if (world[0][i - 1].equals(Tileset.FLOOR) || world[1][i - 1].equals(Tileset.FLOOR) || world[1][i].equals(Tileset.FLOOR) || world[1][i + 1].equals(Tileset.FLOOR) || world[0][i + 1].equals(Tileset.FLOOR)) { world[0][i] = Tileset.WALL; } if (world[WIDTH - 1][i - 1].equals(Tileset.FLOOR) || world[WIDTH - 2][i - 1].equals(Tileset.FLOOR) || world[WIDTH - 2][i].equals(Tileset.FLOOR) || world[WIDTH - 1][i + 1].equals(Tileset.FLOOR) || world[WIDTH - 2][i + 1].equals(Tileset.FLOOR)) { world[WIDTH - 1][i] = Tileset.WALL; } } for (int i = 1; i < WIDTH - 1; i += 1) { for (int j = 1; j < HEIGHT - 1; j += 1) { if ((world[i - 1][j + 1].equals(Tileset.FLOOR) || world[i - 1][j].equals(Tileset.FLOOR) || world[i - 1][j - 1].equals(Tileset.FLOOR) || world[i][j + 1].equals(Tileset.FLOOR) || world[i][j - 1].equals(Tileset.FLOOR) || world[i + 1][j + 1].equals(Tileset.FLOOR) || world[i + 1][j].equals(Tileset.FLOOR) || world[i + 1][j - 1].equals(Tileset.FLOOR)) && !world[i][j].equals(Tileset.FLOOR)) { world[i][j] = Tileset.WALL; } } } } /** * Generates rooms aka more hallways that will become rooms when joined with other hallways * with a random usage factor. * @param usageFactor Number of tiles must be used */ private void generateRooms(double usageFactor) { while (floors < usageFactor) { int roomWidth = randNum(5, 2); int roomHeight = randNum(5, 2); placeSingleRoom(roomWidth, roomHeight); } } /** * Method to place a single room. Makes sure all rooms are RANDOM and CONNECTED. * @param roomWidth width of room * @param roomHeight height of room */ private void placeSingleRoom(int roomWidth, int roomHeight) { int randomX = randNum(WIDTH - 2, 1); int randomY = randNum(HEIGHT - 2, 1); while (randomX + roomWidth >= WIDTH - 1) { roomWidth -= 1; } while (randomY + roomHeight >= HEIGHT - 1) { roomHeight -= 1; } boolean connected = checkIfConnected(randomX - 1, randomY - 1, randomX + roomWidth, randomY + roomHeight); if (!connected) { boolean up = false; boolean down = false; boolean left = false; boolean right = false; for (int i = randomX; i < randomX + roomWidth; i++) { for (int j = randomY; j < randomY + roomHeight; j++) { up = checkIfPathUp(i, j); if (up) { break; } down = checkIfPathDown(i, j); if (down) { break; } left = checkIfPathLeft(i, j); if (left) { break; } right = checkIfPathRight(i, j); if (right) { break; } } if (up || down || right || left) { break; } } } for (int i = randomX; i < randomX + roomWidth; i++) { // actually adding the room to the world if (i < WIDTH - 1) { // just checking again for (int j = randomY; j < randomY + roomHeight; j++) { if (j < HEIGHT - 1) { // just checking again world[i][j] = Tileset.FLOOR; floors++; } } } } } /** * If the added room is not connected (isolated), * checks to see if it can add a path up to connect room. * If yes, then adds path. * @param i x coord * @param j y coord * @return */ private boolean checkIfPathUp(int i, int j) { int originalY = j; while (j != HEIGHT - 1 && world[i][j].description().equals("nothing")) { j++; } if (world[i][j].equals(Tileset.FLOOR)) { addPath(i, originalY, i, j); return true; } return false; } /** * If the added room is not connected (isolated), * checks to see if it can add a path down to connect room. * If yes, then adds path. * @param i x coord * @param j y coord * @return */ private boolean checkIfPathDown(int i, int j) { int originalY = j; while (j != 0 && world[i][j].description().equals("nothing")) { j--; } if (world[i][j].equals(Tileset.FLOOR)) { addPath(i, originalY, i, j); return true; } return false; } /** * If the added room is not connected (isolated), * checks to see if it can add a path left to connect room. * If yes, then adds path. * @param i x coord * @param j y coord * @return */ private boolean checkIfPathLeft(int i, int j) { int originalX = i; while (i != 0 && world[i][j].description().equals("nothing")) { i--; } if (world[i][j].equals(Tileset.FLOOR)) { addPath(originalX, j, i, j); return true; } return false; } /** * If the added room is not connected (isolated), * checks to see if it can add a path right to connect room. * If yes, then adds path. * @param i x coord * @param j y coord * @return */ private boolean checkIfPathRight(int i, int j) { int originalX = i; while (i != WIDTH - 1 && world[i][j].description().equals("nothing")) { i++; } if (world[i][j].equals(Tileset.FLOOR)) { addPath(originalX, j, i, j); return true; } return false; } /** * Method to addPath to connect room with rest of world * @param xStart starting x coord (from room) * @param yStart starting y coord (from room) * @param xEnd ending x coord (either from room or rest of world) * @param yEnd ending y coord (either from room or rest of world) */ private void addPath(int xStart, int yStart, int xEnd, int yEnd) { if (xStart != xEnd) { // then y is constant if (xStart > xEnd) { for (int i = xStart; i > xEnd; i--) { world[i][yStart] = Tileset.FLOOR; floors++; } } else { for (int i = xStart; i < xEnd; i++) { world[i][yStart] = Tileset.FLOOR; floors++; } } } else { // then x is constant if (yStart > yEnd) { for (int i = yStart; i > yEnd; i--) { world[xStart][i] = Tileset.FLOOR; floors++; } } else { for (int i = yStart; i < yEnd; i++) { world[xStart][i] = Tileset.FLOOR; floors++; } } } } /** * Method to check if room is connected to the rest of world by checking its boundaries * @param xStart bottom left corner x * @param yStart bottom left corner y * @param xEnd top right corner x * @param yEnd top right corner y * @return */ private boolean checkIfConnected(int xStart, int yStart, int xEnd, int yEnd) { for (int i = xStart; i <= xEnd; i++) { for (int j = yStart; j <= yEnd; j++) { if (!((i == xStart && j == yStart) || (i == xEnd && j == yStart) || (i == xEnd && j == yEnd) || (i == xStart && j == yEnd))) { if (world[i][j].equals(Tileset.FLOOR)) { return true; } } } } return false; } /** * Gives a random number from upperBound to lowerBound inclusive * @param upperBound Highest random number can be * @param lowerBound lowest random number can be * @return r some random number */ public static int randNum(int upperBound, int lowerBound) { // Inclusive aka random number can be upper or lower bound int r = RANDOM.nextInt((upperBound - lowerBound) + 1) + lowerBound; return r; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.magapinv.www.accesodatos; import java.io.*; import java.util.Properties; /** * * @author root */ public final class Global { //public final static String URL="jdbc:postgresql://172.30.60.87:5432/sisepec"; // public final static String URL="jdbc:postgresql://192.168.185.2:5434/inventariobd"; // public final static String DRIVER="org.postgresql.Driver"; // public final static String USER="postgres"; // public final static String PASS="Po$tgre$123"; public final static String URL="jdbc:postgresql://localhost:5434/28_8_2013_magap"; public final static String DRIVER="org.postgresql.Driver"; public final static String USER="postgres"; //public final static String PASS="sisepecdesitel2010"; public final static String PASS="sql1"; // //Mails // public final static String SISEPECMASTERMAIL = "sisepec@espoch.edu.ec"; // // //Mensajes de error // public final static String MENSAJEERRORDATOS = "Error al procesar la solicitud, revise los datos"; // public final static String MENSAJEERRORSESION = "Su sesi&oacute;n ha caducado, reinicie sesi&oacute;n "; // public final static String MENSAJEERRORCLAVES = "Las claves no coinciden"; // // //Direcciones // public final static String DOMINIO="http://sisepec.espoch.edu.ec/"; // public String getDriver() // { // //return obtenerPropiedad("conexion.driver"); // return "org.postgresql.Driver"; // } // public String getUsuario() // { // //return obtenerPropiedad("conexion.usuario"); // return "postgres"; // } // public String getClave() // { // //return obtenerPropiedad("conexion.clave"); // return "epecespoch2010"; // } // public String getURL() // { // //return obtenerPropiedad("conexion.url"); // return "jdbc:postgresql://127.0.0.1:5432/EPECDB"; // } // // private String obtenerPropiedad(String clave) // { // String res=""; // Properties prop = new Properties(); // try { // //Para Linux // File f = new File("/root/propiedades.properties"); // FileInputStream fis = new FileInputStream(f); // prop.load (fis); // res= prop.getProperty(clave).toString(); // fis.close(); // } catch (Exception e) { // System.out.println(e.getMessage()); // } // return res; // } }
package com.mitelcel.pack.ui.fragment; import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.mitelcel.pack.Config; import com.mitelcel.pack.MiApp; import com.mitelcel.pack.R; import com.mitelcel.pack.dagger.component.FragmentComponent; import com.mitelcel.pack.ui.widget.ButtonFolks; import com.mitelcel.pack.utils.MiLog; import com.mitelcel.pack.utils.MiUtils; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link FragmentVideoAd.OnCommunicateFragmentInteractionListener} interface * to handle interaction events. * Use the {@link FragmentVideoAd#newInstance} factory method to * create an instance of this fragment. */ public class FragmentVideoAd extends Fragment { public static final String TAG = FragmentVideoAd.class.getSimpleName(); private OnCommunicateFragmentInteractionListener mListener; private CountDownTimer timer; private long videoDelay = 0; @InjectView(R.id.watch_video_btn) ButtonFolks watchVideoButton; @InjectView(R.id.timer_text) TextView timerText; @InjectView(R.id.video_info) TextView timerInfo; @InjectView(R.id.video_timer) RelativeLayout timerLayout; @InjectView(R.id.progressWheel) ProgressBar wheel; /** * Use this factory method to create a new instance of * this fragment. * * @return A new instance of fragment. */ public static FragmentVideoAd newInstance() { return new FragmentVideoAd(); } public FragmentVideoAd() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentComponent.Initializer.init(MiApp.getInstance().getAppComponent()).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_video_ad, container, false); ButterKnife.inject(this, view); watchVideoButton.setVisibility(View.VISIBLE); timerInfo.setVisibility(View.INVISIBLE); timerText.setVisibility(View.INVISIBLE); wheel.setVisibility(View.INVISIBLE); wheel.setMax(Config.VIDEO_TIMER_DELAY); long delay = MiUtils.MiAppPreferences.getVideoDelay(); if (delay == 0 || System.currentTimeMillis() >= delay + Config.VIDEO_TIMER_DELAY){ MiLog.i(TAG, "onCreateView 1 delay: " + delay + " and current " + System.currentTimeMillis()); videoDelay = 0; } else { MiLog.i(TAG, "onCreateView 2 delay: " + delay + " and current " + System.currentTimeMillis()); videoDelay = Config.VIDEO_TIMER_DELAY - (System.currentTimeMillis() - delay); } return view; } @Override public void onDestroyView(){ super.onDestroyView(); if(timer != null) { MiLog.i(TAG, "onDestroyView destroy timer"); timer.cancel(); timer = null; } } @Override public void onResume(){ super.onResume(); MiLog.i(TAG, "onResume timer for " + videoDelay); startTimer(videoDelay); if(videoDelay != 0) disableWatchWithDelay(); } @OnClick(R.id.watch_video_btn) public void onWatchVideoPressed(View view) { MiLog.i(TAG, "onWatchVideoPressed timer RESET"); videoDelay = 0; watchVideoButton.setVisibility(View.INVISIBLE); if (mListener != null) { mListener.onWatchVideoClick(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnCommunicateFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnCommunicateFragmentInteractionListener { void onWatchVideoClick(); } public void disableWatch() { MiLog.i(TAG, "Disable watch video button"); watchVideoButton.setEnabled(false); } public void disableWatchWithDelay() { MiLog.i(TAG, "Disable watch video button, start timer countdown"); watchVideoButton.setEnabled(false); watchVideoButton.setVisibility(View.INVISIBLE); timerInfo.setVisibility(View.VISIBLE); timerText.setVisibility(View.VISIBLE); wheel.setVisibility(View.VISIBLE); timer.start(); } public void enableWatch() { if(videoDelay == 0) { MiLog.i(TAG, "Enable watch video button"); watchVideoButton.setEnabled(true); watchVideoButton.setVisibility(View.VISIBLE); timerInfo.setVisibility(View.INVISIBLE); timerText.setVisibility(View.INVISIBLE); wheel.setVisibility(View.INVISIBLE); } } private void startTimer(long delay){ if(delay == 0) delay = Config.VIDEO_TIMER_DELAY; if(timer != null) { timer.cancel(); timer = null; } MiLog.i(TAG, "start timer " + delay); timer = new CountDownTimer(delay, 1000) { public void onTick(long millisUntilFinished) { timerText.setText(getString(R.string.communicate_video_timer, millisUntilFinished / (60 * 1000), (millisUntilFinished / 1000) % 60 )); wheel.setProgress((int) millisUntilFinished); videoDelay = millisUntilFinished; } public void onFinish() { videoDelay = 0; enableWatch(); } }; } }
package com.accp.mapper; import com.accp.domain.Artisangrade; import com.accp.domain.ArtisangradeExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ArtisangradeMapper { int countByExample(ArtisangradeExample example); int deleteByExample(ArtisangradeExample example); int deleteByPrimaryKey(Integer areid); int insert(Artisangrade record); int insertSelective(Artisangrade record); List<Artisangrade> selectByExample(ArtisangradeExample example); Artisangrade selectByPrimaryKey(Integer areid); int updateByExampleSelective(@Param("record") Artisangrade record, @Param("example") ArtisangradeExample example); int updateByExample(@Param("record") Artisangrade record, @Param("example") ArtisangradeExample example); int updateByPrimaryKeySelective(Artisangrade record); int updateByPrimaryKey(Artisangrade record); }
package com.example.admin.masterjson; import com.example.admin.masterjson.model.ItuneStuff; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by ADMIN on 9/26/2017. */ public class JsonItuneParser { public static ItuneStuff getItunestuff(String data) throws JSONException{ ItuneStuff itunestuff=new ItuneStuff(); JSONObject ituneStuffJsonobject=new JSONObject(data); JSONArray resultJsonArray=ituneStuffJsonobject.getJSONArray("results"); JSONObject artistObject=resultJsonArray.getJSONObject(0); itunestuff.setType(getString("wrapperType",artistObject)); itunestuff.setKind(getString("kind",artistObject)); itunestuff.setArtistName(getString("artistName",artistObject)); itunestuff.setCollectionName(getString("collectionName",artistObject)); itunestuff.setArtistViewURL(getString("artworkUrl100",artistObject)); itunestuff.setTrackName(getString("trackName",artistObject)); return itunestuff; } public static JSONObject getJsonObject(String tagname,JSONObject jsonObject)throws JSONException{ return jsonObject.getJSONObject(tagname); } public static String getString(String tagname, JSONObject jsonObject) throws JSONException{ return jsonObject.getString(tagname); } public static int getInt(String tagname,JSONObject jsonObject) throws JSONException{ return jsonObject.getInt(tagname); } public static boolean getBoolean(String tagname,JSONObject jsonObject) throws JSONException{ return jsonObject.getBoolean(tagname); } public static float getFloat(String tagname,JSONObject jsonObject)throws JSONException { return (float) jsonObject.getDouble(tagname); } }
package com.stem.core; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.math.RandomUtils; import com.stem.core.interfaces.ICodeGenerator; public class SimpleCodeGenerator implements ICodeGenerator { private SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); @Override public String generat(String type, int key) { StringBuffer code = new StringBuffer(); code.append(sf.format(new Date())); code.append(type); code.append(key); code.append(RandomUtils.nextInt(10)); return code.toString(); } }
public class NeuralNetwork { Matrix weights_ih; Matrix weights_ho; Matrix bias_h; Matrix bias_o; public int accuracyValue = 0; NeuralNetwork(int numI, int numH, int numO) { weights_ih = new Matrix(numH, numI); weights_ho = new Matrix(numO, numH); Matrix.randomize(weights_ih.data, -1, 1); Matrix.randomize(weights_ho.data, -1, 1); bias_h = new Matrix(numH, 1); bias_o = new Matrix(numO, 1); Matrix.randomize(bias_h.data, -1, 1); Matrix.randomize(bias_o.data, -1, 1); } void train(double[] input_arr, double[] target_arr) { double lr = 0.01; //Convert function inputs to Matrix Matrix input_m = Matrix.fromArray(input_arr); Matrix target_m = Matrix.fromArray(target_arr); //Feed Forward Matrix hidden_output_m = feedForward(input_m, weights_ih, bias_h); Matrix output_m = feedForward(hidden_output_m, weights_ho, bias_o); //Calculate the output layer error //Error = target - outputs Matrix error_m = Matrix.findDiffrence(target_m, output_m); /// /// Change nottation to accept L1 L2 /// //Transpose hidden layer output to allow for the calculation of the gradient of the weights_ho Matrix hidden_output_m_t = Matrix.transposeMatrix(hidden_output_m.data); //Transpose input matrix to allow for the calculation of the gradient of the weights_ih Matrix input_m_t = Matrix.transposeMatrix(input_m.data); //Calculate the derivative of sigmoid Matrix derivative_of_sigmoid_m = Matrix.map(output_m, x -> Matrix.dsoftmax(x)); //Calculate the gradient of the weights_ho matrix Matrix gradient_of_weights_ho_m = Matrix.hadamardProduct(derivative_of_sigmoid_m, error_m); Matrix.scaleMatrix(gradient_of_weights_ho_m.data, lr); bias_o = Matrix.addTwoMatrices(bias_o.data, gradient_of_weights_ho_m.data); gradient_of_weights_ho_m = Matrix.productOfTwoMatrices(gradient_of_weights_ho_m.data, hidden_output_m_t.data); //Adjust the weights_ho matrix accordingly weights_ho = Matrix.addTwoMatrices(weights_ho.data, gradient_of_weights_ho_m.data); //Transpose weights matrix to calculate hidden layer error Matrix weights_ho_t = Matrix.transposeMatrix(weights_ho.data); //Calculate hidden error (error * weight ignoring the normalization) Matrix hidden_error_m = Matrix.productOfTwoMatrices(weights_ho_t.data, error_m.data); //Recalculate the derivative of sigmoid derivative_of_sigmoid_m = Matrix.map(hidden_output_m, x -> Matrix.dsoftmax(x)); //Calculate the gradient of the weights_oh matrix Matrix gradient_of_weights_ih_m = Matrix.hadamardProduct(derivative_of_sigmoid_m, hidden_error_m); Matrix.scaleMatrix(gradient_of_weights_ih_m.data, lr); bias_h = Matrix.addTwoMatrices(bias_h.data, gradient_of_weights_ih_m.data); gradient_of_weights_ih_m = Matrix.productOfTwoMatrices(gradient_of_weights_ih_m.data, input_m_t.data); //Adjust the weights_ih matrix accordingly weights_ih = Matrix.addTwoMatrices(weights_ih.data, gradient_of_weights_ih_m.data); } Matrix feedForward(Matrix input_m, Matrix weights_m, Matrix bias_m) { Matrix output_m = Matrix.productOfTwoMatrices(weights_m.data, input_m.data); output_m = Matrix.addTwoMatrices(output_m.data, bias_m.data); //output_m = Matrix.map(output_m, x -> Matrix.sigmoid(x)); output_m = Matrix.fromArray(Matrix.softmax(Matrix.toArray(output_m))); return output_m; } void displayOutput(float[] arr) { for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
package cs3500.animator.model.feature; import cs3500.animator.model.featuremotion.FeatureMotion; import cs3500.animator.model.featuremotion.FeatureMotionImpl; import cs3500.animator.model.featurestate.FeatureState; import cs3500.animator.model.featurestate.OvalFeatureState; /** * This class represents an Ellipse Feature. One instance of this class represents the lifetime of * an Ellipse within an Animation which includes all of its instantaneous states. */ public class EllipseFeature extends AbstractFeature { /** * This method constructs an EllipseFeature with the specified name. * * @param name the name of the ellipse */ public EllipseFeature(String name) { super(name); } // returns FeatureMotion with given start and end FeatureStates and start and end ticks @Override public FeatureMotion buildMotion(int whenAdded, int t1, int x1, int y1, int w1, int h1, int r1, int g1, int b1, int t2, int x2, int y2, int w2, int h2, int r2, int g2, int b2) { FeatureState start = new OvalFeatureState(x1, y1, w1, h1, r1, g1, b1); start.setMotionNumber(whenAdded); FeatureState end = new OvalFeatureState(x2, y2, w2, h2, r2, g2, b2); end.setMotionNumber(whenAdded); FeatureMotion toAdd = new FeatureMotionImpl(start, end, t1, t2); toAdd.setMotionNumber(whenAdded); return toAdd; } @Override public String getType() { return "ellipse"; // returns type of Feature in the form of a String } }
package com.cyriii.config; import com.cyriii.common.ResultMessage; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { @Autowired private ObjectMapper objectMapper; @Override public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { ResultMessage resultMessage = new ResultMessage(); resultMessage.setCode("100000"); resultMessage.setMessage("用户名或密码错误"); httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write(objectMapper.writeValueAsString(resultMessage)); } }
package com.services; import com.mappers.CredentialMapper; import com.model.Credential; import com.model.Note; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.List; @Service public class CredentialService { private CredentialMapper credentialMapper; public CredentialService(CredentialMapper credentialMapper) { this.credentialMapper = credentialMapper; } @PostConstruct public void postConstruct() { System.out.println("Creating CredentialService bean"); } public List<Note> getCredentials() { return credentialMapper.getAllCredentials(); } public void addNote(Credential credential){ credentialMapper.insertCredentials(credential); } }
package mainGame; import javax.swing.JFrame; import org.newdawn.slick.BasicGame; import org.newdawn.slick.CanvasGameContainer; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import asset.AssetManager; import asset.DungeonManager; import asset.EntityManager; import asset.ItemManager; import asset.SoundManager; import asset.TileManager; import inventoryPack.CraftInventory; import inventoryPack.Inventory; public class WindowGame extends BasicGame { public static final int WIDTH = 1920, HEIGHT = 1080; private boolean leftclick = false; public static World world; AssetManager asset; private CraftInventory craftinventory; private BreakerAnimation breaker; public static Player player; public static Image background; public static Cursor cursor; public static Inventory currentInv; public static DeadScreen deadscreen; public static int SPAWNX; public static int SPAWNY; public WindowGame() { super("mainGame :: WindowGame"); } @Override public void init(GameContainer container) throws SlickException { container.setVSync(true); asset = new AssetManager(); SoundManager.loadMusic(); EntityManager.loadEntity(); TileManager.loadTiles(container); ItemManager.loadItems(); DungeonManager.loadDungeon(); deadscreen = new DeadScreen(); craftinventory = new CraftInventory(); craftinventory.loadCraft(container); player = new Player(container); world = new World(container); SPAWNX = (12*World.getTileSize())*world.getMapWidth()/2; SPAWNY = (12*World.getTileSize())*world.getMapHeight()/2; player.setX(SPAWNX); player.setY(SPAWNY); player.setChunkx(Math.round(player.getX()/World.tileSize/12)); player.setChunky(Math.round(player.getY()/World.tileSize/12)); //container.setFullscreen(true); background = AssetManager.caveback; cursor = new Cursor(AssetManager.Cursor); this.breaker = new BreakerAnimation(); //GENERATE SAFE 3*3 AREA int tileX = Math.round(player.getX()/World.tileSize); int tileY = Math.round(player.getY()/World.tileSize); SoundManager.maintheme.loop(); for(int i = -9; i < 9; i++) { for(int j = -9; j < 9; j++) { World.setTileFromIndex(tileX+i,tileY+j, TileManager.voidt); } } for(int i = 0; i < 99; i++) player.getInventory().addItem(TileManager.woodplat); //DungeonManager.tree1.setDungeonFromTileIndex(tileX-1, tileY-6); //container.setSoundVolume(0); //container.setMusicVolume(0); //WindowGame.world.spawnEntity(player.getX(), player.getY(), EntityManager.janga); ///WindowGame.world.spawnEntity(player.getX(), player.getY(), EntityManager.asmora); } @Override public void render(GameContainer container, Graphics g) throws SlickException { g.clear(); g.resetTransform(); g.drawImage(background, 0, 0); g.setBackground(Color.darkGray); g.translate(container.getWidth() / 2 - (int) player.getX(), container.getHeight() / 2 - (int) player.getY()); world.render(g,container,3,2, Math.round(player.getX()/World.getTileSize())/12, Math.round((player.getY()/World.getTileSize())/12)); if(!deadscreen.isDead()) player.render(g); if(this.leftclick) { this.breaker.Draw(g, cursor.getTileXIndex()*World.tileSize, cursor.getTileYIndex()*World.tileSize); } world.renderEntity(g); world.renderLivingEntity(g,container); if(!player.getInventory().isOpen()) cursor.Draw(g); player.getInventory().render(g,container); if(currentInv != null) { currentInv.render(g, container); } this.craftinventory.render(g, container); String chunkinfo = "\nChunk : " + player.getChunkx() + " , " + player.getChunky(); String entityinf = "\nEntity : " + World.allLivingEntity.size(); g.drawString("X : " + player.getX()/World.tileSize + " Y : " +player.getY()/World.tileSize + chunkinfo + entityinf , 1450, 1000); if(player.getInventory().isOpen()) { cursor.drawInnerCursor(g,container); } if(WindowGame.deadscreen.isDead()) { WindowGame.deadscreen.render(g); } //this.world.Dummyrender(g); } @Override public void update(GameContainer container, int delta) throws SlickException { Input input = container.getInput(); double detx = cursor.getTileXIndex() - WindowGame.player.getX()/World.tileSize; double dety = cursor.getTileYIndex() - WindowGame.player.getY()/World.tileSize; double distance = Math.sqrt(Math.pow(detx, 2) + Math.pow(dety, 2)); world.updateEntity(); world.updateLivingEntity(delta,distance,container); //player.updateCam(world); world.UpdateWorlMap(3, 3, Math.round(player.getX()/World.getTileSize())/12, Math.round((player.getY()/World.getTileSize())/12),delta,container); this.updateBreakAnimation(distance); if(deadscreen.isDead()) { deadscreen.update(delta); } else { player.updatePlayer(delta); this.detectedInput(input, delta); } cursor.updateCursor(container,distance,delta); } @Override public void mousePressed(int button, int x, int y) { switch (button) { case Input.MOUSE_RIGHT_BUTTON: cursor.setPlacing(true); break; case Input.MOUSE_LEFT_BUTTON: this.leftclick = true; break; } } @Override public void mouseReleased(int button, int x, int y){ cursor.setBreaking(false); cursor.setPlacing(false); this.leftclick = false; } @Override public void mouseWheelMoved(int change) { if(!player.getInventory().isOpen()) { if(change < 0) { if(player.getInventory().getSelectedX() < 8) player.getInventory().setSelectedX(player.getInventory().getSelectedX()+1); else player.getInventory().setSelectedX(0); } else { if(player.getInventory().getSelectedX() > 0 ) player.getInventory().setSelectedX(player.getInventory().getSelectedX()-1); else player.getInventory().setSelectedX(8); } } } public void updateBreakAnimation(double distance) { if(distance <2) { cursor.getImage().setImageColor(0, 255, 0); if(this.leftclick && World.getTileFromChunk(cursor.getTileXIndex(), cursor.getTileYIndex()).getName() != "Voidt") { if(!SoundManager.pioche.playing()) SoundManager.pioche.play(); if(World.getTileFromChunk(cursor.getTileXIndex(), cursor.getTileYIndex()).getHarvestLevel() <= cursor.getCurrentEfficiency()) { this.breaker.setMaxTick(World.getTileFromChunk(cursor.getTileXIndex(), cursor.getTileYIndex()).getDurability()); this.breaker.setTick(this.breaker.getTick() + cursor.getCurrentEfficiency()); if(this.breaker.isReady()) { cursor.setBreaking(true); breaker.resetbar(); } this.breaker.setUpdate(true); this.breaker.update(); } } else { SoundManager.pioche.stop(); } } else { cursor.getImage().setImageColor(255, 0, 0); } } public static void main(String[] args) throws SlickException { JFrame frame = new JFrame(); CanvasGameContainer app = new CanvasGameContainer(new WindowGame()); frame.setUndecorated(true); frame.setVisible(true); frame.add(app); frame.setSize(1920, 1080); app.start(); } @Override public void keyReleased(int key, char c) { player.east = false; //player.north = false; player.south = false; player.west = false; if(key == Input.KEY_Q || key == Input.KEY_S || key == Input.KEY_Z || key == Input.KEY_D) { player.setMoving(false); } if(key == Input.KEY_Z || key == Input.KEY_S) { player.setFacing("none"); } } @Override public void keyPressed(int key, char c){ /*if(key == Input.KEY_D) { player.setDirection(3); player.east = true; player.setMoving(true); } if(key == Input.KEY_Q) { player.setDirection(1); player.west = true; player.setMoving(true); } if(key == Input.KEY_S) { player.setDirection(2); player.south = true; player.setMoving(true); } if(key == Input.KEY_Z) { player.setDirection(0); player.north = true; player.setMoving(true); }*/ switch (key) { /*case Input.KEY_D: player.setDirection(3); player.east = true; player.setMoving(true); break; case Input.KEY_Q: player.setDirection(1); player.west = true; player.setMoving(true); break; case Input.KEY_S: player.setDirection(2); player.south = true; player.setMoving(true); break; case Input.KEY_Z: player.setDirection(0); player.north = true; player.setMoving(true); break;*/ case Input.KEY_E: if(currentInv == null) { player.getInventory().setOpen(!player.getInventory().isOpen()); if(player.getInventory().isOpen()) { this.craftinventory.setOpen(true); } else { this.craftinventory.setOpen(false); } } break; case Input.KEY_F: player.setFly(!player.getFly()); break; } switch(key) { case Input.KEY_1: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(0); } break; case Input.KEY_2: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(1); } break; case Input.KEY_3: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(2); } break; case Input.KEY_4: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(3); } break; case Input.KEY_5: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(4); } break; case Input.KEY_6: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(5); } break; case Input.KEY_7: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(6); } break; case Input.KEY_8: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(7); } break; case Input.KEY_9: if(!player.getInventory().isOpen()) { player.getInventory().setSelectedX(8); } break; } } public void detectedInput(Input input,int delta) { if(input.isKeyDown(Input.KEY_D)) { player.setDirection(3); player.east = true; player.setMoving(true); player.setFacing("vertical"); player.updatePosition(delta); } if(input.isKeyDown(Input.KEY_Q)) { player.setDirection(1); player.west = true; player.setMoving(true); player.setFacing("vertical"); player.updatePosition(delta); } if(input.isKeyDown(Input.KEY_S)) { player.setDirection(2); player.south = true; player.setMoving(true); player.setFacing("down"); player.updatePosition(delta); } if(input.isKeyDown(Input.KEY_Z)){ if(player.isOnGround()) player.setJumpheight(29); player.setDirection(0); player.north = true; player.setFacing("up"); player.setMoving(true); player.updatePosition(delta); } player.setDirection(5); player.updatePosition(delta); } }
package registration.booking.service.controller; import java.util.List; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import registration.booking.service.model.Order; import registration.booking.service.model.dto.response.OrderDetailsResponseDto; import registration.booking.service.model.dto.response.OrderResponseDto; import registration.booking.service.service.OrderService; import registration.booking.service.service.dto.mapper.OrderDetailsResponseMapper; import registration.booking.service.service.dto.mapper.OrderResponseMapper; @RestController @RequestMapping("/orders") @AllArgsConstructor public class OrderController { private final OrderService orderService; private final OrderResponseMapper orderResponseMapper; private final OrderDetailsResponseMapper orderDetailsResponseMapper; @PutMapping("/client/{clientId}/complete-order") public ResponseEntity<OrderResponseDto> completeOrder(@PathVariable Long clientId) { Order order = orderService.completeOrder(clientId); List<OrderDetailsResponseDto> orderDetailsResponseDtos = order.getOrderDetails().stream() .map(orderDetailsResponseMapper::map) .collect(Collectors.toList()); OrderResponseDto orderResponseDto = orderResponseMapper.map(order); orderResponseDto.setOrderDetails(orderDetailsResponseDtos); return ResponseEntity.ok(orderResponseDto); } }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ package org.eclipselabs.spray.xtext.ui.quickfix; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.EcoreUtil2; import org.eclipse.xtext.diagnostics.Diagnostic; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; import org.eclipse.xtext.ui.editor.IURIEditorOpener; import org.eclipse.xtext.ui.editor.XtextEditor; import org.eclipse.xtext.ui.editor.model.IXtextDocument; import org.eclipse.xtext.ui.editor.model.edit.IModificationContext; import org.eclipse.xtext.ui.editor.model.edit.ISemanticModification; import org.eclipse.xtext.ui.editor.model.edit.IssueModificationContext; import org.eclipse.xtext.ui.editor.model.edit.SemanticModificationWrapper; import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider; import org.eclipse.xtext.ui.editor.quickfix.Fix; import org.eclipse.xtext.ui.editor.quickfix.IssueResolution; import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionAcceptor; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import org.eclipse.xtext.validation.Issue; import org.eclipselabs.spray.mm.spray.BehaviorGroup; import org.eclipselabs.spray.mm.spray.CustomBehavior; import org.eclipselabs.spray.mm.spray.Diagram; import org.eclipselabs.spray.mm.spray.SprayFactory; import org.eclipselabs.spray.shapes.ui.quickfix.AbstractStyleDSLModificationJob; import org.eclipselabs.spray.shapes.ui.quickfix.LinkingQuickfixModificationJob; import org.eclipselabs.spray.xtext.scoping.AppInjectedAccess; import javax.inject.Inject; public class SprayQuickfixProvider extends DefaultQuickfixProvider { private IResourceDescriptions dscriptions = null; @Inject private IssueModificationContext.Factory modificationContextFactory; @Inject private IURIEditorOpener editorOpener; @Inject private XtextResourceSet xtextResourceSet; @Fix(Diagnostic.LINKING_DIAGNOSTIC) public void handleMissingLink(final Issue issue, IssueResolutionAcceptor acceptor) { if (issue.getMessage().startsWith("Couldn't resolve reference to ShapeDefinition")) { handleMissingDefinitionLink("Create shape definition", "Create shape definition", issue, acceptor, AbstractShapeDSLModificationJob.ModificationJobType.SHAPE); } else if (issue.getMessage().startsWith("Couldn't resolve reference to ConnectionDefinition")) { handleMissingDefinitionLink("Create connection definition", "Create connection definition", issue, acceptor, AbstractShapeDSLModificationJob.ModificationJobType.CONNECTION); } else if (issue.getMessage().startsWith("Couldn't resolve reference to Style")) { handleMissingDefinitionLink("Create style definition", "Create style definition", issue, acceptor, AbstractStyleDSLModificationJob.ModificationJobType.STYLE); } else if (issue.getMessage().startsWith("Couldn't resolve reference to BehaviorGroup")) { acceptor.accept(issue, "Create behavior group", "Create behavior group", null, getModificationForBehaviorGroup(issue)); } else { createLinkingIssueResolutions(issue, acceptor); } } private void handleMissingDefinitionLink(String label, String description, final Issue issue, IssueResolutionAcceptor acceptor, LinkingQuickfixModificationJob linkingQuickfixModificationJob) { URI sprayDSLURI = issue.getUriToProblem(); if (sprayDSLURI != null) { URI shapeDSLURI = getOtherDSLURI(issue.getUriToProblem(), linkingQuickfixModificationJob); if (shapeDSLURI != null) { ISemanticModification modificationForDefinition = getModificationForDefinition(sprayDSLURI, shapeDSLURI, issue, linkingQuickfixModificationJob); if (modificationForDefinition != null) { SemanticModificationWrapper modificationWrapper = new SemanticModificationWrapper(shapeDSLURI, modificationForDefinition); Issue.IssueImpl newIssue = new Issue.IssueImpl(); newIssue.setUriToProblem(shapeDSLURI); acceptor.getIssueResolutions().add(new IssueResolution(label, description, null, modificationContextFactory.createModificationContext(newIssue), modificationWrapper)); } } else { URI styleDSLURI = getOtherDSLURI(issue.getUriToProblem(), linkingQuickfixModificationJob); if (styleDSLURI != null) { createMissingLinkedElement(sprayDSLURI, styleDSLURI, label, description, issue, acceptor, linkingQuickfixModificationJob); } } } } private void createMissingLinkedElement(URI sprayDSLURI, URI otherDSLURI, String label, String description, final Issue issue, IssueResolutionAcceptor acceptor, LinkingQuickfixModificationJob linkingQuickfixModificationJob) { ISemanticModification modificationForDefinition = getModificationForDefinition(sprayDSLURI, otherDSLURI, issue, linkingQuickfixModificationJob); if (modificationForDefinition != null) { SemanticModificationWrapper modificationWrapper = new SemanticModificationWrapper(otherDSLURI, modificationForDefinition); Issue.IssueImpl newIssue = new Issue.IssueImpl(); newIssue.setUriToProblem(otherDSLURI); acceptor.getIssueResolutions().add(new IssueResolution(label, description, null, modificationContextFactory.createModificationContext(newIssue), modificationWrapper)); } } private ISemanticModification getModificationForDefinition(final URI sprayDSLURI, final URI otherDSLURI, final Issue issue, final LinkingQuickfixModificationJob linkingQuickfixModificationJob) { return new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { final IXtextDocument sprayXtextDocument = context.getXtextDocument(sprayDSLURI); final IXtextDocument shapeXtextDocument = context.getXtextDocument(otherDSLURI); IUnitOfWork<?, XtextResource> job = linkingQuickfixModificationJob.create(sprayXtextDocument, issue); if (job != null) { shapeXtextDocument.modify(job); XtextEditor xtextEditor = (XtextEditor) editorOpener.open(otherDSLURI, true); int index = xtextEditor.getDocument().get().length(); if (index > 0) { xtextEditor.selectAndReveal(index, 0); } } } }; } private URI getOtherDSLURI(final URI uriToProblem, LinkingQuickfixModificationJob linkingQuickfixModificationJob) { if (dscriptions == null) { ResourceDescriptionsProvider serviceProvider = AppInjectedAccess.getit(); dscriptions = serviceProvider.createResourceDescriptions(); } return linkingQuickfixModificationJob.getDSLURI(dscriptions, uriToProblem); } private ISemanticModification getModificationForBehaviorGroup(final Issue issue) { return new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { final IXtextDocument xtextDocument = context.getXtextDocument(); String groupName = xtextDocument.get(issue.getOffset(), issue.getLength()).replace("\"", ""); Diagram diagram = EcoreUtil2.getContainerOfType(element, Diagram.class); if (diagram != null) { BehaviorGroup behaviorGroup = SprayFactory.eINSTANCE.createBehaviorGroup(); behaviorGroup.setName(groupName); CustomBehavior customBehavior = SprayFactory.eINSTANCE.createCustomBehavior(); customBehavior.setName(groupName); customBehavior.setLabel(groupName); behaviorGroup.getBehaviorsList().add(customBehavior); diagram.getBehaviourGroupsList().add(behaviorGroup); } } }; } }
package szallitas; import java.util.*; public class Szallito { int nhely; int thely; // 4 public Szallito(int ossz, int t) { this.nhely = ossz - t; this.thely = t; } // 4 private LinkedList<Doboz> normal = new LinkedList<Doboz>(); // 4 private LinkedList<Doboz> torekeny = new LinkedList<Doboz>(); // 4 public LinkedList<Doboz> getDobozok1() {return normal;} // 4 public LinkedList<Doboz> getDobozok2() {return torekeny;} // 4 public boolean felrak(Doboz d) { if (!d.torekenyE() && (nhely - normal.size() > 0)) { normal.add(d); return true; } if (thely - torekeny.size() > 0) { torekeny.add(d); return true; } return false; } // 5 public int lepakol(int db) { int ertek = 0; while (db > 0) { if (torekeny.size() > 0) { db--; ertek += torekeny.get(0).getErtek(); torekeny.remove(0); } else if (normal.size() > 0) { db--; ertek += normal.get(0).getErtek(); normal.remove(0); } else break; } return ertek; } }
package com.yzblike; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient @MapperScan("com.yzblike.dao") public class YzbTrialApplication { public static void main(String[] args) { SpringApplication.run(YzbTrialApplication.class,args); } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.io.File; import java.io.IOException; import java.io.FileNotFoundException; import java.util.Scanner; import java.io.OutputStream; import java.io.FileOutputStream; /** * Die einzigen aktiven Akteure in der Roboterwelt sind die Roboter. * Die Welt besteht aus 14 * 10 Feldern. */ public class Flappy_Bird extends World { private static int zellenGroesse = 1; File folder = new File("saves"); File file = new File("saves/saves.txt"); private Display lDisplay = new Display(1); public Flappy_Bird() { super(750, 750, zellenGroesse); setBackground("images/FB_background.png"); Greenfoot.setSpeed(50); Greenfoot.start(); } public void act() { if(Greenfoot.isKeyDown("escape")) { // Greenfoot.setWorld(new Menu("Test")); } } public int getMoney() { try { Scanner sc = new Scanner(file); int Money = sc.nextInt(); sc.close(); return Money; } catch (FileNotFoundException e) { e.printStackTrace(); } return -33; } public void setMoney(int pMoney) { try { OutputStream stream = new FileOutputStream(file); String Money = "" + pMoney; try { stream.write(Money.getBytes()); stream.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * JobshopVelowarehouse generated by hbm2java */ public class JobshopVelowarehouse implements java.io.Serializable { private JobshopVelowarehouseId id; public JobshopVelowarehouse() { } public JobshopVelowarehouse(JobshopVelowarehouseId id) { this.id = id; } public JobshopVelowarehouseId getId() { return this.id; } public void setId(JobshopVelowarehouseId id) { this.id = id; } }
/* * 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 yblts; /** * * @author balanay-au */ public class connectionString { private String SERVER; private String SNAME; private String SPW; private String SDB; public connectionString(String S, String SN, String SP, String SD) { this.SERVER = S; this.SNAME = SN; this.SPW = SP; this.SDB = SD; } public String getSERVER() { return SERVER; } public void setSERVER(String SERVER) { this.SERVER = SERVER; } public String getSNAME() { return SNAME; } public void setSNAME(String SNAME) { this.SNAME = SNAME; } public String getSPW() { return SPW; } public void setSPW(String SPW) { this.SPW = SPW; } public String getSDB() { return SDB; } public void setSDB(String SDB) { this.SDB = SDB; } }
/** * @author Mie Plougstrup, Anders Abildgaard, Bo Stokholm * @Version 16-12-2014 */ package modelLayer; public class ChartecCode { private int chartecCode; // First 4 digits in chartec number. private String shippingPlace; private boolean hasDeliveryNo; /** * Constructor 1: For creation from ctrClass. * * @param chartecCode * @param shippingPlace * @param haveDeliveryNo */ public ChartecCode(int chartecCode, String shippingPlace, boolean haveDeliveryNo) { this.chartecCode = chartecCode; this.shippingPlace = shippingPlace; this.hasDeliveryNo = haveDeliveryNo; } /** * Constructor 2: For creation from dbClass. */ public ChartecCode() { this.chartecCode = -1; this.shippingPlace = null; this.hasDeliveryNo = false; } /** * Constructor 3: For creation as association. */ public ChartecCode(int chartecCode) { this.chartecCode = chartecCode; this.shippingPlace = null; this.hasDeliveryNo = false; } /** * @return the chartecCode */ public int getChartecCode() { return chartecCode; } /** * @param chartecCode the chartecCode to set */ public void setChartecCode(int chartecCode) { this.chartecCode = chartecCode; } /** * @return the shippingPlace */ public String getShippingPlace() { return shippingPlace; } /** * @param shippingPlace the shippingPlace to set */ public void setShippingPlace(String shippingPlace) { this.shippingPlace = shippingPlace; } /** * @return the haveDeliveryNo */ public boolean hasDeliveryNo() { return hasDeliveryNo; } /** * @param haveDeliveryNo the haveDeliveryNo to set */ public void setHasDeliveryNo(boolean haveDeliveryNo) { this.hasDeliveryNo = haveDeliveryNo; } }
package com.pineapple.mobilecraft.tumcca.mediator; /** * Created by yihao on 15/6/6. */ public interface IRegister { public void addUsernameView(); public void addPasswordView(); public void confirm(); public void cancel(); }
package com.huashun.lockerrobot.exception; public class LockerIsFullException extends RuntimeException { }
package Ex1.RenameVisitors; import Ex1.SearchInContext; import Ex1.SymbolTables.SymbolTable; import Ex1.SymbolTables.VarEntry; import ast.*; import Ex1.RenameVisitors.RenameVisitor; import java.util.Set; public class FieldRenameVisitor extends RenameVisitor { private MethodDecl lastMethodSeen; private boolean isLastOwnerInClassesToCheck; private VarDecl targetAstNode; private Set<String> classesToCheck; public FieldRenameVisitor(String oldName, String newName, SearchInContext searchInContext){ super(oldName, newName, searchInContext); this.targetAstNode = (VarDecl)searchInContext.targetAstNode(); this.classesToCheck = searchInContext.getClassesToCheckForField(targetAstNode); } @Override public void visit(Program prog) { if (prog.mainClass() != null){ prog.mainClass().accept(this); // visit(prog.mainClass()); } if (prog.classDecls() != null){ for (ClassDecl classDecl : prog.classDecls()){ classDecl.accept(this); // visit(classDecl); } } } @Override public void visit(ClassDecl classDecl) { if (classesToCheck.contains(classDecl.name())){ if (classDecl.fields() != null){ for (VarDecl field : classDecl.fields()){ if (field.name().equals(this.oldName)){ field.setName(this.newName); } } } if (classDecl.methoddecls() != null){ for (MethodDecl methodDecl : classDecl.methoddecls()){ methodDecl.accept(this); // visit(methodDecl); } } } } @Override public void visit(MainClass mainClass) { // do nothing } @Override public void visit(MethodDecl methodDecl) { this.lastMethodSeen = methodDecl; boolean isHidingVarExists = false; SymbolTable methodSymbolTable = searchInContext.astNodeToSymbolTable().get(methodDecl); isHidingVarExists = methodSymbolTable.hasVariableWithName(oldName); if (!isHidingVarExists){ if (methodDecl.body() != null){ for (Statement statement : methodDecl.body()){ statement.accept(this); // visit(statement); } } methodDecl.ret().accept(this); // visit(methodDecl.ret()); } } @Override public void visit(FormalArg formalArg) { // do nothing } @Override public void visit(VarDecl varDecl) { //do nothing } @Override public void visit(BlockStatement blockStatement) { if (blockStatement.statements() != null){ for (Statement statement : blockStatement.statements()){ statement.accept(this); // visit(statement); } } } @Override public void visit(IfStatement ifStatement) { ifStatement.cond().accept(this); ifStatement.thencase().accept(this); ifStatement.elsecase().accept(this); } @Override public void visit(WhileStatement whileStatement) { whileStatement.cond().accept(this); whileStatement.body().accept(this); } @Override public void visit(SysoutStatement sysoutStatement) { sysoutStatement.arg().accept(this); } @Override public void visit(AssignStatement assignStatement) { if (assignStatement.lv().equals(oldName)){ assignStatement.setLv(newName); } assignStatement.rv().accept(this); } @Override public void visit(AssignArrayStatement assignArrayStatement) { if (assignArrayStatement.lv().equals(oldName)){ assignArrayStatement.setLv(newName); } assignArrayStatement.index().accept(this); assignArrayStatement.rv().accept(this); } @Override public void visit(AndExpr e) { e.e1().accept(this); e.e2().accept(this); } @Override public void visit(LtExpr e) { e.e1().accept(this); e.e2().accept(this); } @Override public void visit(AddExpr e) { e.e1().accept(this); e.e2().accept(this); } @Override public void visit(SubtractExpr e) { e.e1().accept(this); e.e2().accept(this); } @Override public void visit(MultExpr e) { e.e1().accept(this); e.e2().accept(this); } @Override public void visit(ArrayAccessExpr e) { e.arrayExpr().accept(this); e.indexExpr().accept(this); } @Override public void visit(ArrayLengthExpr e) { e.arrayExpr().accept(this); } @Override public void visit(MethodCallExpr e) { e.ownerExpr().accept(this); if (e.actuals() != null){ for (Expr actual : e.actuals()){ actual.accept(this); } } } @Override public void visit(IntegerLiteralExpr e) { // do nothing } @Override public void visit(TrueExpr e) { // do nothing } @Override public void visit(FalseExpr e) { // do nothing } @Override public void visit(IdentifierExpr e) { if (e.id().equals(oldName)){ e.setId(newName); } } @Override public void visit(ThisExpr e) { //do nothing } @Override public void visit(NewIntArrayExpr e) { e.lengthExpr().accept(this); } @Override public void visit(NewObjectExpr e) { // do nothing } @Override public void visit(NotExpr e) { e.e().accept(this); } @Override public void visit(IntAstType t) { // do nothing } @Override public void visit(BoolAstType t) { // do nothing } @Override public void visit(IntArrayAstType t) { // do nothing } @Override public void visit(RefType t) { // do nothing } }
import Healing.HealingTool; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HealingToolTest { private HealingTool healingTool; @Before public void before(){ healingTool = new HealingTool("bread", 10, 10); } @Test public void can_get_name(){ assertEquals("bread", healingTool.getName()); } @Test public void can_get_value(){ assertEquals(10, healingTool.getHealingAmount(), 0.01); } }
package br.edu.ifpb.followup.controller; import br.edu.ifpb.followup.entity.Professor; import br.edu.ifpb.followup.dao.ProfessorDAO; import br.edu.ifpb.followup.entity.ListaDeQuestao; import br.edu.ifpb.followup.entity.Questao; import br.edu.ifpb.followup.session.SessionJSF; import br.edu.ifpb.followup.session.UserSession; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean @RequestScoped public class ProfessorService { @EJB private ProfessorDAO pDao; private Professor prof; @PostConstruct public void init() { prof = (Professor) UserSession.getUser(); } public List<Questao> questoes(){ return pDao.questoes(prof); } }
package com.mx.profuturo.bolsa.model.vo.vacancy; import com.mx.profuturo.bolsa.model.vo.common.CatalogoVO; public class InformacionBasicaVacante { private int idVacante; private String titulo; private CatalogoVO areaInteres; private String descripcionVacante; private String salario; private String fechaPublicacion; private String turno; private String division; public int getIdVacante() { return idVacante; } public void setIdVacante(int idVacante) { this.idVacante = idVacante; } public String getDescripcionVacante() { return descripcionVacante; } public void setDescripcionVacante(String descripcionVacante) { this.descripcionVacante = descripcionVacante; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getSalario() { return salario; } public void setSalario(String salario) { this.salario = salario; } public String getFechaPublicacion() { return fechaPublicacion; } public void setFechaPublicacion(String fechaPublicacion) { this.fechaPublicacion = fechaPublicacion; } public CatalogoVO getAreaInteres() { return areaInteres; } public void setAreaInteres(CatalogoVO areaInteres) { this.areaInteres = areaInteres; } public String getTurno() { return turno; } public void setTurno(String turno) { this.turno = turno; } public String getDivision() { return division; } public void setDivision(String division) { this.division = division; } public InformacionBasicaVacante(int idVacante, String descripcionVacante, String titulo, String salario, String fechaPublicacion, CatalogoVO areaInteres, String turno, String division) { this.idVacante = idVacante; this.descripcionVacante = descripcionVacante; this.titulo = titulo; this.salario = salario; this.fechaPublicacion = fechaPublicacion; this.areaInteres = areaInteres; this.turno = turno; this.division = division; } public InformacionBasicaVacante() { } }
package fanli.selfcode.binarysortedtree; // 二叉树创建和遍历 // 二叉树的删除结点操作 // 同一个类 private 同一个包(default) 非同包继承 proteced 非同包不继承 public public class BinarySortTreeDemo { public static void main(String[] args) { int[] arr = new int[]{7,3,10,12,5,1,9,11}; BST_Tree bsTree = new BST_Tree(); for (int num : arr) { bsTree.add(new Node(num)); } System.out.println("创建的二叉搜索树,中序遍历结果为:"); bsTree.inOrder_BST(); System.out.println(); System.out.println("==================================="); bsTree.deleteNode(7); System.out.println("删除一个结点后"); bsTree.inOrder_BST(); System.out.println(); bsTree.deleteNode(10); System.out.println("删除一个结点后"); bsTree.inOrder_BST(); System.out.println(); bsTree.deleteNode(3); System.out.println("删除一个结点后"); bsTree.inOrder_BST(); } } class BST_Tree{ Node root; public Node getRoot(){ return root; } public void add(Node node){ if(root == null){ root = node; }else { root.addNode(node); } } public void inOrder_BST(){ if(root == null) return; else{ root.inOrder(); } } public void deleteNode(int data){ Node delNode = root.searchNode(data); // System.out.println("要删除的结点为:"+delNode.data); Node parent; if(delNode.left == null && delNode.right == null){ // 叶子结点删除 parent = delNode.parent; if(parent == null){ root = null; // 树只有一个根结点 return; } if(parent.left == delNode) parent.left = null; if(parent.right == delNode) parent.right = null; }else if(delNode.left != null && delNode.right != null){ // 有左右孩子的结点删除 Node tmp = delNode.right.leftMostNode(); // System.out.println("tmp = "+tmp.data); deleteNode(tmp.data); // 不知道对不对,感觉像用了递归 -- > OK了 delNode.data = tmp.data; }else{ // 只有一个孩子的结点删除 parent = delNode.parent; if(parent == null){ this.root = delNode.left == null ? delNode.right : delNode.left; return; } if(parent.left == delNode){ parent.left = delNode.left == null? delNode.right : delNode.left; } if(parent.right == delNode){ parent.right = delNode.left == null? delNode.right : delNode.left; } } } } class Node{ Integer data; Node left; Node right; Node parent; public Node(Integer value){ this.data = value; } // 添加结点 递归 public void addNode(Node node){ if(node == null) return; if(node.data < this.data){ if(this.left == null){ this.left = node; node.parent = this; }else { this.left.addNode(node); // 以left为根结点去添加新的结点 } }else { if(this.right == null){ this.right = node; node.parent = this; }else{ this.right.addNode(node); } } } // 找到要删除的结点 public Node searchNode(int data){ if(this.data == data){ return this; }else { if(data < this.data){ return this.left.searchNode(data); }else{ return this.right.searchNode(data); } } } // 找到以该结点为根的最左部分的结点 public Node leftMostNode(){ if(this == null) return null; Node node = this; Node p = null; while( node != null){ p = node; node = node.left; } return p; } // 中序遍历 public void inOrder(){ if(this.left != null){ this.left.inOrder(); } System.out.print(this.data+ " "); if(this.right != null){ this.right.inOrder(); } } }
package bootcamp.test.alert; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class Prompt { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); // to launch a page driver.get("https://demoqa.com/alerts"); driver.findElement(By.id("promtButton")).click(); Alert prompt = driver.switchTo().alert(); System.out.println(prompt.getText()); // Please enter your name prompt.sendKeys("Hello"); prompt.accept(); } }
package com.tencent.mm.plugin.sns.model; import com.tencent.mm.plugin.sns.storage.n; import com.tencent.mm.sdk.platformtools.x; class ar$6 implements Runnable { final /* synthetic */ ar nrO; final /* synthetic */ ay nrQ; final /* synthetic */ boolean nrR; ar$6(ar arVar, ay ayVar, boolean z) { this.nrO = arVar; this.nrQ = ayVar; this.nrR = z; } public final void run() { n Nl = af.byo().Nl(this.nrQ.bKW); this.nrQ.nsF = Nl != null ? Nl.field_userName : ""; x.i("MicroMsg.SnsVideoService", "offer [%b] video task[%s] to queue ", new Object[]{Boolean.valueOf(this.nrR), this.nrQ}); if (this.nrR) { this.nrO.nrK.offerFirst(this.nrQ); } else { this.nrO.nrK.offerLast(this.nrQ); } this.nrO.nrL.put(this.nrQ.elz, this.nrQ); } }
package seleniumGrid; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class findElementTest { public static void main(String[] args) throws Exception { // Start browser //System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe"); System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Thread.sleep(200); driver.findElement(By.name("button")).click(); // Navigate to the URL---body > div > div > form > table.m_tbl > tbody > tr > td > table.table-upper > tbody > tr:nth-child(4) > td > table > tbody > tr > td:nth-child(1) > input.btn // driver.findElement(By.linkText("Deprecated")).click(); driver.get("https://www.techbeamers.com"); //driver.get("https://stackoverflow.com/"); // Sleep for 5 seconds Thread.sleep(5000); // Here, see how the XPath will select unique Element. WebElement link = driver .findElement(By.xpath("'//table/tr[1]/td[1]/a")); // click on the link link.click(); } }
package com.tencent.mm.model; import com.tencent.mm.a.e; import com.tencent.mm.ak.q; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.io.File; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public final class w { public a dBc = null; boolean dBd = false; BlockingQueue<c> dBe = new ArrayBlockingQueue(80); public b dBf = null; ag handler; class c { boolean dBk = false; String dBl; String filename; int pos; String url; public c(String str, String str2, int i, String str3) { this.url = str; if (q.Pn() && w.this.dBd) { this.url = q.lX(this.url); } this.filename = str2; this.pos = i; this.dBk = false; this.dBl = str3; } } static /* synthetic */ void a(w wVar, long j, long j2) { if (wVar.dBd) { x.d("MicroMsg.GetPicService", "doIdKeyStat, key:%d, val:%d", new Object[]{Long.valueOf(j), Long.valueOf(j2)}); h.mEJ.a(86, j, j2, false); } } public w(boolean z) { g.Ek(); this.handler = new 1(this, g.Em().lnJ.getLooper()); this.dBc = null; this.dBd = z; x.d("MicroMsg.GetPicService", "getPicService, isFromWebView:%b", new Object[]{Boolean.valueOf(z)}); } public final String c(String str, int i, int i2, String str2) { String str3; if (str == null) { str3 = null; } else if (g.Eg().Dx()) { str3 = com.tencent.mm.plugin.p.c.Gb() + "/reader_" + i + "_" + com.tencent.mm.a.g.u(str.getBytes()) + ".jpg"; } else { x.i("MicroMsg.GetPicService", "genFileName, account not ready"); File file = new File(g.Ei().dqo + "/imagecache"); if (!file.exists()) { file.mkdirs(); } str3 = file.getAbsolutePath() + "/reader_" + i + "_" + com.tencent.mm.a.g.u(str.getBytes()) + ".jpg"; } x.d("MicroMsg.GetPicService", "getPicfileByUrl type:" + i + " url:" + str); try { if (e.cn(str3)) { return str3; } } catch (Throwable e) { x.e("MicroMsg.GetPicService", "exception:%s", new Object[]{bi.i(e)}); } try { this.dBe.add(new c(str, str3, i2, str2)); if (this.dBc == null || !com.tencent.mm.sdk.f.e.X(this.dBc)) { com.tencent.mm.sdk.f.e.remove(this.dBc); this.dBc = new a(this); com.tencent.mm.sdk.f.e.post(this.dBc, "GetPicService_getPic"); } } catch (Throwable e2) { x.e("MicroMsg.GetPicService", "exception:%s", new Object[]{bi.i(e2)}); } return null; } }
package com.goldgov.gtiles.core.web.webservice; import java.io.IOException; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.annotation.PostConstruct; import javax.jws.HandlerChain; import javax.jws.WebService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.ClassUtils; import com.goldgov.gtiles.core.web.webservice.annotation.WebServiceExplain; import com.goldgov.gtiles.core.web.webservice.authenticator.AuthServerHandler; import com.goldgov.gtiles.core.web.webservice.service.impl.WebServiceContext; public class WebServiceResourceLoader{ private ResourceBundle resourceBundle = ResourceBundle.getBundle("config"); private String RESOURCE_PATTERN = "/**/*.class"; private String[] packagesToScan; private final Log logger = LogFactory.getLog(getClass()); @PostConstruct public void initWebServiceResource() { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); //FIXME if(packagesToScan == null){ packagesToScan = new String[]{"com.goldgov"}; } for (String pkg : packagesToScan) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN; Resource[] resources = null; try { resources = resourcePatternResolver.getResources(pattern); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { MetadataReader reader = null; try { reader = readerFactory.getMetadataReader(resource); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } if (resource.isReadable()) { ClassMetadata classMetadata = reader.getClassMetadata(); if(classMetadata.isAbstract() || classMetadata.isInterface()){ continue; } process(reader); } } } logger.info("启用了WebService组件,目前系统中的WebService服务数量:" + WebServiceContext.getServiceSize()); } private void process(MetadataReader metadataReader){ AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); Map<String, Object> webServiceAttributes = annotationMetadata.getAnnotationAttributes(WebService.class.getName()); if(webServiceAttributes != null){ ServiceState serviceState = new ServiceState(); serviceState.setServiceName((String) webServiceAttributes.get("serviceName")); Map<String, Object> explainAttributes = annotationMetadata.getAnnotationAttributes(WebServiceExplain.class.getName()); if(explainAttributes != null){ serviceState.setServiceExplain((String)explainAttributes.get("name")); } Map<String, Object> handlerChainAttributes = annotationMetadata.getAnnotationAttributes(HandlerChain.class.getName()); if(handlerChainAttributes != null){ if(AuthServerHandler.AUTHENTICATION_HANDLER_CHAIN.equals(handlerChainAttributes.get("file"))){ serviceState.setNeedAuth(true); } } String hostname = "127.0.0.1"; int serverPort = 8317; String basePath = "/"; try{ hostname = String.valueOf(resourceBundle.getObject("webService-serverHostname")); }catch(MissingResourceException e){} try{ serverPort = Integer.parseInt(resourceBundle.getObject("webService-serverPort").toString()); }catch(MissingResourceException e){} try{ basePath = String.valueOf(resourceBundle.getObject("webService-serverBasePath")); basePath = basePath.startsWith("/") ? basePath : "/" + basePath; basePath = basePath.endsWith("/") ? basePath : basePath + "/"; }catch(MissingResourceException e){} serviceState.setServiceUrl("http://" + hostname + ":" + serverPort + basePath + serviceState.getServiceName() +"?wsdl"); // try { // HttpServer httpServer = (HttpServer)SpringBeanUtils.getBean("WebServiceServer"); // String hostName = httpServer.getAddress().getHostName(); // int port = httpServer.getAddress().getPort(); // } catch (NoSuchBeanDefinitionException e) { // } WebServiceContext.addServiceState(serviceState); } } public void setPackagesToScan(String[] packagesToScan) { this.packagesToScan = packagesToScan; } }
package cn.xeblog.design.patterns.decorator.code; /** * cf游戏服务接口 * * @author anlingyi */ public interface CFGameService { /** * 登入 * @param username * @param password */ void login(String username, String password); /** * 开枪射击 */ void fire(); /** * 丢手雷 */ void grenade(); }
package com.tencent.mm.plugin.luckymoney.ui; import com.tencent.mm.g.a.pl; import com.tencent.mm.plugin.wallet_core.model.a; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h; class LuckyMoneyPrepareUI$12 extends c<pl> { final /* synthetic */ LuckyMoneyPrepareUI kWX; LuckyMoneyPrepareUI$12(LuckyMoneyPrepareUI luckyMoneyPrepareUI) { this.kWX = luckyMoneyPrepareUI; this.sFo = pl.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { a aVar = ((pl) bVar).can.cao; if (aVar != null && aVar.bOq()) { x.i("MicroMsg.LuckyMoneyPrepareUI", "show 261 alert item"); LuckyMoneyPrepareUI.a(this.kWX, true); h.a(this.kWX.mController.tml, aVar.bSc, "", aVar.kRv, aVar.kRu, new 1(this, aVar), new 2(this)); } return false; } }
/** * Copyright © 2016 公司名. All rights reserved. * * @Title: LoginVo.java * @Prject: mainWeb * @Package: com.hyx.mainweb.controller.iphone.param * @Description: TODO * @author: Administrator * @date: 2016年6月6日 上午9:26:27 * @version: V1.0 */ package com.nemo.api.services.param.input.user; /** * @ClassName: LoginVo * @Description: 登录vo * @author: Administrator * @date: 2016年6月6日 上午9:26:27 */ public class OauthLoginInPutVo { /** * serialVersionUID */ private String type;// 1表示QQ快捷登录;2表示是微信快捷登录;3表示是新浪微博快捷登录 private String oauthName;//第三方登录的名称 private String oauthId;// 第三方协议id private long oauthAccessToken;//访问秘钥 private long oauthExpires;//协议到期时间 private long userId;//用户Id public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getOauthExpires() { return oauthExpires; } public void setOauthExpires(long oauthExpires) { this.oauthExpires = oauthExpires; } public long getOauthAccessToken() { return oauthAccessToken; } public void setOauthAccessToken(long oauthAccessToken) { this.oauthAccessToken = oauthAccessToken; } public String getOauthName() { return oauthName; } public void setOauthName(String oauthName) { this.oauthName = oauthName; } public String getOauthId() { return oauthId; } public void setOauthId(String oauthId) { this.oauthId = oauthId; } }
package kr.ko.nexmain.server.MissingU.membership.model; import org.hibernate.validator.constraints.NotEmpty; import kr.ko.nexmain.server.MissingU.common.model.CommReqVO; public class UpdateFmJoinYnReqVO extends CommReqVO { private static final long serialVersionUID = -5457239916212812718L; @NotEmpty private String fmJoinYn; /** * @return the fmJoinYn */ public String getFmJoinYn() { return fmJoinYn; } /** * @param fmJoinYn the fmJoinYn to set */ public void setFmJoinYn(String fmJoinYn) { this.fmJoinYn = fmJoinYn; } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.g.a.py; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; class SnsTimeLineUI$8 extends c<py> { final /* synthetic */ SnsTimeLineUI odw; SnsTimeLineUI$8(SnsTimeLineUI snsTimeLineUI) { this.odw = snsTimeLineUI; this.sFo = py.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { py pyVar = (py) bVar; if (!(SnsTimeLineUI.g(this.odw) == null || SnsTimeLineUI.g(this.odw).nLK == null)) { com.tencent.mm.plugin.sns.h.b bVar2 = SnsTimeLineUI.g(this.odw).nLK.nrb; bVar2.nxd.add(pyVar.caE.bSZ); } return false; } }
package com.dps.ring2park.web; import java.security.Principal; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.dps.ring2park.domain.Booking; import com.dps.ring2park.service.BookingService; import com.dps.ring2park.service.UserService; @Controller @RequestMapping("/statements/*") public class StatementsController { @Autowired private BookingService bookingService; @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET) public String list(Principal currentUser, Model model) { List<Booking> bookings; boolean isAdmin = false; if (userService.hasRole("ROLE_ADMIN")) isAdmin = true; /*UserDetails userDetails = userService.getUserDetails(); Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities(); for (GrantedAuthority grantedAuthority : authorities) { if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { isAdmin = true; } }*/ if (isAdmin) bookings = bookingService.findBookings(); else bookings = bookingService.findBookings(currentUser.getName()); model.addAttribute("bookingList", bookings); return "statements/list"; } @RequestMapping(value = "{id}", method = RequestMethod.GET) public String details(@PathVariable Long id, Model model) { model.addAttribute(bookingService.findBookingById(id)); return "statements/details"; } }
package br.com.caelum.estoque.modelo.usuario; import java.util.Date; import javax.xml.ws.WebFault; @WebFault(name = "AutoricaoFault", messageName = "AutorizacaoFault") public class AutorizacaoExcveption extends Exception { public AutorizacaoExcveption(String mensagem) { super(mensagem); } public FaultInfo getFaultInfo() { return new FaultInfo("Token inválido", new Date()); } }
package com.tencent.mm.pluginsdk.ui; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import com.tencent.mm.R; import com.tencent.mm.aa.g; import com.tencent.mm.aa.q; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.plugin.webview.ui.tools.widget.m; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.o; import com.tencent.mm.ui.base.s; public final class f { private static final Drawable kXh = new ColorDrawable(); private Activity activity; private String fsq; public o kXg; private GetHdHeadImageGalleryView kXi; private g mQp; private String qFo; private b qFp; private int qFq; private String username; public f(Activity activity, String str) { this(activity, str, null); } public f(Activity activity, String str, String str2) { this(activity, str, str2, a.qFt); } public f(Activity activity, String str, String str2, int i) { this(activity, str, str2, i, (byte) 0); } private f(Activity activity, String str, String str2, int i, byte b) { this.qFo = null; this.fsq = null; this.activity = activity; this.username = str; this.fsq = str2; this.qFp = null; this.qFq = i; } public final void cde() { View inflate = LayoutInflater.from(this.activity).inflate(R.i.get_hd_head_image_gallery_view, null); this.kXg = new o(inflate, -1, -1); switch (3.qFs[this.qFq - 1]) { case 1: this.kXg.setAnimationStyle(R.m.PopLeftTopAnimation); break; case 2: this.kXg.setAnimationStyle(R.m.PopRightTopAnimation); break; case 3: this.kXg.setAnimationStyle(R.m.PopLeftBottomAnimation); break; } this.kXg.setFocusable(true); this.kXg.setOutsideTouchable(true); this.kXg.setBackgroundDrawable(kXh); this.kXg.showAtLocation(this.activity.getWindow().getDecorView(), 49, 0, 0); this.kXg.setOnDismissListener(new 1(this)); this.kXi = (GetHdHeadImageGalleryView) inflate.findViewById(R.h.gallery); this.kXi.setParentWindow(this.kXg); this.kXi.setUsername(this.username); m.Bk(1); au.HU(); if (c.isSDCardAvailable()) { Bitmap d = !bi.oW(this.fsq) ? com.tencent.mm.ac.m.d(this.username, this.fsq, R.g.nosdcard_headimg) : com.tencent.mm.aa.c.a(this.username, true, -1); if (d == null) { d = BitmapFactory.decodeResource(this.activity.getResources(), R.g.default_avatar); } if (d == null || d.isRecycled()) { x.i("MicroMsg.GetHdHeadImg", "The avatar of %s is not in the cache, use default avatar", new Object[]{this.username}); } else { x.i("MicroMsg.GetHdHeadImg", "The avatar of %s is in the cache", new Object[]{this.username}); this.kXi.setThumbImage(d); } if (!bi.oW(this.qFo)) { this.username = this.qFo; } Bitmap jU = q.Kp().jU(this.username); if (jU == null || jU.isRecycled()) { this.mQp = new g(); this.mQp.a(this.username, new 2(this, d)); return; } x.i("MicroMsg.GetHdHeadImg", "The HDAvatar of %s is already exists", new Object[]{this.username}); d(jU, q.Kp().c(this.username, true, false)); return; } s.gH(this.activity); d(q.Kp().bJ(this.activity), null); } private void d(Bitmap bitmap, String str) { try { Bitmap createBitmap; if (bitmap.getWidth() < 480) { float width = (float) (480 / bitmap.getWidth()); Matrix matrix = new Matrix(); matrix.postScale(width, width); createBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } else { createBitmap = bitmap; } x.d("MicroMsg.GetHdHeadImg", "dkhdbm old[%d %d] new[%d %d]", new Object[]{Integer.valueOf(bitmap.getWidth()), Integer.valueOf(bitmap.getHeight()), Integer.valueOf(createBitmap.getWidth()), Integer.valueOf(createBitmap.getHeight())}); this.kXi.setHdHeadImage(createBitmap); this.kXi.setHdHeadImagePath(str); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.GetHdHeadImg", e, "", new Object[0]); } } }
package SemanticsAndTypes; import AST.*; import AST.Visitor.Visitor; import javax.lang.model.type.ArrayType; import java.beans.Expression; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; public class ErrorCheckVisitor implements Visitor { public SymbolTable symbolTable; public TypeTable typeTable; private String currentClass; private String currentMethod; private int errorCounter; public ErrorCheckVisitor(Program root, SymbolTable st, TypeTable tt) { errorCounter = 0; symbolTable = st; typeTable = tt; root.accept(this); } public boolean errorsInProgram() { return (errorCounter > 0); } // Display added for toy example language. Not used in regular MiniJava public void visit(Display n) { n.e.accept(this); } // MainClass m; // ClassDeclList cl; public void visit(Program n) { n.m.accept(this); for ( int i = 0; i < n.cl.size(); i++ ) { n.cl.get(i).accept(this); } } // Identifier i1,i2; // Statement s; public void visit(MainClass n) { currentClass = n.i1.s; // TAG n.i1.accept(this); // class name n.s.accept(this); // main method body } // Identifier i; // VarDeclList vl; // MethodDeclList ml; public void visit(ClassDeclSimple n) { currentClass = n.i.s; // TAG n.i.accept(this); // class name for ( int i = 0; i < n.vl.size(); i++ ) { if (symbolTable.getClassScope(currentClass).instanceVariableCount.get(n.vl.get(i).i.s) != 1) { System.out.println("Error: (Line " + n.vl.get(i).line_number + ") variable " + n.vl.get(i).i.s + " is already defined."); errorCounter++; } n.vl.get(i).accept(this); } for ( int i = 0; i < n.ml.size(); i++ ) { currentMethod = n.ml.get(i).i.s; for (int j = 0; j < n.ml.get(i).fl.size(); j++) { String argumentName = n.ml.get(i).fl.get(j).i.s; // check if argument is declared already as a field if (symbolTable.getClassScope(currentClass).instanceVariableCount.containsKey(argumentName)) { System.out.println("Error: (Line " + n.ml.get(i).fl.get(j).line_number + ") argument " + argumentName + " is already defined as field."); errorCounter++; } if (symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).variableDeclarationCount.get(argumentName) != 1) { System.out.println("Error: (Line " + n.ml.get(i).fl.get(j).line_number + ") argument " + argumentName + " is already defined in method scope."); errorCounter++; } } // checking the method variables for (int j = 0; j < n.ml.get(i).vl.size(); j++) { String methodVarName = n.ml.get(i).vl.get(j).i.s; // check if variable in method is declared already as a field if (symbolTable.getClassScope(currentClass).instanceVariableCount.containsKey(methodVarName)) { System.out.println("Error: (Line " + n.ml.get(i).vl.get(j).line_number + ") variable " + methodVarName + " is already defined as field."); errorCounter++; } if (symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).variableDeclarationCount.get(methodVarName) != 1) { System.out.println("Error: (Line " + n.ml.get(i).vl.get(j).line_number + ") variable " + methodVarName + " is already defined in method scope."); errorCounter++; } } n.ml.get(i).accept(this); } } // Identifier i; // Identifier j; // VarDeclList vl; // MethodDeclList ml; public void visit(ClassDeclExtends n) { currentClass = n.i.s; // TAG n.i.accept(this); // class name if (!checkLoopInheritance(n.i.s, new HashSet<>())) { // if loop encountered, abandon ship System.exit(1); } n.j.accept(this); // extend class name for ( int i = 0; i < n.vl.size(); i++ ) { String fieldName = n.vl.get(i).i.s; // check for fieldname in superclass of any depth if (fieldFoundInSuper(fieldName, currentClass)) { System.out.println("Error: (Line " + n.vl.get(i).line_number + ") field " + fieldName + " already inherited."); errorCounter++; } // check if its already defined in class scope if (symbolTable.getClassScope(currentClass).instanceVariableCount.get(fieldName) != 1) { System.out.println("Error: (Line " + n.vl.get(i).line_number + ") variable " + fieldName + " is already defined."); errorCounter++; } n.vl.get(i).accept(this); } if (symbolTable.getClassScope(n.j.s) == null) { System.out.println("Error: (Line " + n.line_number + ") superclass " + n.j.s + " does not exist."); errorCounter++; } for ( int i = 0; i < n.ml.size(); i++ ) { currentMethod = n.ml.get(i).i.s; if (symbolTable.getClassScope(n.j.s) != null) { for (int j = 0; j < n.ml.get(i).fl.size(); j++) { String argumentName = n.ml.get(i).fl.get(j).i.s; if (fieldFoundInSuper(argumentName, currentClass)) { System.out.println("Error: (Line " + n.ml.get(i).fl.get(j).line_number + ") argument " + argumentName + " already inherited."); errorCounter++; } if (symbolTable.getClassScope(currentClass).instanceVariableCount.containsKey(argumentName)) { System.out.println("Error: (Line " + n.ml.get(i).fl.get(j).line_number + ") argument " + argumentName + " is already defined as field."); errorCounter++; } if (symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).variableDeclarationCount.get(argumentName) != 1) { System.out.println("Error: (Line " + n.ml.get(i).fl.get(j).line_number + ") argument " + argumentName + " is already defined in method scope."); errorCounter++; } } for (int j = 0; j < n.ml.get(i).vl.size(); j++) { String variableName = n.ml.get(i).vl.get(j).i.s; if (fieldFoundInSuper(variableName, currentClass)) { System.out.println("Error: (Line " + n.ml.get(i).vl.get(j).line_number + ") argument " + variableName + " already inherited."); errorCounter++; } // check if variable in method is declared already as a field if (symbolTable.getClassScope(currentClass).instanceVariableCount.containsKey(variableName)) { System.out.println("Error: (Line " + n.ml.get(i).vl.get(j).line_number + ") variable " + variableName + " is already defined as field."); errorCounter++; } if (symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).variableDeclarationCount.get(variableName) != 1) { System.out.println("Error: (Line " + n.ml.get(i).vl.get(j).line_number + ") variable " + variableName + " is already defined in method scope."); errorCounter++; } } if (symbolTable.getClassScope(n.j.s).methodMap.containsKey(currentMethod)) { if (isDerived(symbolTable.getClassScope(n.j.s).getMethodScope(currentMethod).methodType, symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).methodType)) { for (int j = 0; j < n.ml.get(i).fl.size(); j++) { Type t = n.ml.get(i).fl.get(i).t; String superType = symbolTable.getClassScope(n.j.s).getMethodScope(currentMethod).arguments.get(j).type; if (!((t instanceof BooleanType && superType.equals("boolean")) || (t instanceof IntegerType && superType.equals("integer")) || (t instanceof IntArrayType && superType.equals("intArray")) || (t instanceof IdentifierType && superType.equals(((IdentifierType) t).s)))) { errorCounter++; System.out.println("Error (line " + n.ml.get(i).line_number + ") override method argument types do not match"); } } } else { errorCounter++; System.out.println("Error (line " + n.ml.get(i).line_number + ") override method return type does not match"); } } } n.ml.get(i).accept(this); } } // Type t; // Identifier i; public void visit(VarDecl n) { n.t.accept(this); n.i.accept(this); } // Type t; // Identifier i; // FormalList fl; // VarDeclList vl; // StatementList sl; // Exp e; public void visit(MethodDecl n) { currentMethod = n.i.s; // TAG n.i.accept(this); // method name n.t.accept(this); // return type for ( int i = 0; i < n.fl.size(); i++ ) { String idLookup = lookupTypeForID(n.fl.get(i).i.s); if (idLookup != null && !typeTable.types.containsKey(idLookup)) { System.out.println("Error: (Line " + n.fl.line_number + ") argument type " + idLookup + " is not defined."); errorCounter++; } n.fl.get(i).accept(this); } for ( int i = 0; i < n.vl.size(); i++ ) { n.vl.get(i).accept(this); } for ( int i = 0; i < n.sl.size(); i++ ) { n.sl.get(i).accept(this); } checkTypesMatch(n.e, n.t); n.e.accept(this); } public void checkTypesMatch(Exp e, Type t) { if (isArithmeticExpression(e, false)) { if (!(t instanceof IntegerType)) { System.out.println("Error: (line " + e.line_number + ") return types don't match."); errorCounter++; } } else if (isBooleanExpression(e)) { if (!(t instanceof BooleanType)) { System.out.println("Error: (line " + e.line_number + ") return types don't match."); errorCounter++; } } else if (e instanceof Call) { if (isCall(((Call) e).e, ((Call) e).i, ((Call) e).el, "intArray", false)) { if (!(t instanceof IntArrayType)) { System.out.println("Error: (line " + e.line_number + ") return types don't match."); errorCounter++; } } if (t instanceof IdentifierType) { if (!isCall(((Call) e).e, ((Call) e).i, ((Call) e).el, ((IdentifierType)t).s, false)) { System.out.println("Error: (line " + e.line_number + ") return types don't match."); errorCounter++; } } else { // some sort of error } } else if (e instanceof IdentifierExp) { if (t instanceof IdentifierType) { String lookup = lookupTypeForID(((IdentifierExp) e).s); if (lookup == null) { System.out.println("Error: (Line " + e.line_number + ") " + (((IdentifierExp) e).s) + " is an undeclared variable."); errorCounter++; } else if (!((IdentifierType) t).s.equals(lookup)) { System.out.println("Error: (line " + e.line_number + ") return types don't match."); errorCounter++; } } else { // some sort of error } } } // Type t; // Identifier i; public void visit(Formal n) { n.t.accept(this); n.i.accept(this); } public void visit(IntArrayType n) { } public void visit(BooleanType n) { } public void visit(IntegerType n) { } // String s; public void visit(IdentifierType n) { } // StatementList sl; public void visit(Block n) { for ( int i = 0; i < n.sl.size(); i++ ) { n.sl.get(i).accept(this); } } private boolean isArithmeticExpression(Exp e, boolean printError) { if (e instanceof Plus) { return isArithmeticExpression(((Plus) e).e1, true) && isArithmeticExpression(((Plus) e).e2, true); } else if (e instanceof Minus) { return isArithmeticExpression(((Minus) e).e1, true) && isArithmeticExpression(((Minus) e).e2, true); } else if (e instanceof Times) { return isArithmeticExpression(((Times) e).e1, true) && isArithmeticExpression(((Times) e).e2, true); } else if (e instanceof IntegerLiteral) { return true; } else if (e instanceof IdentifierExp) { return isVariableDefined(currentClass, currentMethod, e, "integer"); } else if (e instanceof Call) { return isCall(((Call) e).e, ((Call) e).i, ((Call) e).el, "integer", printError); } else if (e instanceof ArrayLookup) { if (((ArrayLookup) e).e1 instanceof Call) { Call c = ((Call) ((ArrayLookup) e).e1); return isCall(c.e, c.i, c.el, "intArray", true) && isArithmeticExpression(((ArrayLookup) e).e2, true); } else if (((ArrayLookup) e).e1 instanceof IdentifierExp) { IdentifierExp ie = ((IdentifierExp) ((ArrayLookup) e).e1); return isVariableDefined(currentClass, currentMethod, ie, "intArray") && isArithmeticExpression(((ArrayLookup) e).e2, true); } return false; } else if (e instanceof ArrayLength) { // a . length if (((ArrayLength) e).e instanceof Call) { Call c = ((Call) ((ArrayLength) e).e); return isCall(c.e, c.i, c.el, "intArray", true); } else if (((ArrayLength) e).e instanceof IdentifierExp) { IdentifierExp ie = ((IdentifierExp) ((ArrayLength) e).e); return isVariableDefined(currentClass, currentMethod, ie, "intArray"); } return false; } return false; } private boolean isBooleanExpression(Exp e) { if (e instanceof And) { return isBooleanExpression(((And) e).e1) && isBooleanExpression(((And) e).e2); } else if (e instanceof LessThan) { return isArithmeticExpression(((LessThan) e).e1, true) && isArithmeticExpression(((LessThan) e).e2, true); } else if (e instanceof Not) { return isBooleanExpression(((Not) e).e); } else if (e instanceof True) { return true; } else if (e instanceof False) { return true; } else if (e instanceof IdentifierExp) { return isVariableDefined(currentClass, currentMethod, e, "boolean"); } else if (e instanceof Call) { return isCall(((Call)e).e, ((Call)e).i, ((Call)e).el, "boolean", false); } return false; } private String isCallHelper(Exp exp, Identifier id, ExpList expList) { if (exp instanceof Call) { String classname = isCallHelper(((Call)exp).e,((Call)exp).i,((Call)exp).el); if (classname == null || !isExtendedFrom(classname, id.s)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Method: " + id.s + " does not exist in scope"); return null; } return getMethodType(classname, id, expList); } else if (exp instanceof IdentifierExp) { String variableClass = lookupTypeForID(((IdentifierExp) exp).s); if (variableClass == null) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Variable: " + ((IdentifierExp) exp).s + " does not exist in scope"); return null; } if (!isExtendedFrom(variableClass, id.s)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Method: " + id.s + " not in scope of " + variableClass); return null; } return getMethodType(variableClass, id, expList); } else if (exp instanceof This) { if (!isExtendedFrom(currentClass, id.s)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Method: " + id.s + " not in scope of current class"); return null; } return getMethodType(currentClass, id, expList); } else if (exp instanceof NewObject) { if(!typeTable.types.containsKey(((NewObject) exp).i.s)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Class: " + ((NewObject) exp).i.s + " does not exist in scope"); return null; } return getMethodType(((NewObject) exp).i.s, id, expList); } else if (exp instanceof NewArray) { // MiniJava array only has the .length field. if (!isArithmeticExpression(((NewArray) exp).e, true) || !id.s.equals("length")) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Invalid Array.length call"); return null; } return "integer"; } // Should never get to this as parser would already complain. return null; } private boolean isCall(Exp exp, Identifier id, ExpList expList, String type, boolean printError) { // check 'exp' recursively to make sure that it leads to a valid exp. // - could be an identifier // - nested exp. (ex. a.b.c.d) // if its not valid return false, else.. // make sure that the id is a proper method of the class exp // make sure that the return type of exp is a type class that can call id // a.b(2,2) if (exp instanceof Call) { String classname = isCallHelper(((Call)exp).e, ((Call)exp).i, ((Call)exp).el); if (classname == null) { return false; } if (!isExtendedFrom(classname, id.s)) { return false; } return isMethodDefined(classname, id, expList, type, printError); } else if (exp instanceof IdentifierExp) { String variableClass = lookupTypeForID(((IdentifierExp) exp).s); if (variableClass == null) { if (printError) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Variable: " + ((IdentifierExp) exp).s + " does not exist in scope"); } return false; } if (!isExtendedFrom(variableClass, id.s)) { if (printError) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Method: " + id.s + " not in scope of " + variableClass); } return false; } return isMethodDefined(variableClass, id, expList, type, printError); } else if (exp instanceof This) { if (!isExtendedFrom(currentClass, id.s)) { if (printError) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Method: " + id.s + " not in scope of current class"); } return false; } return isMethodDefined(currentClass, id, expList, type, printError); } else if (exp instanceof NewObject) { if(!typeTable.types.containsKey(((NewObject) exp).i.s)) { if (printError) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") Class: " + ((NewObject) exp).i.s + " does not exist"); } return false; } return isMethodDefined(((NewObject) exp).i.s, id, expList, type, printError); } else if (exp instanceof NewArray) { // MiniJava array only has the .length field. return isArithmeticExpression(((NewArray) exp).e, true) && id.s.equals("length"); } return false; } // returns true if fieldname is found in a super class of any depth, false otherwise. private boolean fieldFoundInSuper(String fieldName, String cn) { String extendedClass = typeTable.getType(cn); if (extendedClass != null) { if (symbolTable.getClassScope(extendedClass).instanceVariableCount.containsKey(fieldName)) { return true; } return fieldFoundInSuper(fieldName, extendedClass); } return false; } private String findClassForMethodInScope(String mn, String cn) { String extendedClass = typeTable.getType(cn); if (extendedClass != null) { if (symbolTable.getClassScope(extendedClass).methodMap.containsKey(mn)) { return extendedClass; } return findClassForMethodInScope(mn, extendedClass); } return null; } private boolean isMethodDefined(String className, Identifier id, ExpList expList, String type, boolean printError) { String methodName = id.s; ClassScope cs = symbolTable.getClassScope(className); String extendedClass = findClassForMethodInScope(methodName, className); if (cs.methodMap.containsKey(methodName)) { MethodScope ms = cs.getMethodScope(methodName); if (!isDerived(type, ms.methodType)) { if (printError) { errorCounter++; System.out.println("Error: (line " + id.line_number + ") method return type invalid"); } return false; } if (ms.arguments.size() != expList.size()) { errorCounter++; System.out.println("Error: (line " + id.line_number + ") method " + methodName + " expected " + ms.arguments.size() + " arguments. " + expList.size() + " arguments given"); return false; } for (int i = 0; i < ms.arguments.size(); i++) { ArgumentType at = ms.arguments.get(i); Exp exp = expList.get(i); // string, integer, boolean if (at.type.equals("integer")) { if (!isArithmeticExpression(exp, true)) { errorCounter++; System.out.println("Error: (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (at.type.equals("boolean")) { if (!isBooleanExpression(exp)) { errorCounter++; System.out.println("Error: (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (at.type.equals("intArray")) { if (exp instanceof Call) { if(!isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, "intArray", true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if(exp instanceof IdentifierExp) { if (!isVariableDefined(className, methodName, exp, "intArray")) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (typeTable.types.containsKey(at.type)) { // identifier case if (exp instanceof Call) { return isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, at.type, printError); } else if(exp instanceof IdentifierExp) { String variableType = lookupTypeForID(((IdentifierExp) exp).s); if (!(variableType != null && isDerived(at.type, variableType))) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (exp instanceof This) { if(!isDerived(at.type, currentClass)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } } } else if (extendedClass != null) { MethodScope ms = symbolTable.getClassScope(extendedClass).getMethodScope(methodName); if (!isDerived(type, ms.methodType)) { if (printError) { errorCounter++; System.out.println("Error (line " + id.line_number + ") method return type invalid"); } return false; } if (ms.arguments.size() != expList.size()) { errorCounter++; System.out.println("Error (line " + id.line_number + ") method " + methodName + " expected " + ms.arguments.size() + " arguments. " + expList.size() + " arguments given"); return false; } for (int i = 0; i < ms.arguments.size(); i++) { ArgumentType at = ms.arguments.get(i); Exp exp = expList.get(i); // string, integer, boolean if (at.type.equals("integer")) { if (!isArithmeticExpression(exp, true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (at.type.equals("boolean")) { if (!isBooleanExpression(exp)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (at.type.equals("intArray")) { if (exp instanceof Call) { if(!isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, "intArray", true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if(exp instanceof IdentifierExp) { if (!isVariableDefined(className, methodName, exp, "intArray")) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (typeTable.types.containsKey(at.type)) { // identifier case if (exp instanceof Call) { return isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, at.type, printError); } else if(exp instanceof IdentifierExp) { String variableType = lookupTypeForID(((IdentifierExp) exp).s); if (!(variableType != null && isDerived(at.type, variableType))) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else if (exp instanceof This) { if(!isDerived(at.type, currentClass)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return false; } } } } else { errorCounter++; System.out.println("Error (line " + id.line_number + ") Method: " + id.s + " not defined in scope"); return false; } return true; } // assuming that it does exist in the SymbolTable private String getMethodType(String className, Identifier id, ExpList expList) { String methodName = id.s; String extendedClass = findClassForMethodInScope(methodName, className); MethodScope ms; if (extendedClass != null){ ms = symbolTable.getClassScope(extendedClass).getMethodScope(methodName); } else if (symbolTable.getClassScope(className).methodMap.containsKey(methodName)) { ms = symbolTable.getClassScope(className).getMethodScope(methodName); } else { errorCounter++; System.out.println("Error (line " + id.line_number + ") Method " + id.s + " not defined in scope"); return null; } if (ms.arguments.size() != expList.size()) { errorCounter++; System.out.println("Error (line " + id.line_number + ") method " + methodName + " expected " + ms.arguments.size() + " arguments. " + expList.size() + " arguments given"); return null; } for (int i = 0; i < ms.arguments.size(); i++) { ArgumentType at = ms.arguments.get(i); Exp exp = expList.get(i); if (at.type.equals("integer")) { if (!isArithmeticExpression(exp, true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if (at.type.equals("boolean")) { if (!isBooleanExpression(exp)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if (at.type.equals("intArray")) { if (exp instanceof Call) { if(!isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, "intArray", true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if(exp instanceof IdentifierExp) { if(!isVariableDefined(className, methodName, exp, "intArray")) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if (typeTable.types.containsKey(at.type)) { // identifier case if (exp instanceof Call) { if (!isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, at.type, true)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if(exp instanceof IdentifierExp) { String variableType = lookupTypeForID(((IdentifierExp) exp).s); if (!(variableType != null && isDerived(at.type, variableType))) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else if (exp instanceof This) { if(!isDerived(at.type, currentClass)) { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } else { errorCounter++; System.out.println("Error (line " + exp.line_number + ") method argument number " + i + " has type mismatch"); return null; } } } return ms.methodType; } private boolean isVariableDefined(String className, String methodName, Exp e, String type) { String id = ((IdentifierExp) e).s; ClassScope cs = symbolTable.getClassScope(className); MethodScope ms = cs.getMethodScope(methodName); for (ArgumentType at : ms.arguments) { if (at.name.equals(id)) { if (isDerived(type, at.type)) { return true; } } } //System.out.println("Classname: " + className + " Methodname: " + methodName + " ID: " + id + " Type: " + type); //System.out.println("Line number: " + e.line_number); if (ms.methodVariables.containsKey(id) && isDerived(type, ms.methodVariables.get(id))) { return true; } if (cs.variableMap.containsKey(id) && isDerived(type, cs.variableMap.get(id))) { return true; } if (fieldFoundInSuper(id, className)) { return true; } //new Exception().printStackTrace(System.out); //System.out.println("Error: (Line " + e.line_number + ") variable " + id + " is not defined."); //errorCounter++; return false; } // Exp e; // Statement s1,s2; public void visit(If n) { if (!isBooleanExpression(n.e)) { errorCounter++; System.out.println("Error: (line " + n.e.line_number + ") condition is not of type boolean"); } n.e.accept(this); n.s1.accept(this); // if true n.s2.accept(this); } // Exp e; // Statement s; public void visit(While n) { if (!isBooleanExpression(n.e)) { errorCounter++; System.out.println("Error: (line " + n.e.line_number + ") conditional not boolean"); } n.e.accept(this); n.s.accept(this); } // Exp e; public void visit(Print n) { if (!isArithmeticExpression(n.e, true)) { System.out.println("Error: (line " + n.e.line_number + ") print applied to non-int expression or print expression invalid."); errorCounter++; } n.e.accept(this); } // Identifier i; // Exp e; public void visit(Assign n) { n.i.accept(this); String lookup = lookupTypeForID(n.i.s); if (lookup == null) { System.out.println("Error: (line " + n.i.line_number + ") " + n.i.s + " is undeclared."); errorCounter++; } else { if (!areEqualTypes(n.e, lookup)) { errorCounter++; System.out.println("Error: (line " + n.i.line_number + ") types do not match."); } } n.e.accept(this); } private String lookupTypeForID(String id) { // is id a variable declared in this class and method? String type = symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).getVariableType(id); if (type == null) { // is id a variable declared as a parameter of this method, in this class type = symbolTable.getClassScope(currentClass).getMethodScope(currentMethod).getParameterType(id); if (type == null) { // is id declared as a field of this class? type = symbolTable.getClassScope(currentClass).getVariableType(id); if (type == null) { // is id declared in any superclass? return findFieldInSuperClass(id, currentClass); } } } return type; } // checks to see if a id is a field from a super class of any depth private String findFieldInSuperClass(String id, String className) { String superClass = typeTable.getType(className); if (superClass != null) { // className extends superClass // check to see if that superClass has a field 'id' if (symbolTable.getClassScope(superClass).variableMap.containsKey(id)) { // check to see if that superClass has a field 'id' // if it does, return that class return symbolTable.getClassScope(superClass).getVariableType(id); } else { // if not keep looking return findFieldInSuperClass(id, superClass); } } // superClass is null return symbolTable.getClassScope(className).variableMap.containsKey(id) ? symbolTable.getClassScope(className).getVariableType(id): null; } // RHS LHS private boolean areEqualTypes(Exp exp, String type) { if (type.equals("boolean")) { return isBooleanExpression(exp); } else if (type.equals("integer")) { return isArithmeticExpression(exp, false); } else if (type.equals("intArray")) { if (exp instanceof Call) { return isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, type, false); } else if (exp instanceof IdentifierExp) { return isVariableDefined(currentClass, currentMethod, exp, type); } else if (exp instanceof NewArray) { return isArithmeticExpression(((NewArray) exp).e, false); } return false; } else if (typeTable.types.containsKey(type)) { if (exp instanceof Call) { return isCall(((Call) exp).e, ((Call) exp).i, ((Call) exp).el, type, false); } else if (exp instanceof IdentifierExp) { return isDerived(type, lookupTypeForID(((IdentifierExp) exp).s)); } else if (exp instanceof NewObject) { return isDerived(type, ((NewObject) exp).i.s); } else if (exp instanceof This) { return isDerived(type, currentClass); } return false; } return false; } // argument type variable type private boolean isDerived(String leftAssign, String rightAssign) { if (leftAssign.equals(rightAssign)) { return true; } String superType = typeTable.getType(rightAssign); if (superType != null) { return isDerived(leftAssign, superType); } return false; } // ... private boolean isExtendedFrom(String className, String methodName) { if (!symbolTable.getClassScope(className).methodMap.containsKey(methodName)) { // check for extended class String extendedClass = typeTable.getType(className); if (extendedClass != null) { return isExtendedFrom(extendedClass, methodName); } else { // no extended class return false; } } return true; } private boolean checkLoopInheritance(String className, Set<String> visitedClasses) { if (visitedClasses.contains(className)) { // already visited this class System.out.println("Error: Class inheritance loop detected with " + className); return false; } else { visitedClasses.add(className); } // check for extended class String extendedClass = typeTable.getType(className); if (extendedClass != null) { return checkLoopInheritance(extendedClass, visitedClasses); } else { // no extended class return true; } } // Identifier i; // Exp e1,e2; public void visit(ArrayAssign n) { n.i.accept(this); if (!(lookupTypeForID(n.i.s).equals("intArray") && isArithmeticExpression(n.e1, true) && isArithmeticExpression(n.e2, true))) { errorCounter++; System.out.println("Error: (line " + n.i.line_number + ") array assign failed"); } n.e1.accept(this); n.e2.accept(this); } // Exp e1,e2; public void visit(And n) { n.e1.accept(this); if (!(isBooleanExpression(n.e1) && isBooleanExpression(n.e2))) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") types do not match"); } n.e2.accept(this); } // Exp e1,e2; public void visit(LessThan n) { n.e1.accept(this); if (!(isArithmeticExpression(n.e1, true) && isArithmeticExpression(n.e2, true))) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") types do not match"); } n.e2.accept(this); } // Exp e1,e2; public void visit(Plus n) { n.e1.accept(this); if (!(isArithmeticExpression(n.e1, true) && isArithmeticExpression(n.e2, true))) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") types do not match"); } n.e2.accept(this); } // Exp e1,e2; public void visit(Minus n) { n.e1.accept(this); if (!(isArithmeticExpression(n.e1, true) && isArithmeticExpression(n.e2, true))) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") types do not match"); } n.e2.accept(this); } // Exp e1,e2; public void visit(Times n) { n.e1.accept(this); if (!(isArithmeticExpression(n.e1, true) && isArithmeticExpression(n.e2, true))) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") types do not match"); } n.e2.accept(this); } // Exp e1,e2; public void visit(ArrayLookup n) { if (!isArray(n)) { errorCounter++; System.out.println("Error: (line " + n.e1.line_number + ") array described is not valid"); } n.e1.accept(this); if (!isArithmeticExpression(n.e2, true)) { errorCounter++; System.out.println("Error: (line " + n.e2.line_number + ") expression in bracket is not of integer type"); } n.e2.accept(this); } // Exp e; public void visit(ArrayLength n) { if (!isArrayLength(n.e)) { errorCounter++; System.out.println("Error: (line " + n.e.line_number + ") array described is not valid"); } n.e.accept(this); } private boolean isArrayLength(Exp exp) { if (exp instanceof Call) { Call c = ((Call) exp); return isCall(c.e, c.i, c.el, "intArray", true); } else if (exp instanceof IdentifierExp) { IdentifierExp ie = ((IdentifierExp) exp); return isVariableDefined(currentClass, currentMethod, ie, "intArray"); } return false; } private boolean isArray(ArrayLookup arr) { if (arr.e1 instanceof Call) { Call c = ((Call) arr.e1); return isCall(c.e, c.i, c.el, "intArray", true) && isArithmeticExpression(arr.e2, true); } else if (arr.e1 instanceof IdentifierExp) { IdentifierExp ie = ((IdentifierExp) arr.e1); return isVariableDefined(currentClass, currentMethod, ie, "intArray") && isArithmeticExpression(arr.e2, true); } return false; } // Exp e; // Identifier i; // ExpList el; public void visit(Call n) { isCallHelper(n.e, n.i, n.el); n.e.accept(this); n.i.accept(this); for ( int i = 0; i < n.el.size(); i++ ) { n.el.get(i).accept(this); } } // int i; public void visit(IntegerLiteral n) { } public void visit(True n) { } public void visit(False n) { } // String s; public void visit(IdentifierExp n) { } public void visit(This n) { } // Exp e; public void visit(NewArray n) { if (!isArithmeticExpression(n.e, true)) { errorCounter++; System.out.println("Error: (line " + n.e.line_number + ") expression not of type integer."); } n.e.accept(this); } // Identifier i; public void visit(NewObject n) { if (symbolTable.getClassScope(n.i.s) == null) { errorCounter++; System.out.println("Error: (line " + n.i.line_number + ") class not found."); } } // Exp e; public void visit(Not n) { if (!(isBooleanExpression(n.e))) { errorCounter++; System.out.println("Error: (line " + n.e.line_number + ") not boolean expression"); } n.e.accept(this); } // String s; public void visit(Identifier n) { } }
package com.one.sugarcane.sellerloginlog.dao; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import org.springframework.stereotype.Repository; import com.one.sugarcane.entity.SellerLoginLog; @Repository public class SellerLoginLogDaoImpl { @Resource private SessionFactory sessionFactory; }
package com.example.healthmanage.ui.activity.temperature.adapter; import android.content.Context; import android.widget.ImageView; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.healthmanage.R; import com.example.healthmanage.ui.activity.temperature.response.TemperatureResponse; import java.util.List; public class GridPictureAdapter extends BaseQuickAdapter<TemperatureResponse.DataBean.ListBean, BaseViewHolder> { Context mContext; public GridPictureAdapter(Context context ,@Nullable List<TemperatureResponse.DataBean.ListBean> data) { super(R.layout.item_patient_picture,data); this.mContext = context; } @Override protected void convert(BaseViewHolder helper, TemperatureResponse.DataBean.ListBean item) { Glide.with(mContext).load(item.getUrl()).apply(new RequestOptions().placeholder(R.drawable.ic_size_seat).error(R.drawable.ic_size_seat)) .into((ImageView) helper.getView(R.id.iv_patient_pic)); } }
package org.jlb.plongee.datamodel; import org.jlb.tools.metamodel.Entity; /** * Classe décrivant un logbook. * * @author JLuc * */ public class LogBook extends Entity { /** * */ public LogBook() { // TODO Auto-generated constructor stub } }
package com.im; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.channels.ServerSocketChannel; public class Test { public static void main(String[] args) { String port = "5230"; int num = Runtime.getRuntime().availableProcessors(); Processor[] processors = new Processor[num]; RequestChannel requestChannel = new RequestChannel(4, 1000); for (int i = 0; i < num; i++) { processors[i] = new Processor(i, 1000, 4, requestChannel,1000); Utils.newThread("kafka-network-thread-%d-%d".format(port, i), processors[i], false).start(); } } }